ccswarm 0.4.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
pub mod boundary;

use anyhow::Result;
use chrono::{DateTime, Utc};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::{Duration, Instant};

/// Core agent identity information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentIdentity {
    /// Unique agent identifier
    pub agent_id: String,

    /// Agent's specialization role
    pub specialization: AgentRole,

    /// Workspace path for this agent
    pub workspace_path: PathBuf,

    /// Environment variables for role identification
    pub env_vars: HashMap<String, String>,

    /// Session identifier (unique per startup)
    pub session_id: String,

    /// Parent orchestrator process ID
    pub parent_process_id: String,

    /// Timestamp of agent initialization
    pub initialized_at: DateTime<Utc>,
}

/// Agent specialization roles with their specific configurations
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Hash, Eq)]
pub enum AgentRole {
    Frontend {
        technologies: Vec<String>,
        responsibilities: Vec<String>,
        boundaries: Vec<String>,
    },
    Backend {
        technologies: Vec<String>,
        responsibilities: Vec<String>,
        boundaries: Vec<String>,
    },
    DevOps {
        technologies: Vec<String>,
        responsibilities: Vec<String>,
        boundaries: Vec<String>,
    },
    QA {
        technologies: Vec<String>,
        responsibilities: Vec<String>,
        boundaries: Vec<String>,
    },
    Master {
        oversight_roles: Vec<String>,
        quality_standards: QualityStandards,
    },
    Search {
        technologies: Vec<String>,
        responsibilities: Vec<String>,
        boundaries: Vec<String>,
    },
}

impl AgentRole {
    /// Get the name of the role
    pub fn name(&self) -> &str {
        match self {
            AgentRole::Frontend { .. } => "Frontend",
            AgentRole::Backend { .. } => "Backend",
            AgentRole::DevOps { .. } => "DevOps",
            AgentRole::QA { .. } => "QA",
            AgentRole::Master { .. } => "Master",
            AgentRole::Search { .. } => "Search",
        }
    }

    /// Get the string representation of the role
    /// This is an alias for the `name()` method following Rust conventions
    pub fn as_str(&self) -> &str {
        self.name()
    }

    /// Get the technologies associated with this role
    pub fn technologies(&self) -> Vec<String> {
        match self {
            AgentRole::Frontend { technologies, .. }
            | AgentRole::Backend { technologies, .. }
            | AgentRole::DevOps { technologies, .. }
            | AgentRole::QA { technologies, .. }
            | AgentRole::Search { technologies, .. } => technologies.clone(),
            AgentRole::Master { .. } => vec!["Orchestration".to_string()],
        }
    }

    /// Get the responsibilities for this role
    pub fn responsibilities(&self) -> Vec<String> {
        match self {
            AgentRole::Frontend {
                responsibilities, ..
            }
            | AgentRole::Backend {
                responsibilities, ..
            }
            | AgentRole::DevOps {
                responsibilities, ..
            }
            | AgentRole::QA {
                responsibilities, ..
            }
            | AgentRole::Search {
                responsibilities, ..
            } => responsibilities.clone(),
            AgentRole::Master {
                oversight_roles, ..
            } => oversight_roles.clone(),
        }
    }

    /// Get the boundaries for this role
    pub fn boundaries(&self) -> Vec<String> {
        match self {
            AgentRole::Frontend { boundaries, .. }
            | AgentRole::Backend { boundaries, .. }
            | AgentRole::DevOps { boundaries, .. }
            | AgentRole::QA { boundaries, .. }
            | AgentRole::Search { boundaries, .. } => boundaries.clone(),
            AgentRole::Master { .. } => vec!["No direct code implementation".to_string()],
        }
    }
}

/// Quality standards for code review and acceptance
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct QualityStandards {
    pub min_test_coverage: f64,
    pub max_complexity: u32,
    pub security_scan_required: bool,
    pub performance_threshold_secs: u64,
}

// Manual implementations for Hash and Eq that handle f64 properly
impl std::hash::Hash for QualityStandards {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // Convert f64 to bits for hashing
        self.min_test_coverage.to_bits().hash(state);
        self.max_complexity.hash(state);
        self.security_scan_required.hash(state);
        self.performance_threshold_secs.hash(state);
    }
}

impl Eq for QualityStandards {}

impl Default for QualityStandards {
    fn default() -> Self {
        Self {
            min_test_coverage: 0.85, // 85%
            max_complexity: 10,
            security_scan_required: true,
            performance_threshold_secs: 5,
        }
    }
}

/// Identity monitoring status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum IdentityStatus {
    Healthy,
    DriftDetected(String),
    BoundaryViolation(String),
    CriticalFailure(String),
}

/// Identity monitor for tracking agent behavior
#[derive(Debug)]
pub struct IdentityMonitor {
    pub agent_id: String,
    pub last_identity_check: Instant,
    pub identity_drift_threshold: Duration,
    pub response_parser: ResponseParser,
}

impl IdentityMonitor {
    pub fn new(agent_id: &str) -> Self {
        Self {
            agent_id: agent_id.to_string(),
            last_identity_check: Instant::now(),
            identity_drift_threshold: Duration::from_secs(300), // 5 minutes
            response_parser: ResponseParser::new(),
        }
    }

    /// Monitor a response for identity compliance
    pub async fn monitor_response(&mut self, response: &str) -> Result<IdentityStatus> {
        // Check for identity header
        let has_identity_header = self.check_identity_header(response);

        // Check boundary compliance
        let boundary_compliance = self.check_boundary_compliance(response);

        // Check delegation behavior
        let _delegation_behavior = self.check_delegation_behavior(response);

        if !has_identity_header {
            return Ok(IdentityStatus::DriftDetected(
                "Missing identity header".to_string(),
            ));
        }

        if !boundary_compliance {
            return Ok(IdentityStatus::BoundaryViolation(
                "Response indicates work outside specialization".to_string(),
            ));
        }

        self.last_identity_check = Instant::now();
        Ok(IdentityStatus::Healthy)
    }

    pub fn check_identity_header(&self, response: &str) -> bool {
        let required_pattern = format!("🤖 AGENT: {}", self.agent_id);
        response.contains(&required_pattern)
    }

    fn check_boundary_compliance(&self, response: &str) -> bool {
        // Check for indicators of boundary violations
        let violation_patterns = vec![
            r"working on backend code",
            r"modifying infrastructure",
            r"changing database schema",
        ];

        for pattern in violation_patterns {
            // These patterns are hardcoded and safe, so we use expect with a clear message
            let re = Regex::new(pattern).expect("Hardcoded regex pattern should always be valid");
            if re.is_match(response) {
                return false;
            }
        }
        true
    }

    fn check_delegation_behavior(&self, response: &str) -> bool {
        // Check for proper delegation patterns
        response.contains("DELEGATING TO:")
            || response.contains("outside my specialization")
            || !response.contains("I'll handle this")
    }

    /// Generate correction prompt for identity drift
    pub fn generate_correction_prompt(&self, workspace: &str, specialization: &str) -> String {
        format!(
            r#"
⚠️ IDENTITY DRIFT DETECTED

You seem to have forgotten your role. Let me remind you:

## YOUR IDENTITY
- You are the {} Agent
- Your workspace is {}
- You specialize ONLY in {}
- You must include identity headers in all responses

Please acknowledge your identity and continue with the current task while staying within your boundaries.

Remember to start your response with:
```
🤖 AGENT: {}
📁 WORKSPACE: {}
🎯 SCOPE: [Task assessment]
```
"#,
            self.agent_id, workspace, specialization, self.agent_id, workspace
        )
    }
}

/// Response parser for analyzing agent outputs
#[derive(Debug)]
pub struct ResponseParser {
    identity_regex: Regex,
    workspace_regex: Regex,
    scope_regex: Regex,
}

impl Default for ResponseParser {
    fn default() -> Self {
        Self::new()
    }
}

impl ResponseParser {
    pub fn new() -> Self {
        Self {
            identity_regex: Regex::new(r"🤖 AGENT: (.+)")
                .expect("Identity regex pattern should be valid"),
            workspace_regex: Regex::new(r"📁 WORKSPACE: (.+)")
                .expect("Workspace regex pattern should be valid"),
            scope_regex: Regex::new(r"🎯 SCOPE: (.+)")
                .expect("Scope regex pattern should be valid"),
        }
    }

    /// Parse identity information from response
    pub fn parse_identity(&self, response: &str) -> Option<(String, String, String)> {
        let agent = self
            .identity_regex
            .captures(response)
            .and_then(|cap| cap.get(1))
            .map(|m| m.as_str().to_string());

        let workspace = self
            .workspace_regex
            .captures(response)
            .and_then(|cap| cap.get(1))
            .map(|m| m.as_str().to_string());

        let scope = self
            .scope_regex
            .captures(response)
            .and_then(|cap| cap.get(1))
            .map(|m| m.as_str().to_string());

        match (agent, workspace, scope) {
            (Some(a), Some(w), Some(s)) => Some((a, w, s)),
            _ => None,
        }
    }
}

/// Default role configurations
pub fn default_frontend_role() -> AgentRole {
    AgentRole::Frontend {
        technologies: vec![
            "React".to_string(),
            "TypeScript".to_string(),
            "Tailwind CSS".to_string(),
            "Jest".to_string(),
            "Vite".to_string(),
        ],
        responsibilities: vec![
            "UI Component Development".to_string(),
            "State Management".to_string(),
            "Frontend Testing".to_string(),
            "User Experience".to_string(),
            "Accessibility".to_string(),
        ],
        boundaries: vec![
            "No backend API development".to_string(),
            "No database operations".to_string(),
            "No server-side logic".to_string(),
            "No infrastructure changes".to_string(),
            "No deployment scripts".to_string(),
        ],
    }
}

pub fn default_backend_role() -> AgentRole {
    AgentRole::Backend {
        technologies: vec![
            "Node.js".to_string(),
            "TypeScript".to_string(),
            "Express".to_string(),
            "PostgreSQL".to_string(),
            "Prisma".to_string(),
        ],
        responsibilities: vec![
            "API Development".to_string(),
            "Database Design".to_string(),
            "Authentication".to_string(),
            "Business Logic".to_string(),
            "Data Validation".to_string(),
        ],
        boundaries: vec![
            "No frontend UI code".to_string(),
            "No CSS styling".to_string(),
            "No infrastructure provisioning".to_string(),
            "No deployment automation".to_string(),
        ],
    }
}

pub fn default_devops_role() -> AgentRole {
    AgentRole::DevOps {
        technologies: vec![
            "Docker".to_string(),
            "Kubernetes".to_string(),
            "Terraform".to_string(),
            "AWS".to_string(),
            "GitHub Actions".to_string(),
        ],
        responsibilities: vec![
            "Infrastructure Provisioning".to_string(),
            "CI/CD Pipelines".to_string(),
            "Monitoring Setup".to_string(),
            "Security Configuration".to_string(),
            "Deployment Automation".to_string(),
        ],
        boundaries: vec![
            "No application code changes".to_string(),
            "No business logic implementation".to_string(),
            "No UI development".to_string(),
            "No database schema design".to_string(),
        ],
    }
}

pub fn default_qa_role() -> AgentRole {
    AgentRole::QA {
        technologies: vec![
            "Jest".to_string(),
            "Cypress".to_string(),
            "Playwright".to_string(),
            "Postman".to_string(),
            "K6".to_string(),
        ],
        responsibilities: vec![
            "Test Strategy".to_string(),
            "Test Implementation".to_string(),
            "Quality Assurance".to_string(),
            "Performance Testing".to_string(),
            "Security Testing".to_string(),
        ],
        boundaries: vec![
            "No production code changes".to_string(),
            "No feature implementation".to_string(),
            "No infrastructure changes".to_string(),
            "No deployment execution".to_string(),
        ],
    }
}

pub fn default_search_role() -> AgentRole {
    AgentRole::Search {
        technologies: vec![
            "Gemini CLI".to_string(),
            "Web Search".to_string(),
            "Information Retrieval".to_string(),
            "Search APIs".to_string(),
        ],
        responsibilities: vec![
            "Web Search".to_string(),
            "Information Gathering".to_string(),
            "Result Filtering".to_string(),
            "Query Optimization".to_string(),
            "Knowledge Discovery".to_string(),
        ],
        boundaries: vec![
            "No code implementation".to_string(),
            "No direct file modifications".to_string(),
            "Read-only information gathering".to_string(),
            "No execution of found code".to_string(),
            "No decision making beyond search".to_string(),
        ],
    }
}

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

    #[test]
    fn test_basic_role_functionality() {
        let frontend = default_frontend_role();
        assert_eq!(frontend.name(), "Frontend");

        let monitor = IdentityMonitor::new("Frontend");
        let valid_response = "🤖 AGENT: Frontend\n📁 WORKSPACE: /test\n🎯 SCOPE: UI work";
        assert!(monitor.check_identity_header(valid_response));
    }
}