Skip to main content

sprite/commands/
init.rs

1use crate::error::SpriteError;
2use anyhow::{Context, Result};
3use std::fs;
4use std::path::{Path, PathBuf};
5use std::process::Command;
6use std::time::Instant;
7
8#[cfg(unix)]
9use std::os::unix::fs::PermissionsExt;
10
11pub struct InitOptions {
12    pub force: bool,
13    pub agents: u32,
14}
15
16pub fn execute(options: InitOptions) -> Result<()> {
17    let start_time = Instant::now();
18
19    println!("🚀 Initializing Sprite multi-agent environment...");
20
21    // Step 1: Ensure git repository exists
22    ensure_git_repository()?;
23
24    // T028: Handle edge case - existing configuration
25    let agents_dir = PathBuf::from("agents");
26    let config_file = agents_dir.join("agents.yaml");
27
28    if config_file.exists() && !options.force {
29        return Err(SpriteError::config(
30            "Configuration file already exists. Use --force to overwrite.",
31        )
32        .into());
33    }
34
35    // Step 2: Create directory structure (only scripts and profiles, not agent dirs)
36    create_base_directory_structure(&agents_dir)?;
37
38    // Step 3: Ensure we have an initial commit before creating branches/worktrees
39    ensure_initial_commit_for_worktrees()?;
40
41    // Step 4: Create agent branches and worktrees (BEFORE config to avoid copying)
42    if options.agents > 0 {
43        setup_agent_worktrees(options.agents)?;
44    }
45
46    // Step 5: Generate configuration file (AFTER worktrees to avoid nested copies)
47    generate_agents_config(&config_file, options.agents)?;
48
49    // Step 5: Create shell script templates
50    create_shell_script_templates(&agents_dir)?;
51
52    // Step 6: Create tmux profile templates
53    create_tmux_profile_templates(&agents_dir)?;
54
55    // Step 7: Create .envrc for direnv if direnv is available
56    create_direnv_config(&agents_dir)?;
57
58    // Step 8: Commit configuration to git
59    ensure_initial_commit(&agents_dir)?;
60
61    let duration = start_time.elapsed();
62    println!(
63        "✅ Sprite environment initialized successfully in {:.1}s!",
64        duration.as_secs_f64()
65    );
66    println!();
67    println!("📁 Created directories:");
68    println!("   agents/");
69    println!("   agents/scripts/");
70    println!("   agents/profiles/");
71    println!();
72    println!("📄 Generated configuration:");
73    println!("   agents/agents.yaml");
74    println!();
75
76    if options.agents > 0 {
77        println!("🤖 Configured {} agents:", options.agents);
78        for i in 1..=options.agents {
79            println!("   Agent {}: agents/{}", i, i);
80        }
81    } else {
82        println!("🤖 No agents configured (empty setup)");
83    }
84    println!();
85
86    println!("đŸŽ¯ Next steps:");
87    if options.agents > 0 {
88        println!("   1. Review agents/agents.yaml and customize agent configurations");
89        println!("   2. Run 'sprite start' to begin supervision session");
90    } else {
91        println!("   1. Add agents using 'sprite agents create <id>'");
92        println!("   2. Or edit agents/agents.yaml manually");
93        println!("   3. Run 'sprite start' when ready");
94    }
95    println!();
96    println!("💡 Pro tip: Everything is ready! You can start coding immediately.");
97
98    Ok(())
99}
100
101/// Ensure git repository exists, initialize if needed
102fn ensure_git_repository() -> Result<()> {
103    // Check if .git exists
104    if !PathBuf::from(".git").exists() {
105        println!("đŸ“Ļ No git repository found. Initializing...");
106        let output = Command::new("git")
107            .args(["init"])
108            .output()
109            .context("Failed to run git init")?;
110
111        if !output.status.success() {
112            anyhow::bail!("Failed to initialize git repository");
113        }
114        println!("   ✅ Git repository initialized");
115    } else {
116        println!("   ✅ Git repository detected");
117    }
118
119    Ok(())
120}
121
122/// Ensure initial commit exists for worktree creation
123fn ensure_initial_commit_for_worktrees() -> Result<()> {
124    // Check if there are any commits
125    let has_commits = Command::new("git")
126        .args(["rev-parse", "HEAD"])
127        .output()
128        .map(|o| o.status.success())
129        .unwrap_or(false);
130
131    if !has_commits {
132        println!("   📌 No commits found. Creating initial commit...");
133
134        // Ensure git user is configured
135        ensure_git_user_configured()?;
136
137        // Create a simple initial commit
138        let output = Command::new("git")
139            .args([
140                "commit",
141                "--allow-empty",
142                "-m",
143                "Initial commit for sprite worktrees",
144            ])
145            .output()
146            .context("Failed to create initial commit")?;
147
148        if output.status.success() {
149            println!("   ✅ Initial commit created");
150        } else {
151            let stderr = String::from_utf8_lossy(&output.stderr);
152            anyhow::bail!("Failed to create initial commit: {}", stderr);
153        }
154    }
155
156    Ok(())
157}
158
159/// Ensure at least one commit exists
160fn ensure_initial_commit(agents_dir: &Path) -> Result<()> {
161    println!("📝 Setting up git commit...");
162
163    // Check if there are any commits
164    let has_commits = Command::new("git")
165        .args(["rev-parse", "HEAD"])
166        .output()
167        .map(|o| o.status.success())
168        .unwrap_or(false);
169
170    if !has_commits {
171        println!("   📌 No commits found. Creating initial commit...");
172
173        // Ensure git user is configured (needed for commits in CI)
174        ensure_git_user_configured()?;
175    } else {
176        println!("   📌 Adding agents configuration...");
177    }
178
179    // Stage agents directory
180    let output = Command::new("git")
181        .args(["add", agents_dir.to_str().unwrap()])
182        .output()
183        .context("Failed to stage agents directory")?;
184
185    if !output.status.success() {
186        anyhow::bail!("Failed to stage agents directory");
187    }
188
189    // If there are no commits, we MUST create one (branches need a commit)
190    // If there are commits, check if there's anything to commit
191    if has_commits {
192        let status_output = Command::new("git")
193            .args(["status", "--porcelain"])
194            .output()
195            .context("Failed to check git status")?;
196
197        if status_output.stdout.is_empty() {
198            println!("   â„šī¸  No changes to commit");
199            return Ok(());
200        }
201    }
202
203    // Commit
204    let output = Command::new("git")
205        .args(["commit", "-m", "Initialize Sprite multi-agent environment"])
206        .output()
207        .context("Failed to create commit")?;
208
209    if output.status.success() {
210        println!("   ✅ Changes committed");
211    } else {
212        let stderr = String::from_utf8_lossy(&output.stderr);
213        anyhow::bail!("Failed to create commit: {}", stderr);
214    }
215
216    Ok(())
217}
218
219/// Ensure git user is configured (for CI environments)
220fn ensure_git_user_configured() -> Result<()> {
221    // Check if user.name is set
222    let name_check = Command::new("git")
223        .args(["config", "user.name"])
224        .output()
225        .map(|o| o.status.success() && !o.stdout.is_empty())
226        .unwrap_or(false);
227
228    if !name_check {
229        // Set a default user name
230        Command::new("git")
231            .args(["config", "user.name", "Sprite"])
232            .output()
233            .context("Failed to set git user.name")?;
234    }
235
236    // Check if user.email is set
237    let email_check = Command::new("git")
238        .args(["config", "user.email"])
239        .output()
240        .map(|o| o.status.success() && !o.stdout.is_empty())
241        .unwrap_or(false);
242
243    if !email_check {
244        // Set a default user email
245        Command::new("git")
246            .args(["config", "user.email", "sprite@localhost"])
247            .output()
248            .context("Failed to set git user.email")?;
249    }
250
251    Ok(())
252}
253
254/// Create agent branches and worktrees
255fn setup_agent_worktrees(agent_count: u32) -> Result<()> {
256    println!("đŸŒŗ Setting up agent worktrees...");
257
258    // First, prune any stale worktree entries
259    // Run this twice to ensure all stale entries are removed
260    prune_stale_worktrees()?;
261    prune_stale_worktrees()?;
262
263    for i in 1..=agent_count {
264        let branch_name = format!("agents/{}", i);
265        let worktree_path = format!("agents/{}", i);
266
267        // Check if worktree is already registered
268        if is_worktree_registered(&worktree_path)? {
269            println!(
270                "   â„šī¸  Worktree {} already registered, removing...",
271                worktree_path
272            );
273            remove_worktree(&worktree_path)?;
274        }
275
276        // Create branch if it doesn't exist
277        println!("   🔀 Creating branch: {}", branch_name);
278        let branch_exists = Command::new("git")
279            .args(["rev-parse", "--verify", &branch_name])
280            .output()
281            .map(|o| o.status.success())
282            .unwrap_or(false);
283
284        if !branch_exists {
285            let output = Command::new("git")
286                .args(["branch", &branch_name])
287                .output()
288                .context("Failed to create branch")?;
289
290            if !output.status.success() {
291                anyhow::bail!("Failed to create branch: {}", branch_name);
292            }
293        }
294
295        // Remove placeholder directory if it exists
296        let worktree_dir = PathBuf::from(&worktree_path);
297        if worktree_dir.exists() {
298            fs::remove_dir_all(&worktree_dir).with_context(|| {
299                format!("Failed to remove placeholder directory: {}", worktree_path)
300            })?;
301        }
302
303        // Create worktree (with force flag to override any stale entries)
304        println!("   📁 Creating worktree: {}", worktree_path);
305        let mut cmd = Command::new("git");
306        cmd.args(["worktree", "add"]);
307
308        // Try with --force flag first to handle edge cases
309        cmd.arg("--force");
310        cmd.args([&worktree_path, &branch_name]);
311
312        let output = cmd.output().context("Failed to create worktree")?;
313
314        if !output.status.success() {
315            let stderr = String::from_utf8_lossy(&output.stderr);
316            anyhow::bail!("Failed to create worktree {}: {}", worktree_path, stderr);
317        }
318        println!("   ✅ Agent {} worktree ready", i);
319    }
320
321    // Show worktree list
322    println!();
323    println!("📋 Git worktree status:");
324    let output = Command::new("git")
325        .args(["worktree", "list"])
326        .output()
327        .context("Failed to list worktrees")?;
328
329    if output.status.success() {
330        let worktrees = String::from_utf8_lossy(&output.stdout);
331        for line in worktrees.lines() {
332            println!("   {}", line);
333        }
334    }
335
336    Ok(())
337}
338
339/// Prune stale worktree entries
340fn prune_stale_worktrees() -> Result<()> {
341    let output = Command::new("git")
342        .args(["worktree", "prune"])
343        .output()
344        .context("Failed to prune worktrees")?;
345
346    if !output.status.success() {
347        let stderr = String::from_utf8_lossy(&output.stderr);
348        // Don't fail on prune errors, just warn
349        println!("   âš ī¸  Warning: Failed to prune worktrees: {}", stderr);
350    }
351
352    Ok(())
353}
354
355/// Check if a worktree is registered
356fn is_worktree_registered(path: &str) -> Result<bool> {
357    let output = Command::new("git")
358        .args(["worktree", "list", "--porcelain"])
359        .output()
360        .context("Failed to list worktrees")?;
361
362    if !output.status.success() {
363        return Ok(false);
364    }
365
366    let worktree_list = String::from_utf8_lossy(&output.stdout);
367    // Check if the path appears in the worktree list
368    Ok(worktree_list.contains(&format!("worktree {}", path)))
369}
370
371/// Remove a worktree registration
372fn remove_worktree(path: &str) -> Result<()> {
373    let output = Command::new("git")
374        .args(["worktree", "remove", path, "--force"])
375        .output()
376        .context("Failed to remove worktree")?;
377
378    if !output.status.success() {
379        let stderr = String::from_utf8_lossy(&output.stderr);
380        // If remove fails, the worktree might not exist - that's okay
381        println!("   âš ī¸  Warning: {}", stderr);
382    }
383
384    Ok(())
385}
386
387/// Create base directory structure (without agent directories)
388fn create_base_directory_structure(agents_dir: &Path) -> Result<()> {
389    println!("📁 Creating directory structure...");
390
391    // Create main agents directory
392    fs::create_dir_all(agents_dir).context("Failed to create agents directory")?;
393
394    // Create .gitignore to prevent recursive copying
395    let gitignore_content = r"# Prevent git worktrees from copying this directory recursively
396# This file prevents the agents/ directory from being copied into agent worktrees
397
398# Ignore everything except this file
399/*
400!/.gitignore
401";
402    fs::write(agents_dir.join(".gitignore"), gitignore_content)
403        .context("Failed to create .gitignore in agents directory")?;
404
405    // Create scripts directory
406    let scripts_dir = agents_dir.join("scripts");
407    fs::create_dir_all(&scripts_dir).context("Failed to create scripts directory")?;
408
409    // Create profiles directory
410    let profiles_dir = agents_dir.join("profiles");
411    fs::create_dir_all(&profiles_dir).context("Failed to create profiles directory")?;
412
413    println!("   ✅ Base directories created");
414
415    Ok(())
416}
417
418fn generate_agents_config(config_file: &Path, agent_count: u32) -> Result<()> {
419    println!("📝 Generating configuration file...");
420
421    if agent_count == 0 {
422        // Warn user about zero agents
423        println!("   âš ī¸  Warning: Initializing with 0 agents");
424        println!("   💡 You can add agents later using 'sprite agents create <id>'");
425        println!();
426    }
427
428    let config = if agent_count == 0 {
429        // Empty configuration template with updated schema
430        include_str!("../templates/empty_agents.yaml").to_string()
431    } else {
432        // Generate configuration with agents
433        generate_config_content(agent_count)?
434    };
435
436    fs::write(config_file, config).context("Failed to write agents.yaml configuration")?;
437
438    Ok(())
439}
440
441fn generate_config_content(agent_count: u32) -> Result<String> {
442    let mut config = String::new();
443
444    config.push_str("# Sprite Multi-Agent Configuration\n");
445    config.push_str("# Generated automatically by 'sprite init'\n");
446    config.push_str("# Customize this file to match your project needs\n\n");
447
448    config.push_str("version: \"1.0\"\n\n");
449
450    config.push_str("agents:\n");
451    for i in 1..=agent_count {
452        config.push_str(&format!("- id: '{}'\n", i));
453        config.push_str(&format!("  branch: agents/{}\n", i));
454        config.push_str(&format!("  worktree_path: agents/{}\n", i));
455        config.push_str("  model: claude-sonnet-4\n");
456        config.push_str(&format!("  description: Agent {} workspace\n", i));
457        config.push_str("  status: Inactive\n");
458        config.push_str("  config:\n");
459        config.push_str("    env_vars: {}\n");
460        config.push_str("    work_dir: null\n");
461        config.push_str("    startup_commands: []\n");
462        config.push_str("    resource_limits:\n");
463        config.push_str("      max_memory_mb: 1024\n");
464        config.push_str("      max_cpu_percent: 80\n");
465        config.push_str("      operation_timeout_secs: 300\n");
466        config.push_str("      max_concurrent_ops: 3\n");
467        config.push_str("      max_disk_mb: 5120\n");
468        config.push_str("    shell: null\n");
469        config.push_str("    default_timeout_secs: 300\n");
470        config.push_str("    auto_sync: false\n");
471        config.push_str("    custom_settings: {}\n");
472    }
473
474    config.push_str("session_name: sprite-session\n");
475
476    config.push_str("sync:\n");
477    config.push_str("  auto_sync: false\n");
478    config.push_str("  default_interval_secs: 300\n");
479    config.push_str("  conflict_resolution: Manual\n");
480    config.push_str("  exclude_branches:\n");
481    config.push_str("  - main\n");
482    config.push_str("  - master\n");
483    config.push_str("  pre_sync_hooks: []\n");
484    config.push_str("  post_sync_hooks: []\n");
485
486    config.push_str("settings:\n");
487    config.push_str("  default_shell: bash\n");
488    config.push_str("  global_env_vars: {}\n");
489    config.push_str("  logging:\n");
490    config.push_str("    log_file: agents/logs/sprite.log\n");
491    config.push_str("    level: Info\n");
492    config.push_str("    log_to_stdout: true\n");
493    config.push_str("    rotation:\n");
494    config.push_str("      max_size_mb: 100\n");
495    config.push_str("      max_files: 5\n");
496    config.push_str("  performance:\n");
497    config.push_str("    max_concurrent_ops: 10\n");
498    config.push_str("    default_timeout_secs: 300\n");
499    config.push_str("    enable_monitoring: true\n");
500    config.push_str("    memory_limit_mb: 1024\n");
501    config.push_str("    cpu_limit_percent: 80\n");
502    config.push_str("  security:\n");
503    config.push_str("    allowed_paths:\n");
504    config.push_str("    - agents/\n");
505    config.push_str("    blocked_commands:\n");
506    config.push_str("    - rm -rf\n");
507    config.push_str("    - sudo\n");
508    config.push_str("    - su\n");
509    config.push_str("    - chmod 777\n");
510    config.push_str("    strict_path_validation: true\n");
511    config.push_str("    max_command_length: 1000\n");
512    config.push_str("    allow_shell_execution: false\n");
513
514    Ok(config)
515}
516
517fn create_shell_script_templates(agents_dir: &Path) -> Result<()> {
518    println!("🔧 Creating shell script templates...");
519
520    let scripts_dir = agents_dir.join("scripts");
521
522    // Create setup.sh script
523    let setup_script = include_str!("../templates/setup.sh");
524    fs::write(scripts_dir.join("setup.sh"), setup_script)?;
525
526    // Make scripts executable
527    #[cfg(unix)]
528    {
529        use std::os::unix::fs::PermissionsExt;
530        let mut perms = fs::metadata(scripts_dir.join("setup.sh"))?.permissions();
531        perms.set_mode(0o755);
532        fs::set_permissions(scripts_dir.join("setup.sh"), perms)?;
533    }
534
535    // Create start-agents.sh script
536    let start_script = include_str!("../templates/start-agents.sh");
537    fs::write(scripts_dir.join("start-agents.sh"), start_script)?;
538
539    #[cfg(unix)]
540    {
541        let mut perms = fs::metadata(scripts_dir.join("start-agents.sh"))?.permissions();
542        perms.set_mode(0o755);
543        fs::set_permissions(scripts_dir.join("start-agents.sh"), perms)?;
544    }
545
546    // Create attach-session.sh script
547    let attach_script = include_str!("../templates/attach-session.sh");
548    fs::write(scripts_dir.join("attach-session.sh"), attach_script)?;
549
550    #[cfg(unix)]
551    {
552        let mut perms = fs::metadata(scripts_dir.join("attach-session.sh"))?.permissions();
553        perms.set_mode(0o755);
554        fs::set_permissions(scripts_dir.join("attach-session.sh"), perms)?;
555    }
556
557    Ok(())
558}
559
560fn create_tmux_profile_templates(agents_dir: &Path) -> Result<()> {
561    println!("đŸ–ŧī¸  Creating tmux profile templates...");
562
563    let profiles_dir = agents_dir.join("profiles");
564
565    // Profile 0: Top + split bottom (2-3 agents)
566    let profile0 = include_str!("../templates/profile0.sh");
567    fs::write(profiles_dir.join("profile0.sh"), profile0)?;
568
569    // Profile 1: Left column + stacked right
570    let profile1 = include_str!("../templates/profile1.sh");
571    fs::write(profiles_dir.join("profile1.sh"), profile1)?;
572
573    // Profile 2: Top row + full-width bottom
574    let profile2 = include_str!("../templates/profile2.sh");
575    fs::write(profiles_dir.join("profile2.sh"), profile2)?;
576
577    // Profile 3: Single full-width top (focus mode)
578    let profile3 = include_str!("../templates/profile3.sh");
579    fs::write(profiles_dir.join("profile3.sh"), profile3)?;
580
581    // Profile 4: Three-pane layout
582    let profile4 = include_str!("../templates/profile4.sh");
583    fs::write(profiles_dir.join("profile4.sh"), profile4)?;
584
585    // Profile 5: Six-pane dashboard
586    let profile5 = include_str!("../templates/profile5.sh");
587    fs::write(profiles_dir.join("profile5.sh"), profile5)?;
588
589    // Make all profile scripts executable
590    #[cfg(unix)]
591    {
592        use std::os::unix::fs::PermissionsExt;
593        for i in 0..=5 {
594            let profile_file = profiles_dir.join(format!("profile{}.sh", i));
595            if profile_file.exists() {
596                let mut perms = fs::metadata(&profile_file)?.permissions();
597                perms.set_mode(0o755);
598                fs::set_permissions(&profile_file, perms)?;
599            }
600        }
601    }
602
603    Ok(())
604}
605
606fn create_direnv_config(agents_dir: &Path) -> Result<()> {
607    // Check if direnv is available
608    let direnv_available = std::process::Command::new("direnv")
609        .arg("version")
610        .output()
611        .is_ok();
612
613    if !direnv_available {
614        return Ok(()); // Skip if direnv is not available
615    }
616
617    println!("🔌 Creating direnv configuration...");
618
619    let envrc_content = r#"# Sprite Multi-Agent Environment Configuration
620# Generated automatically by 'sprite init'
621
622# Load common environment variables
623export SPRITE_ENV="development"
624export SPRITE_AGENTS_DIR="$(pwd)/agents"
625
626# Add scripts to PATH
627export PATH="$SPRITE_AGENTS_DIR/scripts:$PATH"
628
629# Common aliases for sprite commands
630alias sa='sprite attach'
631alias ss='sprite start'
632alias sk='sprite kill'
633alias sw='sprite warp'
634alias sz='sprite zoom'
635
636# Auto-load environment when entering agent directories
637layout_dir agents
638"#;
639
640    fs::write(".envrc", envrc_content)?;
641
642    // Also create .envrc in agents directory
643    let agents_envrc = r#"# Sprite Agents Environment
644# Generated automatically by 'sprite init'
645
646export SPRITE_AGENT_DIR="$(pwd)"
647"#;
648
649    fs::write(agents_dir.join(".envrc"), agents_envrc)?;
650
651    println!("   Created .envrc files for direnv");
652
653    Ok(())
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659    use std::fs;
660    use tempfile::TempDir;
661
662    #[test]
663    fn test_create_base_directory_structure() {
664        let temp_dir = TempDir::new().unwrap();
665        let agents_dir = temp_dir.path().join("agents");
666
667        let result = create_base_directory_structure(&agents_dir);
668
669        assert!(result.is_ok());
670        assert!(agents_dir.exists());
671        assert!(agents_dir.join("scripts").exists());
672        assert!(agents_dir.join("profiles").exists());
673        // Agent directories are NOT created by this function anymore
674        assert!(!agents_dir.join("1").exists());
675        assert!(!agents_dir.join("2").exists());
676        assert!(!agents_dir.join("3").exists());
677    }
678
679    #[test]
680    fn test_create_base_directory_structure_idempotent() {
681        let temp_dir = TempDir::new().unwrap();
682        let agents_dir = temp_dir.path().join("agents");
683
684        // Call twice to ensure it's idempotent
685        let result1 = create_base_directory_structure(&agents_dir);
686        let result2 = create_base_directory_structure(&agents_dir);
687
688        assert!(result1.is_ok());
689        assert!(result2.is_ok());
690        assert!(agents_dir.exists());
691        assert!(agents_dir.join("scripts").exists());
692        assert!(agents_dir.join("profiles").exists());
693    }
694
695    #[test]
696    fn test_create_base_directory_structure_nested() {
697        let temp_dir = TempDir::new().unwrap();
698        let agents_dir = temp_dir.path().join("agents");
699
700        let result = create_base_directory_structure(&agents_dir);
701
702        assert!(result.is_ok());
703        assert!(agents_dir.exists());
704        assert!(agents_dir.join("scripts").exists());
705        assert!(agents_dir.join("profiles").exists());
706    }
707
708    #[test]
709    fn test_generate_config_content() {
710        let result = generate_config_content(2);
711
712        assert!(result.is_ok());
713        let config = result.unwrap();
714
715        assert!(config.contains("agents:"));
716        assert!(config.contains("- id: '1'"));
717        assert!(config.contains("- id: '2'"));
718        assert!(config.contains("session_name:"));
719        assert!(config.contains("sync:"));
720        assert!(config.contains("settings:"));
721        assert!(config.contains("version: \"1.0\""));
722        assert!(config.contains("claude-sonnet-4"));
723        assert!(config.contains("worktree_path:"));
724        assert!(config.contains("resource_limits:"));
725    }
726
727    #[test]
728    fn test_generate_config_content_many_agents() {
729        let result = generate_config_content(10);
730
731        assert!(result.is_ok());
732        let config = result.unwrap();
733
734        // Should contain all agents from 1 to 10
735        for i in 1..=10 {
736            assert!(config.contains(&format!("- id: '{}'", i)));
737        }
738        // Should not contain agent 11
739        assert!(!config.contains("- id: '11'"));
740    }
741
742    #[test]
743    fn test_generate_empty_config() {
744        let result = generate_config_content(0);
745
746        assert!(result.is_ok());
747        let config = result.unwrap();
748
749        assert!(config.contains("agents:"));
750        assert!(!config.contains("- id: '1'"));
751        assert!(config.contains("version: \"1.0\""));
752        assert!(config.contains("session_name:"));
753    }
754
755    #[test]
756    fn test_generate_agents_config() {
757        let temp_dir = TempDir::new().unwrap();
758        let config_file = temp_dir.path().join("agents.yaml");
759
760        let result = generate_agents_config(&config_file, 3);
761
762        assert!(result.is_ok());
763        assert!(config_file.exists());
764
765        let content = fs::read_to_string(&config_file).unwrap();
766        assert!(content.contains("agents:"));
767        assert!(content.contains("- id: '1'"));
768        assert!(content.contains("- id: '2'"));
769        assert!(content.contains("- id: '3'"));
770    }
771
772    #[test]
773    fn test_generate_agents_config_empty() {
774        let temp_dir = TempDir::new().unwrap();
775        let config_file = temp_dir.path().join("agents.yaml");
776
777        let result = generate_agents_config(&config_file, 0);
778
779        assert!(result.is_ok());
780        assert!(config_file.exists());
781
782        let content = fs::read_to_string(&config_file).unwrap();
783        // Should use empty template
784        assert!(!content.is_empty());
785    }
786
787    #[test]
788    fn test_create_shell_script_templates() {
789        let temp_dir = TempDir::new().unwrap();
790        let agents_dir = temp_dir.path().join("agents");
791
792        // Create the base directory structure first
793        let result = create_base_directory_structure(&agents_dir);
794        assert!(result.is_ok());
795
796        let scripts_dir = agents_dir.join("scripts");
797        assert!(scripts_dir.exists());
798
799        // Create a simple test script
800        let test_script = "#!/bin/bash\n# Test script\necho 'Hello from test script'";
801        fs::write(scripts_dir.join("test_script.sh"), test_script).unwrap();
802
803        assert!(scripts_dir.join("test_script.sh").exists());
804
805        let test_content = fs::read_to_string(scripts_dir.join("test_script.sh")).unwrap();
806        assert!(!test_content.is_empty());
807        assert!(test_content.contains("#!/bin/bash"));
808    }
809
810    #[test]
811    fn test_create_tmux_profile_templates() {
812        let temp_dir = TempDir::new().unwrap();
813        let agents_dir = temp_dir.path().join("agents");
814
815        // Create the base directory structure first
816        let result = create_base_directory_structure(&agents_dir);
817        assert!(result.is_ok());
818
819        let profiles_dir = agents_dir.join("profiles");
820        assert!(profiles_dir.exists());
821
822        // Create a simple test profile
823        let test_profile = "#!/bin/bash\n# Test tmux profile\necho 'Test tmux profile'";
824        fs::write(profiles_dir.join("test_profile.sh"), test_profile).unwrap();
825
826        assert!(profiles_dir.join("test_profile.sh").exists());
827
828        let content = fs::read_to_string(profiles_dir.join("test_profile.sh")).unwrap();
829        assert!(!content.is_empty());
830        assert!(content.contains("#!/bin/bash"));
831    }
832
833    #[test]
834    fn test_create_direnv_config() {
835        let temp_dir = TempDir::new().unwrap();
836        let agents_dir = temp_dir.path().join("agents");
837        fs::create_dir_all(&agents_dir).unwrap();
838
839        let result = create_direnv_config(&agents_dir);
840
841        assert!(result.is_ok());
842        // Should not fail even if direnv is not available
843    }
844
845    #[test]
846    fn test_init_options_struct() {
847        let options = InitOptions {
848            force: true,
849            agents: 5,
850        };
851
852        assert!(options.force);
853        assert_eq!(options.agents, 5);
854    }
855
856    #[test]
857    fn test_init_execution_with_force() {
858        let temp_dir = TempDir::new().unwrap();
859        let agents_dir = temp_dir.path().join("agents");
860        fs::create_dir_all(&agents_dir).unwrap();
861
862        // Create an existing config file
863        let config_file = agents_dir.join("agents.yaml");
864        fs::write(&config_file, "existing: config").unwrap();
865
866        let _options = InitOptions {
867            force: true,
868            agents: 2,
869        };
870
871        // Should succeed with force flag even if config exists
872        // Note: This test would require mocking git validation for full testing
873        // For now, we test the structure creation parts
874        let result = create_base_directory_structure(&agents_dir);
875        assert!(result.is_ok());
876    }
877
878    #[test]
879    fn test_init_execution_without_force_existing_config() {
880        let temp_dir = TempDir::new().unwrap();
881        let agents_dir = temp_dir.path().join("agents");
882        fs::create_dir_all(&agents_dir).unwrap();
883
884        // Create an existing config file
885        let config_file = agents_dir.join("agents.yaml");
886        fs::write(&config_file, "existing: config").unwrap();
887
888        let _options = InitOptions {
889            force: false,
890            agents: 2,
891        };
892
893        // Testing the config existence check
894        assert!(config_file.exists());
895    }
896
897    #[test]
898    fn test_config_content_structure() {
899        let result = generate_config_content(1);
900        assert!(result.is_ok());
901
902        let config = result.unwrap();
903
904        // Test YAML structure
905        assert!(config.contains("version:"));
906        assert!(config.contains("agents:"));
907        assert!(config.contains("- id:"));
908        assert!(config.contains("branch:"));
909        assert!(config.contains("model:"));
910        assert!(config.contains("description:"));
911        assert!(config.contains("worktree_path:"));
912        assert!(config.contains("status:"));
913        assert!(config.contains("config:"));
914        assert!(config.contains("resource_limits:"));
915        assert!(config.contains("session_name:"));
916        assert!(config.contains("sync:"));
917        assert!(config.contains("settings:"));
918    }
919
920    #[test]
921    fn test_config_content_default_values() {
922        let result = generate_config_content(1);
923        assert!(result.is_ok());
924
925        let config = result.unwrap();
926
927        // Test default values
928        assert!(config.contains("claude-sonnet-4"));
929        assert!(config.contains("Inactive"));
930        assert!(config.contains("max_memory_mb: 1024"));
931        assert!(config.contains("max_cpu_percent: 80"));
932        assert!(config.contains("operation_timeout_secs: 300"));
933        assert!(config.contains("max_concurrent_ops: 3"));
934        assert!(config.contains("max_disk_mb: 5120"));
935        assert!(config.contains("auto_sync: false"));
936    }
937
938    #[test]
939    fn test_config_content_security_settings() {
940        let result = generate_config_content(1);
941        assert!(result.is_ok());
942
943        let config = result.unwrap();
944
945        // Test security settings
946        assert!(config.contains("security:"));
947        assert!(config.contains("allowed_paths:"));
948        assert!(config.contains("blocked_commands:"));
949        assert!(config.contains("strict_path_validation: true"));
950        assert!(config.contains("max_command_length: 1000"));
951        assert!(config.contains("allow_shell_execution: false"));
952    }
953
954    #[test]
955    fn test_error_handling_invalid_directory() {
956        // Test with an invalid path (should handle gracefully)
957        let invalid_path = Path::new("/invalid/nonexistent/path");
958
959        // This should return an error, not panic
960        let result = create_base_directory_structure(invalid_path);
961        assert!(result.is_err());
962    }
963
964    #[test]
965    fn test_edge_case_large_agent_count() {
966        let temp_dir = TempDir::new().unwrap();
967        let agents_dir = temp_dir.path().join("agents");
968
969        // Test with a large number of agents (but we only test base structure now)
970        let result = create_base_directory_structure(&agents_dir);
971        assert!(result.is_ok());
972
973        // Verify base directories were created
974        assert!(agents_dir.join("scripts").exists());
975        assert!(agents_dir.join("profiles").exists());
976
977        // Agent directories are NOT created by this function anymore
978        // They are created by setup_agent_worktrees
979        assert!(!agents_dir.join("1").exists());
980        assert!(!agents_dir.join("100").exists());
981    }
982}