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
/// Common traits and patterns used throughout ccswarm
///
/// This module defines reusable traits that provide common functionality
/// across different components of the system, promoting code reuse and
/// consistent interfaces.
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::Duration;

use crate::error::{CCSwarmError, Result};

/// Unique identifier trait for entities in the system
pub trait Identifiable {
    /// Get the unique identifier for this entity
    fn id(&self) -> &str;

    /// Get a human-readable name for this entity
    fn name(&self) -> &str {
        self.id()
    }
}

/// Trait for entities that can be serialized and have metadata
pub trait Describable: Identifiable {
    /// Get a description of this entity
    fn description(&self) -> Option<&str> {
        None
    }

    /// Get metadata associated with this entity
    fn metadata(&self) -> HashMap<String, String> {
        HashMap::new()
    }

    /// Get the creation timestamp
    fn created_at(&self) -> chrono::DateTime<chrono::Utc>;

    /// Get the last modified timestamp
    fn updated_at(&self) -> chrono::DateTime<chrono::Utc>;
}

/// Trait for entities that have a lifecycle state
pub trait Stateful {
    type State: Clone + PartialEq + std::fmt::Debug;

    /// Get the current state
    fn state(&self) -> &Self::State;

    /// Check if the entity is in a valid state for operations
    fn is_operational(&self) -> bool;

    /// Get state transition history if available
    fn state_history(&self) -> Vec<(Self::State, chrono::DateTime<chrono::Utc>)> {
        Vec::new()
    }
}

/// Trait for configurable entities
pub trait Configurable {
    type Config: Clone + Serialize + for<'de> Deserialize<'de>;

    /// Get the current configuration
    fn config(&self) -> &Self::Config;

    /// Update the configuration
    fn update_config(&mut self, config: Self::Config) -> Result<()>;

    /// Validate a configuration
    fn validate_config(config: &Self::Config) -> Result<()>;

    /// Get default configuration
    fn default_config() -> Self::Config;
}

/// Trait for entities that can be monitored for health and performance
#[async_trait]
pub trait Monitorable {
    type HealthStatus: Clone + std::fmt::Debug + Serialize;
    type Metrics: Clone + std::fmt::Debug + Serialize;

    /// Check the health of this entity
    async fn health_check(&self) -> Result<Self::HealthStatus>;

    /// Get current metrics
    async fn metrics(&self) -> Result<Self::Metrics>;

    /// Get historical metrics if available
    async fn historical_metrics(
        &self,
        since: chrono::DateTime<chrono::Utc>,
    ) -> Result<Vec<(chrono::DateTime<chrono::Utc>, Self::Metrics)>> {
        let _ = since;
        Ok(Vec::new())
    }
}

/// Trait for entities that can execute tasks asynchronously
#[async_trait]
pub trait Executable {
    type Input: Send + Sync;
    type Output: Send + Sync;
    type Context: Send + Sync;

    /// Execute a task with the given input and context
    async fn execute(&mut self, input: Self::Input, context: Self::Context)
    -> Result<Self::Output>;

    /// Check if this executor can handle the given input
    fn can_execute(&self, input: &Self::Input) -> bool;

    /// Get estimated execution time
    fn estimated_duration(&self, input: &Self::Input) -> Option<Duration> {
        let _ = input;
        None
    }
}

/// Trait for entities that can be paused and resumed
#[async_trait]
pub trait Pausable {
    /// Pause the entity
    async fn pause(&mut self) -> Result<()>;

    /// Resume the entity
    async fn resume(&mut self) -> Result<()>;

    /// Check if the entity is currently paused
    fn is_paused(&self) -> bool;
}

/// Trait for entities that support graceful shutdown
#[async_trait]
pub trait Shutdownable {
    /// Initiate graceful shutdown
    async fn shutdown(&mut self) -> Result<()>;

    /// Force immediate shutdown
    async fn force_shutdown(&mut self) -> Result<()> {
        self.shutdown().await
    }

    /// Check if shutdown is in progress
    fn is_shutting_down(&self) -> bool;

    /// Get shutdown timeout
    fn shutdown_timeout(&self) -> Duration {
        Duration::from_secs(30)
    }
}

/// Trait for entities that can validate their internal state
pub trait Validatable {
    type ValidationResult: std::fmt::Debug;

    /// Validate the current state of the entity
    fn validate(&self) -> Result<Self::ValidationResult>;

    /// Auto-fix validation issues if possible
    fn auto_fix(&mut self) -> Result<Vec<String>> {
        Ok(Vec::new())
    }
}

/// Trait for entities that support event notification
#[async_trait]
pub trait EventEmitter {
    type Event: Clone + Send + Sync + std::fmt::Debug;

    /// Emit an event
    async fn emit_event(&self, event: Self::Event) -> Result<()>;

    /// Subscribe to events (returns a channel receiver)
    async fn subscribe(&self) -> Result<tokio::sync::mpsc::Receiver<Self::Event>>;
}

/// Trait for caching and memoization support
#[async_trait]
pub trait Cacheable {
    type Key: Clone + Eq + std::hash::Hash + Send + Sync;
    type Value: Clone + Send + Sync;

    /// Get value from cache
    async fn get(&self, key: &Self::Key) -> Option<Self::Value>;

    /// Set value in cache
    async fn set(&mut self, key: Self::Key, value: Self::Value) -> Result<()>;

    /// Remove value from cache
    async fn remove(&mut self, key: &Self::Key) -> Result<Option<Self::Value>>;

    /// Clear all cached values
    async fn clear(&mut self) -> Result<()>;

    /// Get cache statistics
    async fn stats(&self) -> CacheStats;
}

/// Cache statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheStats {
    pub hits: u64,
    pub misses: u64,
    pub entries: usize,
    pub memory_usage: usize,
    pub hit_rate: f64,
}

impl CacheStats {
    pub fn new() -> Self {
        Self {
            hits: 0,
            misses: 0,
            entries: 0,
            memory_usage: 0,
            hit_rate: 0.0,
        }
    }

    pub fn calculate_hit_rate(&mut self) {
        let total = self.hits + self.misses;
        self.hit_rate = if total > 0 {
            self.hits as f64 / total as f64
        } else {
            0.0
        };
    }
}

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

/// Trait for retry logic with exponential backoff
#[async_trait]
pub trait Retryable {
    type Operation: Send + Sync;
    type Result: Send + Sync;

    /// Execute operation with retry logic
    async fn retry_with_backoff<F, Fut>(
        &self,
        operation: F,
        max_attempts: u32,
        initial_delay: Duration,
        max_delay: Duration,
    ) -> Result<Self::Result>
    where
        F: Fn() -> Fut + Send + Sync,
        Fut: std::future::Future<Output = Result<Self::Result>> + Send;

    /// Get default retry configuration
    fn default_retry_config() -> RetryConfig {
        RetryConfig::default()
    }
}

/// Retry configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryConfig {
    pub max_attempts: u32,
    pub initial_delay: Duration,
    pub max_delay: Duration,
    pub backoff_multiplier: f64,
    pub jitter: bool,
}

impl Default for RetryConfig {
    fn default() -> Self {
        Self {
            max_attempts: 3,
            initial_delay: Duration::from_millis(100),
            max_delay: Duration::from_secs(30),
            backoff_multiplier: 2.0,
            jitter: true,
        }
    }
}

/// Trait for resource cleanup
#[async_trait]
pub trait Cleanupable {
    /// Clean up resources
    async fn cleanup(&mut self) -> Result<CleanupReport>;

    /// Check if cleanup is needed
    fn needs_cleanup(&self) -> bool {
        false
    }

    /// Get cleanup schedule
    fn cleanup_schedule(&self) -> Option<Duration> {
        None
    }
}

/// Cleanup report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CleanupReport {
    pub items_cleaned: usize,
    pub bytes_freed: usize,
    pub duration: Duration,
    pub errors: Vec<String>,
}

impl CleanupReport {
    pub fn new() -> Self {
        Self {
            items_cleaned: 0,
            bytes_freed: 0,
            duration: Duration::from_millis(0),
            errors: Vec::new(),
        }
    }

    pub fn with_items(mut self, count: usize) -> Self {
        self.items_cleaned = count;
        self
    }

    pub fn with_bytes_freed(mut self, bytes: usize) -> Self {
        self.bytes_freed = bytes;
        self
    }

    pub fn with_duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    pub fn add_error<S: Into<String>>(mut self, error: S) -> Self {
        self.errors.push(error.into());
        self
    }
}

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

/// Trait for serializable entities
#[allow(async_fn_in_trait)]
pub trait Persistable: Serialize + for<'de> Deserialize<'de> {
    /// Serialize to bytes
    fn to_bytes(&self) -> Result<Vec<u8>> {
        serde_json::to_vec(self).map_err(CCSwarmError::from)
    }

    /// Deserialize from bytes
    fn from_bytes(bytes: &[u8]) -> Result<Self>
    where
        Self: Sized,
    {
        serde_json::from_slice(bytes).map_err(CCSwarmError::from)
    }

    /// Save to file
    async fn save_to_file<P: AsRef<std::path::Path> + Send>(&self, path: P) -> Result<()> {
        let bytes = self.to_bytes()?;
        tokio::fs::write(path, bytes)
            .await
            .map_err(CCSwarmError::from)
    }

    /// Load from file
    async fn load_from_file<P: AsRef<std::path::Path> + Send>(path: P) -> Result<Self>
    where
        Self: Sized,
    {
        let bytes = tokio::fs::read(path).await.map_err(CCSwarmError::from)?;
        Self::from_bytes(&bytes)
    }
}

/// Automatically implement Persistable for types that implement Serialize + Deserialize
impl<T> Persistable for T where T: Serialize + for<'de> Deserialize<'de> {}

/// Helper macro for generating unique IDs
#[macro_export]
macro_rules! generate_id {
    ($prefix:expr) => {
        format!("{}-{}", $prefix, uuid::Uuid::new_v4())
    };
    () => {
        uuid::Uuid::new_v4().to_string()
    };
}

/// Helper macro for creating timestamped entities
#[macro_export]
macro_rules! with_timestamp {
    ($entity:expr) => {{
        let now = chrono::Utc::now();
        $entity.created_at = now;
        $entity.updated_at = now;
        $entity
    }};
}

/// Helper macro for implementing common trait combinations
#[macro_export]
macro_rules! impl_entity_traits {
    ($type:ty, $id_field:ident, $name_field:ident) => {
        impl $crate::traits::Identifiable for $type {
            fn id(&self) -> &str {
                &self.$id_field
            }

            fn name(&self) -> &str {
                &self.$name_field
            }
        }
    };
    ($type:ty, $id_field:ident) => {
        impl $crate::traits::Identifiable for $type {
            fn id(&self) -> &str {
                &self.$id_field
            }
        }
    };
}