sprit-mutilagent 0.3.2

A robust command-line toolkit for managing multiple AI coding agents in isolated tmux sessions with comprehensive workspace management and health monitoring
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
use crate::error::SpriteError;
use anyhow::{Context, Result};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;

#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;

pub struct InitOptions {
    pub force: bool,
    pub agents: u32,
}

pub fn execute(options: InitOptions) -> Result<()> {
    let start_time = Instant::now();

    println!("🚀 Initializing Sprite multi-agent environment...");

    // Step 1: Ensure git repository exists
    ensure_git_repository()?;

    // T028: Handle edge case - existing configuration
    let agents_dir = PathBuf::from("agents");
    let config_file = agents_dir.join("agents.yaml");

    if config_file.exists() && !options.force {
        return Err(SpriteError::config(
            "Configuration file already exists. Use --force to overwrite.",
        )
        .into());
    }

    // Step 2: Create directory structure (only scripts and profiles, not agent dirs)
    create_base_directory_structure(&agents_dir)?;

    // Step 3: Ensure we have an initial commit before creating branches/worktrees
    ensure_initial_commit_for_worktrees()?;

    // Step 4: Create agent branches and worktrees (BEFORE config to avoid copying)
    if options.agents > 0 {
        setup_agent_worktrees(options.agents)?;
    }

    // Step 5: Generate configuration file (AFTER worktrees to avoid nested copies)
    generate_agents_config(&config_file, options.agents)?;

    // Step 5: Create shell script templates
    create_shell_script_templates(&agents_dir)?;

    // Step 6: Create tmux profile templates
    create_tmux_profile_templates(&agents_dir)?;

    // Step 7: Create .envrc for direnv if direnv is available
    create_direnv_config(&agents_dir)?;

    // Step 8: Commit configuration to git
    ensure_initial_commit(&agents_dir)?;

    let duration = start_time.elapsed();
    println!(
        "✅ Sprite environment initialized successfully in {:.1}s!",
        duration.as_secs_f64()
    );
    println!();
    println!("📁 Created directories:");
    println!("   agents/");
    println!("   agents/scripts/");
    println!("   agents/profiles/");
    println!();
    println!("📄 Generated configuration:");
    println!("   agents/agents.yaml");
    println!();

    if options.agents > 0 {
        println!("🤖 Configured {} agents:", options.agents);
        for i in 1..=options.agents {
            println!("   Agent {}: agents/{}", i, i);
        }
    } else {
        println!("🤖 No agents configured (empty setup)");
    }
    println!();

    println!("🎯 Next steps:");
    if options.agents > 0 {
        println!("   1. Review agents/agents.yaml and customize agent configurations");
        println!("   2. Run 'sprite start' to begin supervision session");
    } else {
        println!("   1. Add agents using 'sprite agents create <id>'");
        println!("   2. Or edit agents/agents.yaml manually");
        println!("   3. Run 'sprite start' when ready");
    }
    println!();
    println!("💡 Pro tip: Everything is ready! You can start coding immediately.");

    Ok(())
}

/// Ensure git repository exists, initialize if needed
fn ensure_git_repository() -> Result<()> {
    // Check if .git exists
    if !PathBuf::from(".git").exists() {
        println!("📦 No git repository found. Initializing...");
        let output = Command::new("git")
            .args(["init"])
            .output()
            .context("Failed to run git init")?;

        if !output.status.success() {
            anyhow::bail!("Failed to initialize git repository");
        }
        println!("   ✅ Git repository initialized");
    } else {
        println!("   ✅ Git repository detected");
    }

    Ok(())
}

/// Ensure initial commit exists for worktree creation
fn ensure_initial_commit_for_worktrees() -> Result<()> {
    // Check if there are any commits
    let has_commits = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if !has_commits {
        println!("   📌 No commits found. Creating initial commit...");

        // Ensure git user is configured
        ensure_git_user_configured()?;

        // Create a simple initial commit
        let output = Command::new("git")
            .args([
                "commit",
                "--allow-empty",
                "-m",
                "Initial commit for sprite worktrees",
            ])
            .output()
            .context("Failed to create initial commit")?;

        if output.status.success() {
            println!("   ✅ Initial commit created");
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Failed to create initial commit: {}", stderr);
        }
    }

    Ok(())
}

/// Ensure at least one commit exists
fn ensure_initial_commit(agents_dir: &Path) -> Result<()> {
    println!("📝 Setting up git commit...");

    // Check if there are any commits
    let has_commits = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if !has_commits {
        println!("   📌 No commits found. Creating initial commit...");

        // Ensure git user is configured (needed for commits in CI)
        ensure_git_user_configured()?;
    } else {
        println!("   📌 Adding agents configuration...");
    }

    // Stage agents directory
    let output = Command::new("git")
        .args(["add", agents_dir.to_str().unwrap()])
        .output()
        .context("Failed to stage agents directory")?;

    if !output.status.success() {
        anyhow::bail!("Failed to stage agents directory");
    }

    // If there are no commits, we MUST create one (branches need a commit)
    // If there are commits, check if there's anything to commit
    if has_commits {
        let status_output = Command::new("git")
            .args(["status", "--porcelain"])
            .output()
            .context("Failed to check git status")?;

        if status_output.stdout.is_empty() {
            println!("   ℹ️  No changes to commit");
            return Ok(());
        }
    }

    // Commit
    let output = Command::new("git")
        .args(["commit", "-m", "Initialize Sprite multi-agent environment"])
        .output()
        .context("Failed to create commit")?;

    if output.status.success() {
        println!("   ✅ Changes committed");
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        anyhow::bail!("Failed to create commit: {}", stderr);
    }

    Ok(())
}

/// Ensure git user is configured (for CI environments)
fn ensure_git_user_configured() -> Result<()> {
    // Check if user.name is set
    let name_check = Command::new("git")
        .args(["config", "user.name"])
        .output()
        .map(|o| o.status.success() && !o.stdout.is_empty())
        .unwrap_or(false);

    if !name_check {
        // Set a default user name
        Command::new("git")
            .args(["config", "user.name", "Sprite"])
            .output()
            .context("Failed to set git user.name")?;
    }

    // Check if user.email is set
    let email_check = Command::new("git")
        .args(["config", "user.email"])
        .output()
        .map(|o| o.status.success() && !o.stdout.is_empty())
        .unwrap_or(false);

    if !email_check {
        // Set a default user email
        Command::new("git")
            .args(["config", "user.email", "sprite@localhost"])
            .output()
            .context("Failed to set git user.email")?;
    }

    Ok(())
}

/// Create agent branches and worktrees
fn setup_agent_worktrees(agent_count: u32) -> Result<()> {
    println!("🌳 Setting up agent worktrees...");

    // First, prune any stale worktree entries
    // Run this twice to ensure all stale entries are removed
    prune_stale_worktrees()?;
    prune_stale_worktrees()?;

    for i in 1..=agent_count {
        let branch_name = format!("agents/{}", i);
        let worktree_path = format!("agents/{}", i);

        // Check if worktree is already registered
        if is_worktree_registered(&worktree_path)? {
            println!(
                "   ℹ️  Worktree {} already registered, removing...",
                worktree_path
            );
            remove_worktree(&worktree_path)?;
        }

        // Create branch if it doesn't exist
        println!("   🔀 Creating branch: {}", branch_name);
        let branch_exists = Command::new("git")
            .args(["rev-parse", "--verify", &branch_name])
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false);

        if !branch_exists {
            let output = Command::new("git")
                .args(["branch", &branch_name])
                .output()
                .context("Failed to create branch")?;

            if !output.status.success() {
                anyhow::bail!("Failed to create branch: {}", branch_name);
            }
        }

        // Remove placeholder directory if it exists
        let worktree_dir = PathBuf::from(&worktree_path);
        if worktree_dir.exists() {
            fs::remove_dir_all(&worktree_dir).with_context(|| {
                format!("Failed to remove placeholder directory: {}", worktree_path)
            })?;
        }

        // Create worktree (with force flag to override any stale entries)
        println!("   📁 Creating worktree: {}", worktree_path);
        let mut cmd = Command::new("git");
        cmd.args(["worktree", "add"]);

        // Try with --force flag first to handle edge cases
        cmd.arg("--force");
        cmd.args([&worktree_path, &branch_name]);

        let output = cmd.output().context("Failed to create worktree")?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            anyhow::bail!("Failed to create worktree {}: {}", worktree_path, stderr);
        }
        println!("   ✅ Agent {} worktree ready", i);
    }

    // Show worktree list
    println!();
    println!("📋 Git worktree status:");
    let output = Command::new("git")
        .args(["worktree", "list"])
        .output()
        .context("Failed to list worktrees")?;

    if output.status.success() {
        let worktrees = String::from_utf8_lossy(&output.stdout);
        for line in worktrees.lines() {
            println!("   {}", line);
        }
    }

    Ok(())
}

/// Prune stale worktree entries
fn prune_stale_worktrees() -> Result<()> {
    let output = Command::new("git")
        .args(["worktree", "prune"])
        .output()
        .context("Failed to prune worktrees")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // Don't fail on prune errors, just warn
        println!("   ⚠️  Warning: Failed to prune worktrees: {}", stderr);
    }

    Ok(())
}

/// Check if a worktree is registered
fn is_worktree_registered(path: &str) -> Result<bool> {
    let output = Command::new("git")
        .args(["worktree", "list", "--porcelain"])
        .output()
        .context("Failed to list worktrees")?;

    if !output.status.success() {
        return Ok(false);
    }

    let worktree_list = String::from_utf8_lossy(&output.stdout);
    // Check if the path appears in the worktree list
    Ok(worktree_list.contains(&format!("worktree {}", path)))
}

/// Remove a worktree registration
fn remove_worktree(path: &str) -> Result<()> {
    let output = Command::new("git")
        .args(["worktree", "remove", path, "--force"])
        .output()
        .context("Failed to remove worktree")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        // If remove fails, the worktree might not exist - that's okay
        println!("   ⚠️  Warning: {}", stderr);
    }

    Ok(())
}

/// Create base directory structure (without agent directories)
fn create_base_directory_structure(agents_dir: &Path) -> Result<()> {
    println!("📁 Creating directory structure...");

    // Create main agents directory
    fs::create_dir_all(agents_dir).context("Failed to create agents directory")?;

    // Create .gitignore to prevent recursive copying
    let gitignore_content = r"# Prevent git worktrees from copying this directory recursively
# This file prevents the agents/ directory from being copied into agent worktrees

# Ignore everything except this file
/*
!/.gitignore
";
    fs::write(agents_dir.join(".gitignore"), gitignore_content)
        .context("Failed to create .gitignore in agents directory")?;

    // Create scripts directory
    let scripts_dir = agents_dir.join("scripts");
    fs::create_dir_all(&scripts_dir).context("Failed to create scripts directory")?;

    // Create profiles directory
    let profiles_dir = agents_dir.join("profiles");
    fs::create_dir_all(&profiles_dir).context("Failed to create profiles directory")?;

    println!("   ✅ Base directories created");

    Ok(())
}

fn generate_agents_config(config_file: &Path, agent_count: u32) -> Result<()> {
    println!("📝 Generating configuration file...");

    if agent_count == 0 {
        // Warn user about zero agents
        println!("   ⚠️  Warning: Initializing with 0 agents");
        println!("   💡 You can add agents later using 'sprite agents create <id>'");
        println!();
    }

    let config = if agent_count == 0 {
        // Empty configuration template with updated schema
        include_str!("../templates/empty_agents.yaml").to_string()
    } else {
        // Generate configuration with agents
        generate_config_content(agent_count)?
    };

    fs::write(config_file, config).context("Failed to write agents.yaml configuration")?;

    Ok(())
}

fn generate_config_content(agent_count: u32) -> Result<String> {
    let mut config = String::new();

    config.push_str("# Sprite Multi-Agent Configuration\n");
    config.push_str("# Generated automatically by 'sprite init'\n");
    config.push_str("# Customize this file to match your project needs\n\n");

    config.push_str("version: \"1.0\"\n\n");

    config.push_str("agents:\n");
    for i in 1..=agent_count {
        config.push_str(&format!("- id: '{}'\n", i));
        config.push_str(&format!("  branch: agents/{}\n", i));
        config.push_str(&format!("  worktree_path: agents/{}\n", i));
        config.push_str("  model: claude-sonnet-4\n");
        config.push_str(&format!("  description: Agent {} workspace\n", i));
        config.push_str("  status: Inactive\n");
        config.push_str("  config:\n");
        config.push_str("    env_vars: {}\n");
        config.push_str("    work_dir: null\n");
        config.push_str("    startup_commands: []\n");
        config.push_str("    resource_limits:\n");
        config.push_str("      max_memory_mb: 1024\n");
        config.push_str("      max_cpu_percent: 80\n");
        config.push_str("      operation_timeout_secs: 300\n");
        config.push_str("      max_concurrent_ops: 3\n");
        config.push_str("      max_disk_mb: 5120\n");
        config.push_str("    shell: null\n");
        config.push_str("    default_timeout_secs: 300\n");
        config.push_str("    auto_sync: false\n");
        config.push_str("    custom_settings: {}\n");
    }

    config.push_str("session_name: sprite-session\n");

    config.push_str("sync:\n");
    config.push_str("  auto_sync: false\n");
    config.push_str("  default_interval_secs: 300\n");
    config.push_str("  conflict_resolution: Manual\n");
    config.push_str("  exclude_branches:\n");
    config.push_str("  - main\n");
    config.push_str("  - master\n");
    config.push_str("  pre_sync_hooks: []\n");
    config.push_str("  post_sync_hooks: []\n");

    config.push_str("settings:\n");
    config.push_str("  default_shell: bash\n");
    config.push_str("  global_env_vars: {}\n");
    config.push_str("  logging:\n");
    config.push_str("    log_file: agents/logs/sprite.log\n");
    config.push_str("    level: Info\n");
    config.push_str("    log_to_stdout: true\n");
    config.push_str("    rotation:\n");
    config.push_str("      max_size_mb: 100\n");
    config.push_str("      max_files: 5\n");
    config.push_str("  performance:\n");
    config.push_str("    max_concurrent_ops: 10\n");
    config.push_str("    default_timeout_secs: 300\n");
    config.push_str("    enable_monitoring: true\n");
    config.push_str("    memory_limit_mb: 1024\n");
    config.push_str("    cpu_limit_percent: 80\n");
    config.push_str("  security:\n");
    config.push_str("    allowed_paths:\n");
    config.push_str("    - agents/\n");
    config.push_str("    blocked_commands:\n");
    config.push_str("    - rm -rf\n");
    config.push_str("    - sudo\n");
    config.push_str("    - su\n");
    config.push_str("    - chmod 777\n");
    config.push_str("    strict_path_validation: true\n");
    config.push_str("    max_command_length: 1000\n");
    config.push_str("    allow_shell_execution: false\n");

    Ok(config)
}

fn create_shell_script_templates(agents_dir: &Path) -> Result<()> {
    println!("🔧 Creating shell script templates...");

    let scripts_dir = agents_dir.join("scripts");

    // Create setup.sh script
    let setup_script = include_str!("../templates/setup.sh");
    fs::write(scripts_dir.join("setup.sh"), setup_script)?;

    // Make scripts executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(scripts_dir.join("setup.sh"))?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(scripts_dir.join("setup.sh"), perms)?;
    }

    // Create start-agents.sh script
    let start_script = include_str!("../templates/start-agents.sh");
    fs::write(scripts_dir.join("start-agents.sh"), start_script)?;

    #[cfg(unix)]
    {
        let mut perms = fs::metadata(scripts_dir.join("start-agents.sh"))?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(scripts_dir.join("start-agents.sh"), perms)?;
    }

    // Create attach-session.sh script
    let attach_script = include_str!("../templates/attach-session.sh");
    fs::write(scripts_dir.join("attach-session.sh"), attach_script)?;

    #[cfg(unix)]
    {
        let mut perms = fs::metadata(scripts_dir.join("attach-session.sh"))?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(scripts_dir.join("attach-session.sh"), perms)?;
    }

    Ok(())
}

fn create_tmux_profile_templates(agents_dir: &Path) -> Result<()> {
    println!("🖼️  Creating tmux profile templates...");

    let profiles_dir = agents_dir.join("profiles");

    // Profile 0: Top + split bottom (2-3 agents)
    let profile0 = include_str!("../templates/profile0.sh");
    fs::write(profiles_dir.join("profile0.sh"), profile0)?;

    // Profile 1: Left column + stacked right
    let profile1 = include_str!("../templates/profile1.sh");
    fs::write(profiles_dir.join("profile1.sh"), profile1)?;

    // Profile 2: Top row + full-width bottom
    let profile2 = include_str!("../templates/profile2.sh");
    fs::write(profiles_dir.join("profile2.sh"), profile2)?;

    // Profile 3: Single full-width top (focus mode)
    let profile3 = include_str!("../templates/profile3.sh");
    fs::write(profiles_dir.join("profile3.sh"), profile3)?;

    // Profile 4: Three-pane layout
    let profile4 = include_str!("../templates/profile4.sh");
    fs::write(profiles_dir.join("profile4.sh"), profile4)?;

    // Profile 5: Six-pane dashboard
    let profile5 = include_str!("../templates/profile5.sh");
    fs::write(profiles_dir.join("profile5.sh"), profile5)?;

    // Make all profile scripts executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        for i in 0..=5 {
            let profile_file = profiles_dir.join(format!("profile{}.sh", i));
            if profile_file.exists() {
                let mut perms = fs::metadata(&profile_file)?.permissions();
                perms.set_mode(0o755);
                fs::set_permissions(&profile_file, perms)?;
            }
        }
    }

    Ok(())
}

fn create_direnv_config(agents_dir: &Path) -> Result<()> {
    // Check if direnv is available
    let direnv_available = std::process::Command::new("direnv")
        .arg("version")
        .output()
        .is_ok();

    if !direnv_available {
        return Ok(()); // Skip if direnv is not available
    }

    println!("🔌 Creating direnv configuration...");

    let envrc_content = r#"# Sprite Multi-Agent Environment Configuration
# Generated automatically by 'sprite init'

# Load common environment variables
export SPRITE_ENV="development"
export SPRITE_AGENTS_DIR="$(pwd)/agents"

# Add scripts to PATH
export PATH="$SPRITE_AGENTS_DIR/scripts:$PATH"

# Common aliases for sprite commands
alias sa='sprite attach'
alias ss='sprite start'
alias sk='sprite kill'
alias sw='sprite warp'
alias sz='sprite zoom'

# Auto-load environment when entering agent directories
layout_dir agents
"#;

    fs::write(".envrc", envrc_content)?;

    // Also create .envrc in agents directory
    let agents_envrc = r#"# Sprite Agents Environment
# Generated automatically by 'sprite init'

export SPRITE_AGENT_DIR="$(pwd)"
"#;

    fs::write(agents_dir.join(".envrc"), agents_envrc)?;

    println!("   Created .envrc files for direnv");

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_create_base_directory_structure() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");

        let result = create_base_directory_structure(&agents_dir);

        assert!(result.is_ok());
        assert!(agents_dir.exists());
        assert!(agents_dir.join("scripts").exists());
        assert!(agents_dir.join("profiles").exists());
        // Agent directories are NOT created by this function anymore
        assert!(!agents_dir.join("1").exists());
        assert!(!agents_dir.join("2").exists());
        assert!(!agents_dir.join("3").exists());
    }

    #[test]
    fn test_create_base_directory_structure_idempotent() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");

        // Call twice to ensure it's idempotent
        let result1 = create_base_directory_structure(&agents_dir);
        let result2 = create_base_directory_structure(&agents_dir);

        assert!(result1.is_ok());
        assert!(result2.is_ok());
        assert!(agents_dir.exists());
        assert!(agents_dir.join("scripts").exists());
        assert!(agents_dir.join("profiles").exists());
    }

    #[test]
    fn test_create_base_directory_structure_nested() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");

        let result = create_base_directory_structure(&agents_dir);

        assert!(result.is_ok());
        assert!(agents_dir.exists());
        assert!(agents_dir.join("scripts").exists());
        assert!(agents_dir.join("profiles").exists());
    }

    #[test]
    fn test_generate_config_content() {
        let result = generate_config_content(2);

        assert!(result.is_ok());
        let config = result.unwrap();

        assert!(config.contains("agents:"));
        assert!(config.contains("- id: '1'"));
        assert!(config.contains("- id: '2'"));
        assert!(config.contains("session_name:"));
        assert!(config.contains("sync:"));
        assert!(config.contains("settings:"));
        assert!(config.contains("version: \"1.0\""));
        assert!(config.contains("claude-sonnet-4"));
        assert!(config.contains("worktree_path:"));
        assert!(config.contains("resource_limits:"));
    }

    #[test]
    fn test_generate_config_content_many_agents() {
        let result = generate_config_content(10);

        assert!(result.is_ok());
        let config = result.unwrap();

        // Should contain all agents from 1 to 10
        for i in 1..=10 {
            assert!(config.contains(&format!("- id: '{}'", i)));
        }
        // Should not contain agent 11
        assert!(!config.contains("- id: '11'"));
    }

    #[test]
    fn test_generate_empty_config() {
        let result = generate_config_content(0);

        assert!(result.is_ok());
        let config = result.unwrap();

        assert!(config.contains("agents:"));
        assert!(!config.contains("- id: '1'"));
        assert!(config.contains("version: \"1.0\""));
        assert!(config.contains("session_name:"));
    }

    #[test]
    fn test_generate_agents_config() {
        let temp_dir = TempDir::new().unwrap();
        let config_file = temp_dir.path().join("agents.yaml");

        let result = generate_agents_config(&config_file, 3);

        assert!(result.is_ok());
        assert!(config_file.exists());

        let content = fs::read_to_string(&config_file).unwrap();
        assert!(content.contains("agents:"));
        assert!(content.contains("- id: '1'"));
        assert!(content.contains("- id: '2'"));
        assert!(content.contains("- id: '3'"));
    }

    #[test]
    fn test_generate_agents_config_empty() {
        let temp_dir = TempDir::new().unwrap();
        let config_file = temp_dir.path().join("agents.yaml");

        let result = generate_agents_config(&config_file, 0);

        assert!(result.is_ok());
        assert!(config_file.exists());

        let content = fs::read_to_string(&config_file).unwrap();
        // Should use empty template
        assert!(!content.is_empty());
    }

    #[test]
    fn test_create_shell_script_templates() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");

        // Create the base directory structure first
        let result = create_base_directory_structure(&agents_dir);
        assert!(result.is_ok());

        let scripts_dir = agents_dir.join("scripts");
        assert!(scripts_dir.exists());

        // Create a simple test script
        let test_script = "#!/bin/bash\n# Test script\necho 'Hello from test script'";
        fs::write(scripts_dir.join("test_script.sh"), test_script).unwrap();

        assert!(scripts_dir.join("test_script.sh").exists());

        let test_content = fs::read_to_string(scripts_dir.join("test_script.sh")).unwrap();
        assert!(!test_content.is_empty());
        assert!(test_content.contains("#!/bin/bash"));
    }

    #[test]
    fn test_create_tmux_profile_templates() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");

        // Create the base directory structure first
        let result = create_base_directory_structure(&agents_dir);
        assert!(result.is_ok());

        let profiles_dir = agents_dir.join("profiles");
        assert!(profiles_dir.exists());

        // Create a simple test profile
        let test_profile = "#!/bin/bash\n# Test tmux profile\necho 'Test tmux profile'";
        fs::write(profiles_dir.join("test_profile.sh"), test_profile).unwrap();

        assert!(profiles_dir.join("test_profile.sh").exists());

        let content = fs::read_to_string(profiles_dir.join("test_profile.sh")).unwrap();
        assert!(!content.is_empty());
        assert!(content.contains("#!/bin/bash"));
    }

    #[test]
    fn test_create_direnv_config() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();

        let result = create_direnv_config(&agents_dir);

        assert!(result.is_ok());
        // Should not fail even if direnv is not available
    }

    #[test]
    fn test_init_options_struct() {
        let options = InitOptions {
            force: true,
            agents: 5,
        };

        assert!(options.force);
        assert_eq!(options.agents, 5);
    }

    #[test]
    fn test_init_execution_with_force() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();

        // Create an existing config file
        let config_file = agents_dir.join("agents.yaml");
        fs::write(&config_file, "existing: config").unwrap();

        let _options = InitOptions {
            force: true,
            agents: 2,
        };

        // Should succeed with force flag even if config exists
        // Note: This test would require mocking git validation for full testing
        // For now, we test the structure creation parts
        let result = create_base_directory_structure(&agents_dir);
        assert!(result.is_ok());
    }

    #[test]
    fn test_init_execution_without_force_existing_config() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");
        fs::create_dir_all(&agents_dir).unwrap();

        // Create an existing config file
        let config_file = agents_dir.join("agents.yaml");
        fs::write(&config_file, "existing: config").unwrap();

        let _options = InitOptions {
            force: false,
            agents: 2,
        };

        // Testing the config existence check
        assert!(config_file.exists());
    }

    #[test]
    fn test_config_content_structure() {
        let result = generate_config_content(1);
        assert!(result.is_ok());

        let config = result.unwrap();

        // Test YAML structure
        assert!(config.contains("version:"));
        assert!(config.contains("agents:"));
        assert!(config.contains("- id:"));
        assert!(config.contains("branch:"));
        assert!(config.contains("model:"));
        assert!(config.contains("description:"));
        assert!(config.contains("worktree_path:"));
        assert!(config.contains("status:"));
        assert!(config.contains("config:"));
        assert!(config.contains("resource_limits:"));
        assert!(config.contains("session_name:"));
        assert!(config.contains("sync:"));
        assert!(config.contains("settings:"));
    }

    #[test]
    fn test_config_content_default_values() {
        let result = generate_config_content(1);
        assert!(result.is_ok());

        let config = result.unwrap();

        // Test default values
        assert!(config.contains("claude-sonnet-4"));
        assert!(config.contains("Inactive"));
        assert!(config.contains("max_memory_mb: 1024"));
        assert!(config.contains("max_cpu_percent: 80"));
        assert!(config.contains("operation_timeout_secs: 300"));
        assert!(config.contains("max_concurrent_ops: 3"));
        assert!(config.contains("max_disk_mb: 5120"));
        assert!(config.contains("auto_sync: false"));
    }

    #[test]
    fn test_config_content_security_settings() {
        let result = generate_config_content(1);
        assert!(result.is_ok());

        let config = result.unwrap();

        // Test security settings
        assert!(config.contains("security:"));
        assert!(config.contains("allowed_paths:"));
        assert!(config.contains("blocked_commands:"));
        assert!(config.contains("strict_path_validation: true"));
        assert!(config.contains("max_command_length: 1000"));
        assert!(config.contains("allow_shell_execution: false"));
    }

    #[test]
    fn test_error_handling_invalid_directory() {
        // Test with an invalid path (should handle gracefully)
        let invalid_path = Path::new("/invalid/nonexistent/path");

        // This should return an error, not panic
        let result = create_base_directory_structure(invalid_path);
        assert!(result.is_err());
    }

    #[test]
    fn test_edge_case_large_agent_count() {
        let temp_dir = TempDir::new().unwrap();
        let agents_dir = temp_dir.path().join("agents");

        // Test with a large number of agents (but we only test base structure now)
        let result = create_base_directory_structure(&agents_dir);
        assert!(result.is_ok());

        // Verify base directories were created
        assert!(agents_dir.join("scripts").exists());
        assert!(agents_dir.join("profiles").exists());

        // Agent directories are NOT created by this function anymore
        // They are created by setup_agent_worktrees
        assert!(!agents_dir.join("1").exists());
        assert!(!agents_dir.join("100").exists());
    }
}