ccswarm 0.4.5

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
619
620
621
622
623
624
625
626
use thiserror::Error;

/// Main error type for ccswarm with structured error handling
///
/// This enum provides comprehensive error types for all ccswarm operations,
/// with detailed context and proper error chaining using `thiserror`.
///
/// # Examples
///
/// ```rust
/// use ccswarm::error::CCSwarmError;
///
/// // Creating a configuration error
/// let config_error = CCSwarmError::Configuration {
///     message: "Invalid agent configuration".to_string(),
///     source: None,
/// };
/// ```
#[derive(Error, Debug)]
pub enum CCSwarmError {
    /// IO operation failed
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// JSON serialization/deserialization failed
    #[error("JSON error: {0}")]
    SerdeJson(#[from] serde_json::Error),

    /// Configuration related error
    #[error("Configuration error: {message}")]
    Configuration {
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Agent operation failed
    #[error("Agent error [{agent_id}]: {message}")]
    Agent {
        agent_id: String,
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Session management error
    #[error("Session error [{session_id}]: {message}")]
    Session {
        session_id: String,
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Task execution error
    #[error("Task error [{task_id}]: {message}")]
    Task {
        task_id: String,
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Network communication error
    #[error("Network error: {message}")]
    Network {
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Orchestrator coordination error
    #[error("Orchestrator error: {message}")]
    Orchestrator {
        message: String,
        task_id: Option<String>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Git operation error
    #[error("Git error: {message}")]
    Git {
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Template processing error
    #[error("Template error: {message}")]
    Template {
        message: String,
        template_name: Option<String>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Extension system error
    #[error("Extension error [{extension_id}]: {message}")]
    Extension {
        extension_id: String,
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Resource management error
    #[error("Resource error: {message}")]
    Resource {
        message: String,
        resource_type: Option<String>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// Authentication/authorization error
    #[error("Authentication error: {message}")]
    Auth {
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// User-facing error with helpful message
    #[error("{message}")]
    UserError {
        message: String,
        suggestion: Option<String>,
    },

    /// Generic error for cases not covered above
    #[error("{message}")]
    Other {
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },
}

impl From<String> for CCSwarmError {
    fn from(error: String) -> Self {
        Self::Other {
            message: error,
            source: None,
        }
    }
}

impl From<&str> for CCSwarmError {
    fn from(error: &str) -> Self {
        Self::Other {
            message: error.to_string(),
            source: None,
        }
    }
}

/// Result type alias for ccswarm operations
pub type Result<T> = std::result::Result<T, CCSwarmError>;

/// Helper trait for creating structured errors
pub trait ErrorContext<T> {
    /// Add context to an error
    fn with_context<F>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> String;

    /// Add context with error source
    fn with_context_and_source<F, E>(self, f: F, source: E) -> Result<T>
    where
        F: FnOnce() -> String,
        E: std::error::Error + Send + Sync + 'static;
}

impl<T, E> ErrorContext<T> for std::result::Result<T, E>
where
    E: std::error::Error + Send + Sync + 'static,
{
    fn with_context<F>(self, f: F) -> Result<T>
    where
        F: FnOnce() -> String,
    {
        self.map_err(|e| CCSwarmError::Other {
            message: f(),
            source: Some(Box::new(e)),
        })
    }

    fn with_context_and_source<F, S>(self, f: F, source: S) -> Result<T>
    where
        F: FnOnce() -> String,
        S: std::error::Error + Send + Sync + 'static,
    {
        self.map_err(|_| CCSwarmError::Other {
            message: f(),
            source: Some(Box::new(source)),
        })
    }
}

/// Convenience methods for creating specific error types
impl CCSwarmError {
    /// Create a configuration error
    pub fn config<S: Into<String>>(message: S) -> Self {
        Self::Configuration {
            message: message.into(),
            source: None,
        }
    }

    /// Create an agent error
    pub fn agent<S: Into<String>, I: Into<String>>(agent_id: I, message: S) -> Self {
        Self::Agent {
            agent_id: agent_id.into(),
            message: message.into(),
            source: None,
        }
    }

    /// Create a session error
    pub fn session<S: Into<String>, I: Into<String>>(session_id: I, message: S) -> Self {
        Self::Session {
            session_id: session_id.into(),
            message: message.into(),
            source: None,
        }
    }

    /// Create an orchestrator error
    pub fn orchestrator<S: Into<String>>(message: S, task_id: Option<String>) -> Self {
        Self::Orchestrator {
            message: message.into(),
            task_id,
            source: None,
        }
    }

    /// Create a task error
    pub fn task<S: Into<String>, I: Into<String>>(task_id: I, message: S) -> Self {
        Self::Task {
            task_id: task_id.into(),
            message: message.into(),
            source: None,
        }
    }

    /// Create a network error
    pub fn network<S: Into<String>>(message: S) -> Self {
        Self::Network {
            message: message.into(),
            source: None,
        }
    }

    /// Create a git error
    pub fn git<S: Into<String>>(message: S) -> Self {
        Self::Git {
            message: message.into(),
            source: None,
        }
    }

    /// Create a template error
    pub fn template<S: Into<String>>(message: S) -> Self {
        Self::Template {
            message: message.into(),
            template_name: None,
            source: None,
        }
    }

    /// Create a template error with template name
    pub fn template_with_name<S: Into<String>, N: Into<String>>(
        message: S,
        template_name: N,
    ) -> Self {
        Self::Template {
            message: message.into(),
            template_name: Some(template_name.into()),
            source: None,
        }
    }

    /// Create an extension error
    pub fn extension<S: Into<String>, I: Into<String>>(extension_id: I, message: S) -> Self {
        Self::Extension {
            extension_id: extension_id.into(),
            message: message.into(),
            source: None,
        }
    }

    /// Create a resource error
    pub fn resource<S: Into<String>>(message: S) -> Self {
        Self::Resource {
            message: message.into(),
            resource_type: None,
            source: None,
        }
    }

    /// Create a resource error with type
    pub fn resource_with_type<S: Into<String>, T: Into<String>>(
        message: S,
        resource_type: T,
    ) -> Self {
        Self::Resource {
            message: message.into(),
            resource_type: Some(resource_type.into()),
            source: None,
        }
    }

    /// Create an authentication error
    pub fn auth<S: Into<String>>(message: S) -> Self {
        Self::Auth {
            message: message.into(),
            source: None,
        }
    }

    /// Create a user-friendly error with suggestion
    pub fn user_error<S: Into<String>>(message: S) -> Self {
        Self::UserError {
            message: message.into(),
            suggestion: None,
        }
    }

    /// Create a user-friendly error with suggestion
    pub fn user_error_with_suggestion<S: Into<String>, T: Into<String>>(
        message: S,
        suggestion: T,
    ) -> Self {
        Self::UserError {
            message: message.into(),
            suggestion: Some(suggestion.into()),
        }
    }

    /// Add a source error to this error
    pub fn with_source<E>(mut self, source: E) -> Self
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        match &mut self {
            Self::Configuration { source: s, .. }
            | Self::Agent { source: s, .. }
            | Self::Session { source: s, .. }
            | Self::Task { source: s, .. }
            | Self::Network { source: s, .. }
            | Self::Git { source: s, .. }
            | Self::Template { source: s, .. }
            | Self::Extension { source: s, .. }
            | Self::Resource { source: s, .. }
            | Self::Auth { source: s, .. }
            | Self::Other { source: s, .. } => {
                *s = Some(Box::new(source));
            }
            _ => {}
        }
        self
    }

    /// Check if this is a recoverable error
    pub fn is_recoverable(&self) -> bool {
        matches!(
            self,
            Self::Network { .. } | Self::Io(_) | Self::Task { .. } | Self::Resource { .. }
        )
    }

    /// Check if this error should be retried
    ///
    /// Returns true for transient errors that may succeed on retry:
    /// - Network errors (connection issues, timeouts)
    /// - Resource errors (temporary resource exhaustion)
    /// - Certain IO errors (connection reset, broken pipe, etc.)
    pub fn should_retry(&self) -> bool {
        match self {
            Self::Network { .. } | Self::Resource { .. } => true,
            Self::Io(io_err) => {
                // Retry transient IO errors
                matches!(
                    io_err.kind(),
                    std::io::ErrorKind::ConnectionReset
                        | std::io::ErrorKind::ConnectionAborted
                        | std::io::ErrorKind::BrokenPipe
                        | std::io::ErrorKind::TimedOut
                        | std::io::ErrorKind::Interrupted
                        | std::io::ErrorKind::WouldBlock
                )
            }
            _ => false,
        }
    }

    /// Get the suggested delay before retrying this error
    ///
    /// Returns a duration based on the error type:
    /// - Network errors: 1 second (allow network recovery)
    /// - Resource errors: 2 seconds (allow resource cleanup)
    /// - IO errors: 500ms (quick retry for transient issues)
    pub fn suggested_retry_delay(&self) -> std::time::Duration {
        match self {
            Self::Network { .. } => std::time::Duration::from_secs(1),
            Self::Resource { .. } => std::time::Duration::from_secs(2),
            Self::Io(_) => std::time::Duration::from_millis(500),
            _ => std::time::Duration::from_secs(1),
        }
    }

    /// Get the maximum number of retries recommended for this error
    ///
    /// Returns different limits based on error type:
    /// - Network errors: 3 retries
    /// - Resource errors: 5 retries (may need more time to recover)
    /// - IO errors: 2 retries
    /// - Non-retryable errors: 0 retries
    pub fn max_retries(&self) -> u32 {
        if !self.should_retry() {
            return 0;
        }
        match self {
            Self::Network { .. } => 3,
            Self::Resource { .. } => 5,
            Self::Io(_) => 2,
            _ => 0,
        }
    }

    /// Get error severity level
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            Self::Auth { .. } | Self::Configuration { .. } => ErrorSeverity::Critical,
            Self::Agent { .. }
            | Self::Session { .. }
            | Self::Extension { .. }
            | Self::Orchestrator { .. } => ErrorSeverity::High,
            Self::Task { .. } | Self::Git { .. } | Self::Template { .. } => ErrorSeverity::Medium,
            Self::Network { .. } | Self::Resource { .. } => ErrorSeverity::Low,
            Self::Io(_) | Self::SerdeJson(_) => ErrorSeverity::Medium,
            Self::UserError { .. } => ErrorSeverity::Info,
            Self::Other { .. } => ErrorSeverity::Medium,
        }
    }
}

/// Error severity levels for monitoring and alerting
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ErrorSeverity {
    /// Informational - no action needed
    Info,
    /// Low severity - monitoring recommended
    Low,
    /// Medium severity - investigation needed
    Medium,
    /// High severity - immediate attention required
    High,
    /// Critical severity - system failure
    Critical,
}

impl std::fmt::Display for ErrorSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Info => write!(f, "INFO"),
            Self::Low => write!(f, "LOW"),
            Self::Medium => write!(f, "MEDIUM"),
            Self::High => write!(f, "HIGH"),
            Self::Critical => write!(f, "CRITICAL"),
        }
    }
}

// ============================================================================
// FatalError Trait - Inspired by Zellij's error classification pattern
// ============================================================================

/// Trait for classifying errors as fatal or non-fatal.
///
/// Fatal errors indicate unrecoverable conditions that should cause the
/// operation to abort completely. Non-fatal errors can be handled gracefully
/// with fallback behavior.
///
/// # Example
/// ```rust
/// use ccswarm::error::{FatalError, ClassifiedError};
///
/// fn process() -> Result<(), ClassifiedError<std::io::Error>> {
///     // Mark an error as fatal
///     std::fs::read("critical_config.json")
///         .map_err(|e| ClassifiedError::fatal(e))?;
///     Ok(())
/// }
/// ```
pub trait FatalError: Sized {
    /// Mark this error as fatal (unrecoverable)
    fn fatal(self) -> ClassifiedError<Self>;

    /// Mark this error as non-fatal (recoverable)
    fn non_fatal(self) -> ClassifiedError<Self>;
}

/// An error wrapper that classifies the error as fatal or non-fatal.
///
/// This enables graceful degradation by allowing callers to handle
/// non-fatal errors differently from fatal ones.
#[derive(Debug)]
pub struct ClassifiedError<E> {
    /// The underlying error
    pub error: E,
    /// Whether this error is fatal
    pub is_fatal: bool,
}

impl<E> ClassifiedError<E> {
    /// Create a fatal error
    pub fn fatal(error: E) -> Self {
        Self {
            error,
            is_fatal: true,
        }
    }

    /// Create a non-fatal error
    pub fn non_fatal(error: E) -> Self {
        Self {
            error,
            is_fatal: false,
        }
    }

    /// Check if this error is fatal
    pub fn is_fatal(&self) -> bool {
        self.is_fatal
    }

    /// Get the underlying error
    pub fn into_inner(self) -> E {
        self.error
    }

    /// Map the error to a different type
    pub fn map<F, O>(self, f: F) -> ClassifiedError<O>
    where
        F: FnOnce(E) -> O,
    {
        ClassifiedError {
            error: f(self.error),
            is_fatal: self.is_fatal,
        }
    }
}

impl<E: std::fmt::Display> std::fmt::Display for ClassifiedError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_fatal {
            write!(f, "[FATAL] {}", self.error)
        } else {
            write!(f, "{}", self.error)
        }
    }
}

impl<E: std::error::Error + 'static> std::error::Error for ClassifiedError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.error)
    }
}

/// Implement FatalError for any error type
impl<E> FatalError for E {
    fn fatal(self) -> ClassifiedError<Self> {
        ClassifiedError::fatal(self)
    }

    fn non_fatal(self) -> ClassifiedError<Self> {
        ClassifiedError::non_fatal(self)
    }
}

/// Extension trait for Result types to easily classify errors
pub trait ResultFatalExt<T, E> {
    /// Mark the error as fatal if Result is Err
    fn fatal_on_err(self) -> std::result::Result<T, ClassifiedError<E>>;

    /// Mark the error as non-fatal if Result is Err
    fn non_fatal_on_err(self) -> std::result::Result<T, ClassifiedError<E>>;
}

impl<T, E> ResultFatalExt<T, E> for std::result::Result<T, E> {
    fn fatal_on_err(self) -> std::result::Result<T, ClassifiedError<E>> {
        self.map_err(ClassifiedError::fatal)
    }

    fn non_fatal_on_err(self) -> std::result::Result<T, ClassifiedError<E>> {
        self.map_err(ClassifiedError::non_fatal)
    }
}

/// Determine if a CCSwarmError should be treated as fatal
impl CCSwarmError {
    /// Check if this error should be treated as fatal
    ///
    /// Fatal errors are those that indicate system-level failures
    /// that cannot be recovered from:
    /// - Authentication failures
    /// - Critical configuration errors
    /// - Orchestrator failures
    pub fn is_fatal(&self) -> bool {
        matches!(
            self,
            Self::Auth { .. } | Self::Configuration { .. } | Self::Orchestrator { .. }
        )
    }

    /// Convert to a ClassifiedError based on error type
    pub fn classify(self) -> ClassifiedError<Self> {
        if self.is_fatal() {
            ClassifiedError::fatal(self)
        } else {
            ClassifiedError::non_fatal(self)
        }
    }
}