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
//! Configuration validation utilities for the Sprite multi-agent workflow toolkit.
//!
//! This module provides comprehensive validation functions that produce clear,
//! actionable error messages for configuration issues.

use crate::error::SpriteError;
use crate::models::{
    config::SyncHook, Agent, AgentStatus, ConflictResolution, LoggingConfig, PerformanceSettings,
    ProjectConfig, ProjectSettings, SecuritySettings, SyncConfig,
};
use anyhow::{Context, Result};

/// Validate configuration with detailed error messages.
///
/// This function provides comprehensive validation of the entire configuration
/// with specific, actionable error messages that help users understand
/// what needs to be fixed.
#[allow(dead_code)]
pub fn validate_config(config: &ProjectConfig) -> Result<()> {
    validate_version(&config.version)?;
    validate_agents(&config.agents)?;
    validate_session_name(&config.session_name)?;
    validate_sync_config(&config.sync)?;
    validate_project_settings(&config.settings)?;

    Ok(())
}

/// Validate configuration version.
#[allow(dead_code)]
fn validate_version(version: &str) -> Result<()> {
    if version.is_empty() {
        return Err(SpriteError::validation(
            "Configuration version is required",
            Some("version".to_string()),
            Some("empty".to_string()),
        )
        .into());
    }

    // Check if version follows semantic versioning pattern
    if !version.chars().all(|c| c.is_ascii_digit() || c == '.') {
        return Err(SpriteError::validation(
            "Configuration version must be in semantic versioning format (e.g., '1.0', '1.2.3')",
            Some("version".to_string()),
            Some(version.to_string()),
        )
        .into());
    }

    Ok(())
}

/// Validate agent configurations.
#[allow(dead_code)]
fn validate_agents(agents: &[Agent]) -> Result<()> {
    if agents.is_empty() {
        return Err(SpriteError::validation(
            "At least one agent must be configured",
            Some("agents".to_string()),
            Some("empty list".to_string()),
        )
        .into());
    }

    // Check for duplicate agent IDs
    let mut agent_ids = std::collections::HashSet::new();
    for (index, agent) in agents.iter().enumerate() {
        if !agent_ids.insert(&agent.id) {
            return Err(SpriteError::validation(
                format!("Duplicate agent ID '{}' found at index {}", agent.id, index),
                Some("agents".to_string()),
                Some(agent.id.clone()),
            )
            .into());
        }

        validate_agent(agent).with_context(|| format!("Agent '{}' validation failed", agent.id))?;
    }

    Ok(())
}

/// Validate individual agent configuration.
#[allow(dead_code)]
pub fn validate_agent(agent: &Agent) -> Result<()> {
    // Validate agent ID
    if agent.id.is_empty() {
        return Err(SpriteError::validation(
            "Agent ID cannot be empty",
            Some("agent.id".to_string()),
            Some("empty".to_string()),
        )
        .into());
    }

    if !agent
        .id
        .chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
    {
        return Err(SpriteError::validation(
            "Agent ID can only contain alphanumeric characters, hyphens, and underscores",
            Some("agent.id".to_string()),
            Some(agent.id.clone()),
        )
        .into());
    }

    if agent.id.len() > 50 {
        return Err(SpriteError::validation(
            "Agent ID cannot exceed 50 characters",
            Some("agent.id".to_string()),
            Some(format!("{} characters", agent.id.len())),
        )
        .into());
    }

    // Validate branch name
    if agent.branch.is_empty() {
        return Err(SpriteError::validation(
            "Agent branch cannot be empty",
            Some("agent.branch".to_string()),
            Some("empty".to_string()),
        )
        .into());
    }

    validate_branch_name(&agent.branch)?;

    // Validate workspace path
    let workspace_path = agent.workspace_path();
    validate_workspace_path(workspace_path.as_path())?;

    // Validate agent status consistency
    validate_agent_status(agent)?;

    Ok(())
}

/// Validate branch name format.
#[allow(dead_code)]
fn validate_branch_name(branch: &str) -> Result<()> {
    // Basic branch name validation (git branch naming conventions)
    if branch.contains("..") {
        return Err(SpriteError::validation(
            "Branch name cannot contain '..' (path traversal)",
            Some("branch".to_string()),
            Some(branch.to_string()),
        )
        .into());
    }

    if branch.starts_with('/') || branch.ends_with('/') {
        return Err(SpriteError::validation(
            "Branch name cannot start or end with '/'",
            Some("branch".to_string()),
            Some(branch.to_string()),
        )
        .into());
    }

    if branch.chars().any(|c| c.is_control()) {
        return Err(SpriteError::validation(
            "Branch name cannot contain control characters",
            Some("branch".to_string()),
            Some(branch.to_string()),
        )
        .into());
    }

    Ok(())
}

/// Validate workspace path security and format.
#[allow(dead_code)]
fn validate_workspace_path(path: &std::path::Path) -> Result<()> {
    let path_str = path.to_string_lossy();

    // Path must be within agents/ directory
    if !path_str.starts_with("agents/") {
        return Err(SpriteError::validation(
            "Agent workspace must be within the 'agents/' directory",
            Some("worktree_path".to_string()),
            Some(path_str.to_string()),
        )
        .into());
    }

    // Check for path traversal attempts
    if path_str.contains("..") {
        return Err(SpriteError::validation(
            "Agent workspace path cannot contain parent directory references",
            Some("worktree_path".to_string()),
            Some(path_str.to_string()),
        )
        .into());
    }

    // Check for absolute paths
    if path.is_absolute() {
        return Err(SpriteError::validation(
            "Agent workspace path must be relative to project root",
            Some("worktree_path".to_string()),
            Some(path_str.to_string()),
        )
        .into());
    }

    Ok(())
}

/// Validate agent status consistency.
#[allow(dead_code)]
fn validate_agent_status(agent: &Agent) -> Result<()> {
    match &agent.status {
        AgentStatus::Error(msg) => {
            if msg.is_empty() {
                return Err(SpriteError::validation(
                    "Agent error status must include an error message",
                    Some("agent.status".to_string()),
                    Some("empty error message".to_string()),
                )
                .into());
            }
        }
        AgentStatus::Initializing => {
            // Check if last_activity should be set during initialization
            if agent.last_activity.is_none() {
                return Err(SpriteError::validation(
                    "Agent in initializing state should have a last_activity timestamp",
                    Some("agent.last_activity".to_string()),
                    Some("not set".to_string()),
                )
                .into());
            }
        }
        _ => {} // Other statuses are valid without additional checks
    }

    Ok(())
}

/// Validate session configuration.
#[allow(dead_code)]
fn validate_session_name(session_name: &str) -> Result<()> {
    if session_name.is_empty() {
        return Err(SpriteError::validation(
            "Session name cannot be empty",
            Some("session_name".to_string()),
            Some("empty".to_string()),
        )
        .into());
    }

    if !session_name
        .chars()
        .all(|c| c.is_alphanumeric() || c == '-' || c == '_')
    {
        return Err(SpriteError::validation(
            "Session name can only contain alphanumeric characters, hyphens, and underscores",
            Some("session_name".to_string()),
            Some(session_name.to_string()),
        )
        .into());
    }

    if session_name.len() > 50 {
        return Err(SpriteError::validation(
            "Session name cannot exceed 50 characters",
            Some("session_name".to_string()),
            Some(format!("{} characters", session_name.len())),
        )
        .into());
    }

    Ok(())
}

/// Validate sync configuration.
#[allow(dead_code)]
fn validate_sync_config(sync: &SyncConfig) -> Result<()> {
    if sync.default_interval_secs == 0 {
        return Err(SpriteError::validation(
            "Sync interval must be greater than 0 seconds",
            Some("sync.default_interval_secs".to_string()),
            Some("0".to_string()),
        )
        .into());
    }

    if sync.default_interval_secs > 86400 {
        return Err(SpriteError::validation(
            "Sync interval cannot exceed 24 hours (86400 seconds)",
            Some("sync.default_interval_secs".to_string()),
            Some(sync.default_interval_secs.to_string()),
        )
        .into());
    }

    // Validate conflict resolution strategy
    validate_conflict_resolution(&sync.conflict_resolution)?;

    // Validate exclude branches
    for (index, branch) in sync.exclude_branches.iter().enumerate() {
        validate_branch_name(branch)
            .with_context(|| format!("Invalid exclude branch at index {}", index))?;
    }

    // Validate hooks
    for (index, hook) in sync.pre_sync_hooks.iter().enumerate() {
        validate_sync_hook(hook)
            .with_context(|| format!("Pre-sync hook {} validation failed", index + 1))?;
    }

    for (index, hook) in sync.post_sync_hooks.iter().enumerate() {
        validate_sync_hook(hook)
            .with_context(|| format!("Post-sync hook {} validation failed", index + 1))?;
    }

    Ok(())
}

/// Validate conflict resolution strategy.
#[allow(dead_code)]
fn validate_conflict_resolution(resolution: &ConflictResolution) -> Result<()> {
    match resolution {
        ConflictResolution::Manual => Ok(()),
        ConflictResolution::AutoTheirs => Ok(()),
        ConflictResolution::AutoOurs => Ok(()),
    }
}

/// Validate sync hook configuration.
#[allow(dead_code)]
fn validate_sync_hook(hook: &SyncHook) -> Result<()> {
    if hook.command.is_empty() {
        return Err(SpriteError::validation(
            "Hook command cannot be empty",
            Some("hook.command".to_string()),
            Some("empty".to_string()),
        )
        .into());
    }

    // Validate command doesn't contain suspicious characters
    if hook.command.contains("..") || hook.command.contains(";") || hook.command.contains("&") {
        return Err(SpriteError::validation(
            "Hook command contains potentially unsafe characters",
            Some("hook.command".to_string()),
            Some(hook.command.clone()),
        )
        .into());
    }

    // Validate working directory if specified
    if let Some(ref work_dir) = hook.work_dir {
        if work_dir.as_os_str().is_empty() {
            return Err(SpriteError::validation(
                "Hook working directory cannot be empty",
                Some("hook.work_dir".to_string()),
                Some("empty path".to_string()),
            )
            .into());
        }

        validate_workspace_path(work_dir.as_path())?;
    }

    // Validate timeout if specified
    if let Some(timeout) = hook.timeout_secs {
        if timeout == 0 {
            return Err(SpriteError::validation(
                "Hook timeout must be greater than 0 seconds",
                Some("hook.timeout_secs".to_string()),
                Some("0".to_string()),
            )
            .into());
        }

        if timeout > 3600 {
            return Err(SpriteError::validation(
                "Hook timeout cannot exceed 1 hour (3600 seconds)",
                Some("hook.timeout_secs".to_string()),
                Some(timeout.to_string()),
            )
            .into());
        }
    }

    Ok(())
}

/// Validate project settings.
#[allow(dead_code)]
fn validate_project_settings(settings: &ProjectSettings) -> Result<()> {
    validate_logging_config(&settings.logging)?;
    validate_performance_settings(&settings.performance)?;
    validate_security_settings(&settings.security)?;

    Ok(())
}

/// Validate logging configuration.
#[allow(dead_code)]
fn validate_logging_config(logging: &LoggingConfig) -> Result<()> {
    if let Some(ref log_file) = logging.log_file {
        let path_str = log_file.to_string_lossy();

        if log_file.is_absolute() {
            return Err(SpriteError::validation(
                "Log file path should be relative to project root",
                Some("logging.log_file".to_string()),
                Some(path_str.to_string()),
            )
            .into());
        }

        if path_str.contains("..") {
            return Err(SpriteError::validation(
                "Log file path cannot contain parent directory references",
                Some("logging.log_file".to_string()),
                Some(path_str.to_string()),
            )
            .into());
        }
    }

    if let Some(ref rotation) = logging.rotation {
        if rotation.max_size_mb == 0 {
            return Err(SpriteError::validation(
                "Maximum log file size must be greater than 0 MB",
                Some("logging.rotation.max_size_mb".to_string()),
                Some("0".to_string()),
            )
            .into());
        }

        if rotation.max_files == 0 {
            return Err(SpriteError::validation(
                "Maximum number of log files must be greater than 0",
                Some("logging.rotation.max_files".to_string()),
                Some("0".to_string()),
            )
            .into());
        }

        if rotation.max_files > 100 {
            return Err(SpriteError::validation(
                "Maximum number of log files cannot exceed 100",
                Some("logging.rotation.max_files".to_string()),
                Some(rotation.max_files.to_string()),
            )
            .into());
        }
    }

    Ok(())
}

/// Validate performance settings.
#[allow(dead_code)]
fn validate_performance_settings(performance: &PerformanceSettings) -> Result<()> {
    if performance.max_concurrent_ops == 0 {
        return Err(SpriteError::validation(
            "Maximum concurrent operations must be greater than 0",
            Some("performance.max_concurrent_ops".to_string()),
            Some("0".to_string()),
        )
        .into());
    }

    if performance.max_concurrent_ops > 100 {
        return Err(SpriteError::validation(
            "Maximum concurrent operations cannot exceed 100",
            Some("performance.max_concurrent_ops".to_string()),
            Some(performance.max_concurrent_ops.to_string()),
        )
        .into());
    }

    if performance.default_timeout_secs == 0 {
        return Err(SpriteError::validation(
            "Default timeout must be greater than 0 seconds",
            Some("performance.default_timeout_secs".to_string()),
            Some("0".to_string()),
        )
        .into());
    }

    if performance.default_timeout_secs > 3600 {
        return Err(SpriteError::validation(
            "Default timeout cannot exceed 1 hour (3600 seconds)",
            Some("performance.default_timeout_secs".to_string()),
            Some(performance.default_timeout_secs.to_string()),
        )
        .into());
    }

    if let Some(memory_limit) = performance.memory_limit_mb {
        if memory_limit == 0 {
            return Err(SpriteError::validation(
                "Memory limit must be greater than 0 MB",
                Some("performance.memory_limit_mb".to_string()),
                Some("0".to_string()),
            )
            .into());
        }

        if memory_limit > 16384 {
            return Err(SpriteError::validation(
                "Memory limit cannot exceed 16 GB (16384 MB)",
                Some("performance.memory_limit_mb".to_string()),
                Some(memory_limit.to_string()),
            )
            .into());
        }
    }

    if let Some(cpu_limit) = performance.cpu_limit_percent {
        if cpu_limit == 0 || cpu_limit > 100 {
            return Err(SpriteError::validation(
                "CPU limit must be between 1 and 100 percent",
                Some("performance.cpu_limit_percent".to_string()),
                Some(cpu_limit.to_string()),
            )
            .into());
        }
    }

    Ok(())
}

/// Validate security settings.
#[allow(dead_code)]
fn validate_security_settings(security: &SecuritySettings) -> Result<()> {
    if let Some(max_length) = security.max_command_length {
        if max_length == 0 {
            return Err(SpriteError::validation(
                "Maximum command length must be greater than 0",
                Some("security.max_command_length".to_string()),
                Some("0".to_string()),
            )
            .into());
        }

        if max_length > 10000 {
            return Err(SpriteError::validation(
                "Maximum command length cannot exceed 10000 characters",
                Some("security.max_command_length".to_string()),
                Some(max_length.to_string()),
            )
            .into());
        }
    }

    // Validate allowed paths
    for (index, path) in security.allowed_paths.iter().enumerate() {
        if path.as_os_str().is_empty() {
            return Err(SpriteError::validation(
                "Allowed path cannot be empty",
                Some(format!("security.allowed_paths[{}]", index)),
                Some("empty path".to_string()),
            )
            .into());
        }

        if !path.starts_with("agents/") {
            return Err(SpriteError::validation(
                "Allowed paths should be within the agents/ directory",
                Some(format!("security.allowed_paths[{}]", index)),
                Some(path.to_string_lossy().to_string()),
            )
            .into());
        }
    }

    // Validate blocked commands
    if security.blocked_commands.is_empty() {
        return Err(SpriteError::validation(
            "Blocked commands list cannot be empty",
            Some("security.blocked_commands".to_string()),
            Some("empty list".to_string()),
        )
        .into());
    }

    // Check if there are any dangerous commands in the blocked list
    let dangerous_commands = ["rm", "sudo", "su", "chmod", "chown", "dd"];
    let has_dangerous_command = security.blocked_commands.iter().any(|command| {
        dangerous_commands
            .iter()
            .any(|dangerous| command.starts_with(dangerous) || command.ends_with(dangerous))
    });

    if !has_dangerous_command {
        return Err(SpriteError::validation(
            "Consider adding dangerous commands to blocked list (e.g., 'rm', 'sudo', 'su')",
            Some("security.blocked_commands".to_string()),
            Some("insufficient protection".to_string()),
        )
        .into());
    }

    // Validate each blocked command individually
    for (index, command) in security.blocked_commands.iter().enumerate() {
        if command.is_empty() {
            return Err(SpriteError::validation(
                "Blocked command cannot be empty",
                Some(format!("security.blocked_commands[{}]", index)),
                Some("empty command".to_string()),
            )
            .into());
        }
    }

    Ok(())
}

/// Validate configuration against current git repository state.
#[allow(dead_code)]
pub fn validate_config_with_git(config: &ProjectConfig) -> Result<()> {
    // First, do basic validation
    validate_config(config)?;

    // Then validate against git state
    crate::config::validate_git_repository()
        .context("Configuration validation requires a valid git repository")?;

    // Check that all agent branches exist
    for agent in &config.agents {
        if !crate::config::branch_exists(&agent.branch)? {
            return Err(SpriteError::agent(
                format!(
                    "Agent branch '{}' does not exist. Create it with 'git checkout -b {}'",
                    agent.branch, agent.branch
                ),
                Some(&agent.id),
            )
            .into());
        }
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_validate_version() {
        assert!(validate_version("1.0").is_ok());
        assert!(validate_version("2.1.3").is_ok());
        assert!(validate_version("").is_err());
        assert!(validate_version("1.0-beta").is_err());
    }

    #[test]
    fn test_validate_agent() {
        let mut agent = Agent::new("agent-1", "feature/test");
        assert!(validate_agent(&agent).is_ok());

        // Test invalid ID
        agent.id = "invalid agent!".to_string();
        assert!(validate_agent(&agent).is_err());

        // Reset and test invalid branch
        agent = Agent::new("valid-agent", "");
        assert!(validate_agent(&agent).is_err());
    }

    #[test]
    fn test_validate_branch_name() {
        assert!(validate_branch_name("feature/test").is_ok());
        assert!(validate_branch_name("hotfix/issue-123").is_ok());
        assert!(validate_branch_name("../dangerous").is_err());
        assert!(validate_branch_name("/absolute").is_err());
        assert!(validate_branch_name("trailing/").is_err());
    }

    #[test]
    fn test_validate_workspace_path() {
        assert!(validate_workspace_path(PathBuf::from("agents/agent-1").as_path()).is_ok());
        assert!(validate_workspace_path(PathBuf::from("agents/workspace").as_path()).is_ok());
        assert!(validate_workspace_path(PathBuf::from("outside").as_path()).is_err());
        assert!(validate_workspace_path(PathBuf::from("agents/../dangerous").as_path()).is_err());
        assert!(validate_workspace_path(PathBuf::from("/absolute/path").as_path()).is_err());
    }

    #[test]
    fn test_validate_security_settings() {
        let security = SecuritySettings::default();
        assert!(validate_security_settings(&security).is_ok());
    }
}