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 ensure_git_repository()?;
23
24 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 create_base_directory_structure(&agents_dir)?;
37
38 ensure_initial_commit_for_worktrees()?;
40
41 if options.agents > 0 {
43 setup_agent_worktrees(options.agents)?;
44 }
45
46 generate_agents_config(&config_file, options.agents)?;
48
49 create_shell_script_templates(&agents_dir)?;
51
52 create_tmux_profile_templates(&agents_dir)?;
54
55 create_direnv_config(&agents_dir)?;
57
58 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
101fn ensure_git_repository() -> Result<()> {
103 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
122fn ensure_initial_commit_for_worktrees() -> Result<()> {
124 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_configured()?;
136
137 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
159fn ensure_initial_commit(agents_dir: &Path) -> Result<()> {
161 println!("đ Setting up git commit...");
162
163 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_configured()?;
175 } else {
176 println!(" đ Adding agents configuration...");
177 }
178
179 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 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 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
219fn ensure_git_user_configured() -> Result<()> {
221 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 Command::new("git")
231 .args(["config", "user.name", "Sprite"])
232 .output()
233 .context("Failed to set git user.name")?;
234 }
235
236 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 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
254fn setup_agent_worktrees(agent_count: u32) -> Result<()> {
256 println!("đŗ Setting up agent worktrees...");
257
258 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 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 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 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 println!(" đ Creating worktree: {}", worktree_path);
305 let mut cmd = Command::new("git");
306 cmd.args(["worktree", "add"]);
307
308 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 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
339fn 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 println!(" â ī¸ Warning: Failed to prune worktrees: {}", stderr);
350 }
351
352 Ok(())
353}
354
355fn 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 Ok(worktree_list.contains(&format!("worktree {}", path)))
369}
370
371fn 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 println!(" â ī¸ Warning: {}", stderr);
382 }
383
384 Ok(())
385}
386
387fn create_base_directory_structure(agents_dir: &Path) -> Result<()> {
389 println!("đ Creating directory structure...");
390
391 fs::create_dir_all(agents_dir).context("Failed to create agents directory")?;
393
394 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 let scripts_dir = agents_dir.join("scripts");
407 fs::create_dir_all(&scripts_dir).context("Failed to create scripts directory")?;
408
409 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 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 include_str!("../templates/empty_agents.yaml").to_string()
431 } else {
432 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 let setup_script = include_str!("../templates/setup.sh");
524 fs::write(scripts_dir.join("setup.sh"), setup_script)?;
525
526 #[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 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 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 let profile0 = include_str!("../templates/profile0.sh");
567 fs::write(profiles_dir.join("profile0.sh"), profile0)?;
568
569 let profile1 = include_str!("../templates/profile1.sh");
571 fs::write(profiles_dir.join("profile1.sh"), profile1)?;
572
573 let profile2 = include_str!("../templates/profile2.sh");
575 fs::write(profiles_dir.join("profile2.sh"), profile2)?;
576
577 let profile3 = include_str!("../templates/profile3.sh");
579 fs::write(profiles_dir.join("profile3.sh"), profile3)?;
580
581 let profile4 = include_str!("../templates/profile4.sh");
583 fs::write(profiles_dir.join("profile4.sh"), profile4)?;
584
585 let profile5 = include_str!("../templates/profile5.sh");
587 fs::write(profiles_dir.join("profile5.sh"), profile5)?;
588
589 #[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 let direnv_available = std::process::Command::new("direnv")
609 .arg("version")
610 .output()
611 .is_ok();
612
613 if !direnv_available {
614 return Ok(()); }
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 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 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 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 for i in 1..=10 {
736 assert!(config.contains(&format!("- id: '{}'", i)));
737 }
738 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 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 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 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 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 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 }
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 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 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 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 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 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 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 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 let invalid_path = Path::new("/invalid/nonexistent/path");
958
959 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 let result = create_base_directory_structure(&agents_dir);
971 assert!(result.is_ok());
972
973 assert!(agents_dir.join("scripts").exists());
975 assert!(agents_dir.join("profiles").exists());
976
977 assert!(!agents_dir.join("1").exists());
980 assert!(!agents_dir.join("100").exists());
981 }
982}