ccswarm 0.5.0

AI-powered multi-agent orchestration system with proactive intelligence, security monitoring, and session management
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
use crate::agent::task::Task;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Configuration for auto-accept mode
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoAcceptConfig {
    /// Whether auto-accept is enabled
    pub enabled: bool,

    /// Operations that are trusted and can be auto-accepted
    pub trusted_operations: Vec<OperationType>,

    /// Maximum number of file changes allowed in a single operation
    pub max_file_changes: usize,

    /// Whether tests must pass for auto-accept to trigger
    pub require_tests_pass: bool,

    /// Maximum execution time in seconds before requiring manual approval
    pub max_execution_time: u32,

    /// File patterns that require manual approval (e.g., "*.sql", "Cargo.toml")
    pub restricted_files: Vec<String>,

    /// Whether to require git status to be clean before auto-accepting
    pub require_clean_git: bool,

    /// Emergency stop - if true, all auto-accept is disabled
    pub emergency_stop: bool,

    /// Whether to check that tests pass after execution
    pub check_tests_pass: bool,

    /// Whether to validate file changes are within scope
    pub check_file_changes: bool,

    /// Whether to check git status for issues
    pub check_git_status: bool,
}

impl Default for AutoAcceptConfig {
    fn default() -> Self {
        Self {
            enabled: false, // Conservative default - must be explicitly enabled
            trusted_operations: vec![
                OperationType::ReadFile,
                OperationType::FormatCode,
                OperationType::RunTests,
                OperationType::LintCode,
            ],
            max_file_changes: 5,
            require_tests_pass: true,
            max_execution_time: 300, // 5 minutes
            restricted_files: vec![
                "Cargo.toml".to_string(),
                "package.json".to_string(),
                "*.sql".to_string(),
                "*.env".to_string(),
                "**/migrations/*".to_string(),
            ],
            require_clean_git: true,
            emergency_stop: false,
            check_tests_pass: true,
            check_file_changes: true,
            check_git_status: true,
        }
    }
}

/// Types of operations that can be evaluated for auto-acceptance
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum OperationType {
    /// Reading files or directories
    ReadFile,

    /// Writing new files
    WriteFile,

    /// Editing existing files
    EditFile,

    /// Deleting files
    DeleteFile,

    /// Running tests
    RunTests,

    /// Code formatting operations
    FormatCode,

    /// Linting code
    LintCode,

    /// Git operations (commit, push, etc.)
    GitOperation,

    /// Installing dependencies
    InstallDependencies,

    /// Running build commands
    Build,

    /// Database operations
    DatabaseOperation,

    /// Network requests
    NetworkRequest,

    /// System commands
    SystemCommand,

    /// Creating directories
    CreateDirectory,

    /// Other/unknown operations
    Other,
}

/// Represents an operation that needs to be evaluated for auto-acceptance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Operation {
    /// Type of operation
    pub operation_type: OperationType,

    /// Description of what the operation will do
    pub description: String,

    /// Files that will be affected
    pub affected_files: Vec<PathBuf>,

    /// Commands that will be executed
    pub commands: Vec<String>,

    /// Estimated risk level (0-10, where 10 is highest risk)
    pub risk_level: u8,

    /// Whether this operation is reversible
    pub reversible: bool,

    /// Associated task information
    pub task: Option<Task>,

    /// Expected exit code for command operations (None = any exit code OK)
    pub expected_exit_code: Option<i32>,

    /// Actual exit code after execution (set after operation completes)
    pub actual_exit_code: Option<i32>,
}

/// Engine for evaluating whether operations should be auto-accepted
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutoAcceptEngine {
    pub config: AutoAcceptConfig,
    operation_history: HashMap<String, Vec<Operation>>,
}

impl AutoAcceptEngine {
    /// Create a new auto-accept engine with the given configuration
    pub fn new(config: AutoAcceptConfig) -> Self {
        Self {
            config,
            operation_history: HashMap::new(),
        }
    }

    /// Update the configuration
    pub fn update_config(&mut self, config: AutoAcceptConfig) {
        self.config = config;
    }

    /// Emergency stop - disable all auto-accept immediately
    pub fn emergency_stop(&mut self) {
        self.config.emergency_stop = true;
        self.config.enabled = false;
    }

    /// Re-enable auto-accept after emergency stop (requires manual intervention)
    pub fn reset_emergency_stop(&mut self) {
        self.config.emergency_stop = false;
    }

    /// Analyze an operation and determine its characteristics
    pub fn analyze_operation(&self, commands: &[String], task: Option<&Task>) -> Result<Operation> {
        let mut operation = Operation {
            operation_type: OperationType::Other,
            description: format!("Commands: {}", commands.join("; ")),
            affected_files: Vec::new(),
            commands: commands.to_vec(),
            risk_level: 5, // Default medium risk
            reversible: false,
            task: task.cloned(),
            expected_exit_code: Some(0), // Default: expect success
            actual_exit_code: None,      // Set after execution
        };

        // Analyze commands to determine operation type and risk
        for command in commands {
            let cmd_lower = command.to_lowercase();

            // Determine operation type
            if cmd_lower.contains("cat ")
                || cmd_lower.contains("ls ")
                || cmd_lower.contains("find ")
            {
                operation.operation_type = OperationType::ReadFile;
                operation.risk_level = operation.risk_level.min(1);
                operation.reversible = true;
            } else if cmd_lower.contains("echo ") && cmd_lower.contains(" > ") {
                operation.operation_type = OperationType::WriteFile;
                operation.risk_level = operation.risk_level.max(4);
            } else if cmd_lower.contains("sed ")
                || cmd_lower.contains("awk ")
                || cmd_lower.contains(" edit ")
            {
                operation.operation_type = OperationType::EditFile;
                operation.risk_level = operation.risk_level.max(3);
            } else if cmd_lower.contains("rm ") || cmd_lower.contains("delete ") {
                operation.operation_type = OperationType::DeleteFile;
                operation.risk_level = operation.risk_level.max(8);
            } else if cmd_lower.contains("test")
                || cmd_lower.contains("cargo test")
                || cmd_lower.contains("npm test")
            {
                operation.operation_type = OperationType::RunTests;
                operation.risk_level = operation.risk_level.min(2);
                operation.reversible = true;
            } else if cmd_lower.contains("fmt")
                || cmd_lower.contains("format")
                || cmd_lower.contains("prettier")
            {
                operation.operation_type = OperationType::FormatCode;
                operation.risk_level = operation.risk_level.min(1);
                operation.reversible = true;
            } else if cmd_lower.contains("lint")
                || cmd_lower.contains("clippy")
                || cmd_lower.contains("eslint")
            {
                operation.operation_type = OperationType::LintCode;
                operation.risk_level = operation.risk_level.min(1);
                operation.reversible = true;
            } else if cmd_lower.contains("git ") {
                operation.operation_type = OperationType::GitOperation;
                if cmd_lower.contains("git push") || cmd_lower.contains("git reset --hard") {
                    operation.risk_level = operation.risk_level.max(7);
                } else {
                    operation.risk_level = operation.risk_level.max(3);
                }
            } else if cmd_lower.contains("cargo install")
                || cmd_lower.contains("npm install")
                || cmd_lower.contains("pip install")
            {
                operation.operation_type = OperationType::InstallDependencies;
                operation.risk_level = operation.risk_level.max(5);
            } else if cmd_lower.contains("build")
                || cmd_lower.contains("cargo build")
                || cmd_lower.contains("npm run build")
            {
                operation.operation_type = OperationType::Build;
                operation.risk_level = operation.risk_level.max(2);
                operation.reversible = true;
            } else if cmd_lower.contains("psql")
                || cmd_lower.contains("mysql")
                || cmd_lower.contains("sqlite")
            {
                operation.operation_type = OperationType::DatabaseOperation;
                operation.risk_level = operation.risk_level.max(9);
            } else if cmd_lower.contains("curl")
                || cmd_lower.contains("wget")
                || cmd_lower.contains("http")
            {
                operation.operation_type = OperationType::NetworkRequest;
                operation.risk_level = operation.risk_level.max(4);
            } else if cmd_lower.contains("mkdir") || cmd_lower.contains("mkdirs") {
                operation.operation_type = OperationType::CreateDirectory;
                operation.risk_level = operation.risk_level.min(2);
                operation.reversible = true;
            } else {
                operation.operation_type = OperationType::SystemCommand;
                operation.risk_level = operation.risk_level.max(6);
            }

            // Extract file paths (simplified - could be more sophisticated)
            self.extract_file_paths(command, &mut operation.affected_files);
        }

        Ok(operation)
    }

    /// Determine whether an operation should be auto-accepted
    pub fn should_auto_accept(&self, operation: &Operation) -> Result<AutoAcceptDecision> {
        // Quick rejections
        if self.config.emergency_stop {
            return Ok(AutoAcceptDecision::Reject(
                "Emergency stop is active".to_string(),
            ));
        }

        if !self.config.enabled {
            return Ok(AutoAcceptDecision::Reject(
                "Auto-accept is disabled".to_string(),
            ));
        }

        // Check if operation type is trusted
        if !self
            .config
            .trusted_operations
            .contains(&operation.operation_type)
        {
            return Ok(AutoAcceptDecision::Reject(format!(
                "Operation type {:?} is not in trusted operations list",
                operation.operation_type
            )));
        }

        // Check risk level (reject anything above 5 for auto-accept)
        if operation.risk_level > 5 {
            return Ok(AutoAcceptDecision::Reject(format!(
                "Risk level too high: {} > 5",
                operation.risk_level
            )));
        }

        // Check file change limits
        if operation.affected_files.len() > self.config.max_file_changes {
            return Ok(AutoAcceptDecision::Reject(format!(
                "Too many file changes: {} > {}",
                operation.affected_files.len(),
                self.config.max_file_changes
            )));
        }

        // Check for restricted files
        for file in &operation.affected_files {
            let file_str = file.to_string_lossy();
            for pattern in &self.config.restricted_files {
                if self.matches_pattern(&file_str, pattern) {
                    return Ok(AutoAcceptDecision::Reject(format!(
                        "File {} matches restricted pattern {}",
                        file_str, pattern
                    )));
                }
            }
        }

        // All checks passed - auto-accept with conditions
        let mut conditions = Vec::new();

        if self.config.require_tests_pass {
            conditions.push("Tests must pass".to_string());
        }

        if self.config.require_clean_git {
            conditions.push("Git working directory must be clean".to_string());
        }

        Ok(AutoAcceptDecision::Accept(conditions))
    }

    /// Validate changes after an operation has been executed
    pub async fn validate_changes(
        &self,
        operation: &Operation,
        execution_time: u32,
    ) -> Result<ValidationResult> {
        let mut issues = Vec::new();

        // Check execution time
        if execution_time > self.config.max_execution_time {
            issues.push(format!(
                "Execution time exceeded limit: {}s > {}s",
                execution_time, self.config.max_execution_time
            ));
        }

        // Additional validation checks

        // Check if tests still pass
        if self.config.check_tests_pass
            && let Err(test_error) = self.validate_tests().await
        {
            issues.push(format!("Tests failed: {}", test_error));
        }

        // Verify no unexpected files were changed
        if self.config.check_file_changes
            && let Err(file_error) = self.validate_file_changes(operation).await
        {
            issues.push(format!("Unexpected file changes: {}", file_error));
        }

        // Check git status if required
        if self.config.check_git_status
            && let Err(git_error) = self.validate_git_status().await
        {
            issues.push(format!("Git repository issues: {}", git_error));
        }

        // Validate exit codes if expected code is set
        if let Some(expected) = operation.expected_exit_code {
            match operation.actual_exit_code {
                Some(actual) if actual != expected => {
                    issues.push(format!(
                        "Exit code mismatch: expected {}, got {}",
                        expected, actual
                    ));
                }
                None => {
                    issues.push(
                        "Exit code not recorded for operation with expected exit code".to_string(),
                    );
                }
                _ => {} // Matches
            }
        }

        if issues.is_empty() {
            Ok(ValidationResult::Valid)
        } else {
            Ok(ValidationResult::Invalid(issues))
        }
    }

    /// Record an operation in the history for learning and analysis
    pub fn record_operation(&mut self, session_id: String, operation: Operation) {
        self.operation_history
            .entry(session_id)
            .or_default()
            .push(operation);
    }

    /// Get operation history for a session
    pub fn get_operation_history(&self, session_id: &str) -> Option<&Vec<Operation>> {
        self.operation_history.get(session_id)
    }

    /// Clear operation history for a session
    pub fn clear_history(&mut self, session_id: &str) {
        self.operation_history.remove(session_id);
    }

    /// Validate that tests still pass
    async fn validate_tests(&self) -> Result<(), String> {
        // Try common test commands
        let test_commands = ["cargo test", "npm test", "pytest", "go test"];

        for cmd in &test_commands {
            if let Ok(output) = tokio::process::Command::new("sh")
                .arg("-c")
                .arg(cmd)
                .output()
                .await
            {
                if !output.status.success() {
                    return Err(format!(
                        "Test command '{}' failed with exit code: {:?}",
                        cmd,
                        output.status.code()
                    ));
                }
                // If one test command succeeds, we're good
                return Ok(());
            }
        }

        // No test command worked
        Err("No valid test command found or all tests failed".to_string())
    }

    /// Validate file changes are within expected scope
    async fn validate_file_changes(&self, operation: &Operation) -> Result<(), String> {
        // Check if files changed are in allowed patterns
        for file_path in &operation.affected_files {
            let path_str = file_path.to_string_lossy();

            // Check against protected patterns
            let protected_patterns = [
                ".env",
                "*.key",
                ".git/",
                "/etc/",
                "~/.ssh/",
                "credentials",
                "secrets",
                "passwords",
            ];

            for pattern in &protected_patterns {
                if path_str.contains(pattern) {
                    return Err(format!("Protected file modified: {}", path_str));
                }
            }

            // Check file size limits
            if let Ok(metadata) = std::fs::metadata(file_path)
                && metadata.len() > 10_000_000
            {
                // 10MB limit
                return Err(format!(
                    "File too large: {} ({} bytes)",
                    path_str,
                    metadata.len()
                ));
            }
        }

        Ok(())
    }

    /// Validate git repository status
    async fn validate_git_status(&self) -> Result<(), String> {
        // Check git status
        if let Ok(output) = tokio::process::Command::new("git")
            .args(&["status", "--porcelain"])
            .output()
            .await
        {
            let status_output = String::from_utf8_lossy(&output.stdout);

            // Check for unexpected changes
            for line in status_output.lines() {
                if line.starts_with("??") {
                    // Untracked files - could be okay
                    continue;
                }
                if line.starts_with(" D") || line.starts_with("D ") {
                    return Err(format!("Files deleted: {}", line));
                }
                if line.contains(".git/") {
                    return Err(format!("Git metadata changed: {}", line));
                }
            }

            // Check for conflicts
            if status_output.contains("UU ") || status_output.contains("AA ") {
                return Err("Git merge conflicts detected".to_string());
            }
        } else {
            return Err("Failed to check git status".to_string());
        }

        Ok(())
    }

    /// Simple pattern matching for file restrictions
    pub fn matches_pattern(&self, file: &str, pattern: &str) -> bool {
        if pattern.contains('*') {
            // Simple glob matching - could be improved with a proper glob library
            if pattern.starts_with("**/") && pattern.ends_with("/*") {
                // Pattern like "**/migrations/*" - match any path containing the directory
                let dir_name = &pattern[3..pattern.len() - 2]; // Remove "**/" and "/*"
                file.contains(&format!("/{}/", dir_name))
                    || file.starts_with(&format!("{}/", dir_name))
                    || file.contains(&format!("/{}", dir_name)) // Also match if at end
            } else if let Some(suffix) = pattern.strip_prefix("**/") {
                file.contains(suffix)
            } else if pattern.starts_with('*') && pattern.ends_with('*') {
                let middle = &pattern[1..pattern.len() - 1];
                file.contains(middle)
            } else if let Some(suffix) = pattern.strip_prefix('*') {
                file.ends_with(suffix)
            } else if let Some(prefix) = pattern.strip_suffix('*') {
                file.starts_with(prefix)
            } else {
                file == pattern
            }
        } else {
            file == pattern
        }
    }

    /// Extract file paths from command strings (simplified implementation)
    fn extract_file_paths(&self, command: &str, paths: &mut Vec<PathBuf>) {
        // This is a simplified implementation - a more robust version would
        // properly parse shell commands and extract file arguments
        let parts: Vec<&str> = command.split_whitespace().collect();

        for part in parts {
            if part.contains('/') || part.contains('.') {
                // Likely a file path
                if let Ok(path) = std::path::Path::new(part).canonicalize() {
                    if !paths.contains(&path) {
                        paths.push(path);
                    }
                } else {
                    // Add as-is if we can't canonicalize (file might not exist yet)
                    let path = PathBuf::from(part);
                    if !paths.contains(&path) {
                        paths.push(path);
                    }
                }
            }
        }
    }
}

/// Decision result for auto-acceptance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AutoAcceptDecision {
    /// Accept the operation with optional conditions
    Accept(Vec<String>),

    /// Reject the operation with reason
    Reject(String),
}

/// Result of validating changes after execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationResult {
    /// Changes are valid
    Valid,

    /// Changes are invalid with list of issues
    Invalid(Vec<String>),
}