selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
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
use std::path::PathBuf;
use thiserror::Error;

/// The central error type for the Selfware system.
///
/// This hierarchy enables programmatic recovery and unified error handling
/// across agent, API, tools, and safety layers.
#[derive(Error, Debug)]
pub enum SelfwareError {
    #[error("Agent error: {0}")]
    Agent(#[from] AgentError),

    #[error("API error: {0}")]
    Api(#[from] ApiError),

    #[error("Tool error: {0}")]
    Tool(#[from] ToolError),

    #[error("Safety error: {0}")]
    Safety(#[from] SafetyError),

    #[error("Session error: {0}")]
    Session(#[from] SessionError),

    #[error("Resource error: {0}")]
    Resource(#[from] ResourceError),

    #[error("Configuration error: {0}")]
    Config(String),

    #[error("Internal error: {0}")]
    Internal(String),

    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

#[derive(Error, Debug)]
pub enum AgentError {
    #[error("Tool '{tool_name}' requires confirmation but running in non-interactive mode. Use --yolo to auto-approve tools, or run interactively.")]
    ConfirmationRequired { tool_name: String },

    #[error("Iteration limit reached ({limit})")]
    IterationLimit { limit: usize },

    #[error("Step timeout after {seconds} seconds")]
    StepTimeout { seconds: u64 },

    #[error("Invalid state transition from {from} to {to}")]
    InvalidStateTransition { from: String, to: String },

    #[error("Task cancelled by user")]
    Cancelled,

    #[error("Missing system prompt")]
    MissingSystemPrompt,

    #[error("Agent loop panicked: {0}")]
    Panic(String),
}

#[derive(Error, Debug)]
pub enum ApiError {
    #[error("API Request timed out")]
    Timeout,

    #[error("Rate limit exceeded. Retry after {retry_after_secs:?} seconds")]
    RateLimit { retry_after_secs: Option<u64> },

    #[error("Authentication failed: {0}")]
    Authentication(String),

    #[error("API returned status {status}: {message}")]
    HttpStatus { status: u16, message: String },

    #[error("Failed to parse API response: {0}")]
    Parse(String),

    #[error("Network error: {0}")]
    Network(String),

    #[error("Model not found: {0}")]
    ModelNotFound(String),
}

#[derive(Error, Debug)]
pub enum ToolError {
    #[error("Tool '{name}' failed: {message}")]
    Execution { name: String, message: String },

    #[error("Tool '{name}' not found")]
    NotFound { name: String },

    #[error("Invalid arguments for tool '{name}': {message}")]
    InvalidArguments { name: String, message: String },

    #[error("Tool execution timed out")]
    Timeout,
}

#[derive(Error, Debug)]
pub enum SafetyError {
    #[error("Path blocked by safety policy: {path}")]
    BlockedPath { path: String },

    #[error("Dangerous command blocked: {command} ({reason})")]
    BlockedCommand { command: String, reason: String },

    #[error("Potential secret detected in content: {finding}")]
    SecretDetected { finding: String },

    #[error("Action requires manual confirmation: {action}")]
    ConfirmationRequired { action: String },

    #[error("Path traversal attempt detected: {path}")]
    PathTraversal { path: String },
}

#[derive(Error, Debug)]
pub enum SessionError {
    #[error("Failed to save checkpoint: {0}")]
    CheckpointSave(String),

    #[error("Failed to load checkpoint: {0}")]
    CheckpointLoad(String),

    #[error("Storage error at {path}: {message}")]
    Storage { path: PathBuf, message: String },

    #[error("Session history corrupted: {0}")]
    HistoryCorrupted(String),
}

pub type Result<T> = std::result::Result<T, SelfwareError>;

/// Check if an anyhow error is a confirmation-required error (fatal in non-interactive mode)
pub fn is_confirmation_error(e: &anyhow::Error) -> bool {
    // Check if wrapped as SelfwareError::Agent(AgentError::ConfirmationRequired)
    if let Some(SelfwareError::Agent(AgentError::ConfirmationRequired { .. })) =
        e.downcast_ref::<SelfwareError>()
    {
        return true;
    }

    // Also check if AgentError was returned directly into anyhow (e.g. from execution.rs)
    if let Some(AgentError::ConfirmationRequired { .. }) = e.downcast_ref::<AgentError>() {
        return true;
    }

    false
}

#[derive(Error, Debug)]
pub enum ResourceError {
    #[error("Memory exhausted: {0}")]
    MemoryExhausted(String),

    #[error("GPU error: {0}")]
    Gpu(String),

    #[error("Disk exhausted: {0}")]
    DiskExhausted(String),

    #[error("Resource quota exceeded for {resource}: used {used}, limit {limit}")]
    QuotaExceeded {
        resource: String,
        used: u64,
        limit: u64,
    },

    #[error("Resource unavailable: {0}")]
    Unavailable(String),
}

pub const EXIT_SUCCESS: u8 = 0;
pub const EXIT_ERROR: u8 = 1;
pub const EXIT_CONFIG_ERROR: u8 = 2;
pub const EXIT_API_ERROR: u8 = 4;
pub const EXIT_SAFETY_ERROR: u8 = 5;
pub const EXIT_CONFIRMATION_REQUIRED: u8 = 6;

/// Determine the appropriate process exit code for an error.
pub fn get_exit_code(e: &anyhow::Error) -> u8 {
    if is_confirmation_error(e) {
        return EXIT_CONFIRMATION_REQUIRED;
    }

    if let Some(selfware_err) = e.downcast_ref::<SelfwareError>() {
        return match selfware_err {
            SelfwareError::Config(_) => EXIT_CONFIG_ERROR,
            SelfwareError::Api(_) => EXIT_API_ERROR,
            SelfwareError::Safety(_) => EXIT_SAFETY_ERROR,
            _ => EXIT_ERROR,
        };
    }

    // Direct enum unwraps fallback
    if e.downcast_ref::<ApiError>().is_some() {
        return EXIT_API_ERROR;
    }
    if e.downcast_ref::<SafetyError>().is_some() {
        return EXIT_SAFETY_ERROR;
    }
    if e.downcast_ref::<AgentError>().is_some() {
        return EXIT_ERROR;
    }

    // Fallback string matching only for cases where specific types aren't available
    let msg = e.to_string().to_lowercase();
    if msg.contains("config") {
        return EXIT_CONFIG_ERROR;
    } else if msg.contains("api error") || msg.contains("network") {
        return EXIT_API_ERROR;
    } else if msg.contains("safety") || msg.contains("blocked") {
        return EXIT_SAFETY_ERROR;
    }

    EXIT_ERROR
}

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

    // =========================================================================
    // is_confirmation_error tests
    // =========================================================================

    #[test]
    fn test_is_confirmation_error_with_selfware_agent_wrapper() {
        // SelfwareError::Agent(AgentError::ConfirmationRequired) wrapped in anyhow
        let err = SelfwareError::Agent(AgentError::ConfirmationRequired {
            tool_name: "shell_exec".to_string(),
        });
        let anyhow_err: anyhow::Error = err.into();
        assert!(
            is_confirmation_error(&anyhow_err),
            "SelfwareError::Agent(ConfirmationRequired) should be detected"
        );
    }

    #[test]
    fn test_is_confirmation_error_with_direct_agent_error() {
        // AgentError::ConfirmationRequired put directly into anyhow (no SelfwareError wrapper)
        let err: anyhow::Error = AgentError::ConfirmationRequired {
            tool_name: "file_write".to_string(),
        }
        .into();
        assert!(
            is_confirmation_error(&err),
            "Direct AgentError::ConfirmationRequired should be detected"
        );
    }

    #[test]
    fn test_is_confirmation_error_plain_anyhow() {
        let err = anyhow::anyhow!("something went wrong");
        assert!(
            !is_confirmation_error(&err),
            "Plain anyhow error should not be a confirmation error"
        );
    }

    #[test]
    fn test_is_confirmation_error_api_error() {
        let err: anyhow::Error = SelfwareError::Api(ApiError::Timeout).into();
        assert!(
            !is_confirmation_error(&err),
            "ApiError::Timeout should not be a confirmation error"
        );
    }

    #[test]
    fn test_is_confirmation_error_tool_error() {
        let err: anyhow::Error = SelfwareError::Tool(ToolError::NotFound {
            name: "missing_tool".to_string(),
        })
        .into();
        assert!(
            !is_confirmation_error(&err),
            "ToolError should not be a confirmation error"
        );
    }

    #[test]
    fn test_is_confirmation_error_safety_error() {
        let err: anyhow::Error = SelfwareError::Safety(SafetyError::BlockedPath {
            path: "/etc/passwd".to_string(),
        })
        .into();
        assert!(
            !is_confirmation_error(&err),
            "SafetyError should not be a confirmation error"
        );
    }

    #[test]
    fn test_is_confirmation_error_safety_confirmation_required() {
        // SafetyError also has a ConfirmationRequired variant, but it is NOT the agent one
        let err: anyhow::Error = SelfwareError::Safety(SafetyError::ConfirmationRequired {
            action: "delete all files".to_string(),
        })
        .into();
        assert!(
            !is_confirmation_error(&err),
            "SafetyError::ConfirmationRequired is not the agent-level confirmation error"
        );
    }

    #[test]
    fn test_is_confirmation_error_other_agent_errors() {
        let cases: Vec<AgentError> = vec![
            AgentError::IterationLimit { limit: 10 },
            AgentError::StepTimeout { seconds: 30 },
            AgentError::Cancelled,
            AgentError::MissingSystemPrompt,
            AgentError::Panic("oops".to_string()),
            AgentError::InvalidStateTransition {
                from: "A".to_string(),
                to: "B".to_string(),
            },
        ];
        for agent_err in cases {
            let display = format!("{}", agent_err);
            let err: anyhow::Error = agent_err.into();
            assert!(
                !is_confirmation_error(&err),
                "AgentError '{}' should not be a confirmation error",
                display
            );
        }
    }

    // =========================================================================
    // get_exit_code tests
    // =========================================================================

    #[test]
    fn test_exit_code_confirmation_required_via_selfware_wrapper() {
        let err: anyhow::Error = SelfwareError::Agent(AgentError::ConfirmationRequired {
            tool_name: "shell_exec".to_string(),
        })
        .into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_CONFIRMATION_REQUIRED,
            "ConfirmationRequired should yield exit code 6"
        );
    }

    #[test]
    fn test_exit_code_confirmation_required_direct() {
        let err: anyhow::Error = AgentError::ConfirmationRequired {
            tool_name: "git_push".to_string(),
        }
        .into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_CONFIRMATION_REQUIRED,
            "Direct AgentError::ConfirmationRequired should yield exit code 6"
        );
    }

    #[test]
    fn test_exit_code_config_error() {
        let err: anyhow::Error = SelfwareError::Config("missing API key".to_string()).into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_CONFIG_ERROR,
            "Config error should yield exit code 2"
        );
    }

    #[test]
    fn test_exit_code_api_error_wrapped() {
        let err: anyhow::Error =
            SelfwareError::Api(ApiError::Authentication("bad key".to_string())).into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_API_ERROR,
            "Api error should yield exit code 4"
        );
    }

    #[test]
    fn test_exit_code_api_error_direct() {
        // ApiError placed directly into anyhow (not wrapped in SelfwareError)
        let err: anyhow::Error = ApiError::Timeout.into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_API_ERROR,
            "Direct ApiError should yield exit code 4"
        );
    }

    #[test]
    fn test_exit_code_safety_error_wrapped() {
        let err: anyhow::Error = SelfwareError::Safety(SafetyError::BlockedCommand {
            command: "rm -rf /".to_string(),
            reason: "dangerous".to_string(),
        })
        .into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_SAFETY_ERROR,
            "Safety error should yield exit code 5"
        );
    }

    #[test]
    fn test_exit_code_safety_error_direct() {
        let err: anyhow::Error = SafetyError::SecretDetected {
            finding: "AWS key".to_string(),
        }
        .into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_SAFETY_ERROR,
            "Direct SafetyError should yield exit code 5"
        );
    }

    #[test]
    fn test_exit_code_agent_error_non_confirmation() {
        // Non-confirmation AgentError should yield generic EXIT_ERROR
        let err: anyhow::Error =
            SelfwareError::Agent(AgentError::IterationLimit { limit: 50 }).into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_ERROR,
            "Non-confirmation agent error should yield exit code 1"
        );
    }

    #[test]
    fn test_exit_code_tool_error() {
        let err: anyhow::Error = SelfwareError::Tool(ToolError::Execution {
            name: "shell_exec".to_string(),
            message: "command not found".to_string(),
        })
        .into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_ERROR,
            "Tool error should yield exit code 1"
        );
    }

    #[test]
    fn test_exit_code_session_error() {
        let err: anyhow::Error =
            SelfwareError::Session(SessionError::CheckpointSave("disk full".to_string())).into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_ERROR,
            "Session error should yield exit code 1"
        );
    }

    #[test]
    fn test_exit_code_internal_error() {
        let err: anyhow::Error = SelfwareError::Internal("unexpected state".to_string()).into();
        assert_eq!(
            get_exit_code(&err),
            EXIT_ERROR,
            "Internal error should yield exit code 1"
        );
    }

    #[test]
    fn test_exit_code_plain_anyhow_default() {
        // A plain anyhow error with no recognizable keywords falls back to EXIT_ERROR
        let err = anyhow::anyhow!("something completely unexpected happened");
        assert_eq!(
            get_exit_code(&err),
            EXIT_ERROR,
            "Unrecognized plain anyhow error should yield exit code 1"
        );
    }

    #[test]
    fn test_exit_code_string_fallback_config() {
        // Plain anyhow with "config" in the message triggers string fallback
        let err = anyhow::anyhow!("config file not found");
        assert_eq!(
            get_exit_code(&err),
            EXIT_CONFIG_ERROR,
            "String containing 'config' should fallback to exit code 2"
        );
    }

    #[test]
    fn test_exit_code_string_fallback_api_error() {
        let err = anyhow::anyhow!("api error: rate limited");
        assert_eq!(
            get_exit_code(&err),
            EXIT_API_ERROR,
            "String containing 'api error' should fallback to exit code 4"
        );
    }

    #[test]
    fn test_exit_code_string_fallback_network() {
        let err = anyhow::anyhow!("network connection refused");
        assert_eq!(
            get_exit_code(&err),
            EXIT_API_ERROR,
            "String containing 'network' should fallback to exit code 4"
        );
    }

    #[test]
    fn test_exit_code_string_fallback_safety() {
        let err = anyhow::anyhow!("safety violation detected");
        assert_eq!(
            get_exit_code(&err),
            EXIT_SAFETY_ERROR,
            "String containing 'safety' should fallback to exit code 5"
        );
    }

    #[test]
    fn test_exit_code_string_fallback_blocked() {
        let err = anyhow::anyhow!("operation blocked by policy");
        assert_eq!(
            get_exit_code(&err),
            EXIT_SAFETY_ERROR,
            "String containing 'blocked' should fallback to exit code 5"
        );
    }

    #[test]
    fn test_exit_code_constants() {
        assert_eq!(EXIT_SUCCESS, 0);
        assert_eq!(EXIT_ERROR, 1);
        assert_eq!(EXIT_CONFIG_ERROR, 2);
        assert_eq!(EXIT_API_ERROR, 4);
        assert_eq!(EXIT_SAFETY_ERROR, 5);
        assert_eq!(EXIT_CONFIRMATION_REQUIRED, 6);
    }
}