prodigy 0.4.4

Turn ad-hoc Claude sessions into reproducible development pipelines with parallel AI agents
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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
//! # Prodigy Error System
//!
//! This module provides a comprehensive error handling system for Prodigy with support for
//! error context chaining, structured error codes, and user-friendly error messages.
//!
//! ## Overview
//!
//! The error system is built around [`ProdigyError`], a unified error type that supports:
//! - **Context Chaining**: Build rich error context through `.context()` calls
//! - **Error Codes**: Structured error codes for categorization (E1001, E2001, etc.)
//! - **User Messages**: End-user friendly error descriptions
//! - **Developer Messages**: Detailed diagnostic information with full context chain
//! - **Serialization**: Convert errors to JSON for API responses and logging
//!
//! ## Context Chaining Pattern
//!
//! The core pattern is to add context at **Effect boundaries** - points where your code
//! transitions between different layers of abstraction or performs I/O operations.
//!
//! ### Basic Usage
//!
//! The following examples are illustrative patterns showing how to structure error handling.
//! They reference hypothetical types (`Config`, `read_file`) to demonstrate the pattern.
//!
//! ```rust,ignore
//! use prodigy::error::{ProdigyError, ErrorExt};
//!
//! fn read_config(path: &str) -> Result<Config, ProdigyError> {
//!     // Effect boundary: file I/O
//!     let content = std::fs::read_to_string(path)
//!         .map_err(ProdigyError::from)
//!         .context("Failed to read configuration file")?;
//!
//!     // Effect boundary: parsing
//!     let config: Config = serde_json::from_str(&content)
//!         .map_err(ProdigyError::from)
//!         .context("Failed to parse configuration JSON")?;
//!
//!     Ok(config)
//! }
//!
//! fn load_application_config() -> Result<Config, ProdigyError> {
//!     // Effect boundary: calling lower-level function
//!     read_config("config.json")
//!         .context("Failed to load application configuration")?
//! }
//! ```
//!
//! This creates a context chain like:
//! ```text
//! Failed to load application configuration
//!   └─ Failed to read configuration file
//!      └─ No such file or directory (os error 2)
//! ```
//!
//! ### Effect Boundaries
//!
//! Add `.context()` calls at these boundaries:
//!
//! 1. **I/O Operations**
//!    ```rust,ignore
//!    std::fs::write(path, data)
//!        .map_err(ProdigyError::from)
//!        .context(format!("Failed to write to {}", path))?;
//!    ```
//!
//! 2. **External Calls**
//!    ```rust,ignore
//!    subprocess.execute()
//!        .context("Failed to execute git command")?;
//!    ```
//!
//! 3. **Layer Transitions**
//!    ```rust,ignore
//!    storage.save_checkpoint(checkpoint)
//!        .context("Failed to persist workflow checkpoint")?;
//!    ```
//!
//! 4. **Error Propagation**
//!    ```rust,ignore
//!    validate_workflow(&workflow)
//!        .context(format!("Validation failed for workflow '{}'", workflow.name))?;
//!    ```
//!
//! ### Advanced Patterns
//!
//! **Dynamic Context with Closures**:
//! ```rust,ignore
//! work_items.iter()
//!     .map(|item| {
//!         process_item(item)
//!             .with_context(|| format!("Failed to process item {}", item.id))
//!     })
//!     .collect::<Result<Vec<_>, _>>()?;
//! ```
//!
//! **Context with Location Tracking**:
//! ```rust,ignore
//! use prodigy::error::ProdigyError;
//!
//! fn critical_operation() -> Result<(), ProdigyError> {
//!     do_something()
//!         .map_err(ProdigyError::from)
//!         .context_at("In critical_operation")?;
//!     Ok(())
//! }
//! ```
//!
//! ## Error Construction
//!
//! Use the helper functions in [`helpers::common`] for creating errors:
//!
//! ```
//! use prodigy::error::helpers::common;
//! use std::path::PathBuf;
//!
//! // Configuration file not found
//! let err = common::config_not_found("/etc/prodigy/config.yml");
//!
//! // Storage I/O errors
//! let path = Some(PathBuf::from("/var/lib/prodigy/checkpoint.json"));
//! let err = common::storage_io_error(path, "read");
//!
//! // Command not found
//! let err = common::command_not_found("git");
//!
//! // Execution timeout
//! let err = common::execution_timeout("long_running_command", 30);
//!
//! // Session not found
//! let err = common::session_not_found("session-123");
//!
//! // Workflow validation failed
//! let err = common::workflow_validation_failed("deploy", "missing required field");
//! ```
//!
//! ## Displaying Errors
//!
//! Errors support multiple display formats:
//!
//! **User Message** (end-user friendly):
//! ```
//! use prodigy::error::ProdigyError;
//!
//! let error = ProdigyError::config("Invalid configuration file");
//! let msg = error.user_message();
//! assert!(msg.contains("Configuration problem"));
//! ```
//!
//! **Developer Message** (full diagnostic info):
//! ```
//! use prodigy::error::ProdigyError;
//!
//! let error = ProdigyError::storage("File not found")
//!     .context("Loading configuration")
//!     .context("Starting application");
//!
//! let dev_msg = error.developer_message();
//! assert!(dev_msg.contains("File not found"));
//! assert!(dev_msg.contains("Context chain"));
//! ```
//!
//! ## Serialization
//!
//! Convert errors to JSON for APIs and logging:
//!
//! ```
//! use prodigy::error::{ProdigyError, SerializableError};
//!
//! let error = ProdigyError::execution("Command failed")
//!     .context("Running workflow");
//!
//! let serializable = SerializableError::from(&error);
//! assert_eq!(serializable.kind, "Execution");
//!
//! // Or use convenience methods
//! let json_string = error.to_json_string();
//! assert!(json_string.contains("Execution"));
//! ```
//!
//! ## Migration Guide
//!
//! To add context to existing error handling (illustrative pattern):
//!
//! **Before**:
//! ```rust,ignore
//! let data = read_file(path)?;
//! ```
//!
//! **After**:
//! ```rust,ignore
//! let data = read_file(path)
//!     .context(format!("Failed to read file at {}", path))?;
//! ```
//!
//! For a real example, see the working tests above.
//!
//! See the migration guide in `docs/specs/` for comprehensive examples.

use std::fmt::Display;
use std::path::PathBuf;
use std::sync::Arc;
use thiserror::Error;

pub mod codes;
pub mod helpers;
pub mod serialization;

#[cfg(test)]
mod tests;

pub use codes::{describe_error_code, ErrorCode};
pub use helpers::{common, ErrorExt};
pub use serialization::SerializableError;

/// Error context entry
#[derive(Debug, Clone)]
pub struct ErrorContext {
    pub message: String,
    pub location: Option<&'static str>,
}

/// The unified error type for the entire Prodigy application
#[derive(Error, Debug)]
pub enum ProdigyError {
    #[error("[E{code:04}] Configuration error: {message}")]
    Config {
        code: u16,
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
        context: Vec<ErrorContext>,
        error_source: Option<Arc<ProdigyError>>,
    },

    #[error("[E{code:04}] Session error: {message}")]
    Session {
        code: u16,
        message: String,
        session_id: Option<String>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
        context: Vec<ErrorContext>,
        error_source: Option<Arc<ProdigyError>>,
    },

    #[error("[E{code:04}] Storage error: {message}")]
    Storage {
        code: u16,
        message: String,
        path: Option<PathBuf>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
        context: Vec<ErrorContext>,
        error_source: Option<Arc<ProdigyError>>,
    },

    #[error("[E{code:04}] Execution error: {message}")]
    Execution {
        code: u16,
        message: String,
        command: Option<String>,
        exit_code: Option<i32>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
        context: Vec<ErrorContext>,
        error_source: Option<Arc<ProdigyError>>,
    },

    #[error("[E{code:04}] Workflow error: {message}")]
    Workflow {
        code: u16,
        message: String,
        workflow_name: Option<String>,
        step: Option<String>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
        context: Vec<ErrorContext>,
        error_source: Option<Arc<ProdigyError>>,
    },

    #[error("[E{code:04}] Git operation failed: {message}")]
    Git {
        code: u16,
        message: String,
        operation: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
        context: Vec<ErrorContext>,
        error_source: Option<Arc<ProdigyError>>,
    },

    #[error("[E{code:04}] Validation error: {message}")]
    Validation {
        code: u16,
        message: String,
        field: Option<String>,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
        context: Vec<ErrorContext>,
        error_source: Option<Arc<ProdigyError>>,
    },

    #[error("[E{code:04}] {message}")]
    Other {
        code: u16,
        message: String,
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
        context: Vec<ErrorContext>,
        error_source: Option<Arc<ProdigyError>>,
    },
}

impl ProdigyError {
    /// Create a configuration error with default code
    pub fn config(message: impl Into<String>) -> Self {
        Self::Config {
            code: ErrorCode::CONFIG_GENERIC,
            message: message.into(),
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a configuration error with specific code
    pub fn config_with_code(code: u16, message: impl Into<String>) -> Self {
        Self::Config {
            code,
            message: message.into(),
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a session error with default code
    pub fn session(message: impl Into<String>) -> Self {
        Self::Session {
            code: ErrorCode::SESSION_GENERIC,
            message: message.into(),
            session_id: None,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a session error with specific code and session ID
    pub fn session_with_code(
        code: u16,
        message: impl Into<String>,
        session_id: Option<String>,
    ) -> Self {
        Self::Session {
            code,
            message: message.into(),
            session_id,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a storage error with default code
    pub fn storage(message: impl Into<String>) -> Self {
        Self::Storage {
            code: ErrorCode::STORAGE_GENERIC,
            message: message.into(),
            path: None,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a storage error with specific code and path
    pub fn storage_with_code(code: u16, message: impl Into<String>, path: Option<PathBuf>) -> Self {
        Self::Storage {
            code,
            message: message.into(),
            path,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create an execution error with default code
    pub fn execution(message: impl Into<String>) -> Self {
        Self::Execution {
            code: ErrorCode::EXEC_GENERIC,
            message: message.into(),
            command: None,
            exit_code: None,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create an execution error with specific code
    pub fn execution_with_code(
        code: u16,
        message: impl Into<String>,
        command: Option<String>,
    ) -> Self {
        Self::Execution {
            code,
            message: message.into(),
            command,
            exit_code: None,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a workflow error with default code
    pub fn workflow(message: impl Into<String>) -> Self {
        Self::Workflow {
            code: ErrorCode::WORKFLOW_GENERIC,
            message: message.into(),
            workflow_name: None,
            step: None,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a workflow error with specific code
    pub fn workflow_with_code(
        code: u16,
        message: impl Into<String>,
        workflow_name: Option<String>,
    ) -> Self {
        Self::Workflow {
            code,
            message: message.into(),
            workflow_name,
            step: None,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a git error with specific code and operation
    pub fn git(code: u16, message: impl Into<String>, operation: impl Into<String>) -> Self {
        Self::Git {
            code,
            message: message.into(),
            operation: operation.into(),
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a validation error with default code
    pub fn validation(message: impl Into<String>) -> Self {
        Self::Validation {
            code: ErrorCode::VALIDATION_GENERIC,
            message: message.into(),
            field: None,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a validation error with specific code and field
    pub fn validation_with_code(
        code: u16,
        message: impl Into<String>,
        field: Option<String>,
    ) -> Self {
        Self::Validation {
            code,
            message: message.into(),
            field,
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Create a generic other error
    pub fn other(message: impl Into<String>) -> Self {
        Self::Other {
            code: ErrorCode::OTHER_GENERIC,
            message: message.into(),
            source: None,
            context: Vec::new(),
            error_source: None,
        }
    }

    /// Add a source error to this error
    pub fn with_source(
        mut self,
        source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
    ) -> Self {
        match &mut self {
            Self::Config { source: src, .. }
            | Self::Session { source: src, .. }
            | Self::Storage { source: src, .. }
            | Self::Execution { source: src, .. }
            | Self::Workflow { source: src, .. }
            | Self::Git { source: src, .. }
            | Self::Validation { source: src, .. }
            | Self::Other { source: src, .. } => {
                *src = Some(source.into());
            }
        }
        self
    }

    /// Add context to the error message (legacy method, kept for compatibility)
    pub fn with_context(mut self, context: impl Display) -> Self {
        match &mut self {
            Self::Config { message, .. }
            | Self::Session { message, .. }
            | Self::Storage { message, .. }
            | Self::Execution { message, .. }
            | Self::Workflow { message, .. }
            | Self::Git { message, .. }
            | Self::Validation { message, .. }
            | Self::Other { message, .. } => {
                *message = format!("{}: {}", message, context);
            }
        }
        self
    }

    /// Add context to error (fluent API, preferred for new code)
    pub fn context(mut self, message: impl Into<String>) -> Self {
        let ctx = ErrorContext {
            message: message.into(),
            location: None,
        };
        match &mut self {
            Self::Config { context, .. }
            | Self::Session { context, .. }
            | Self::Storage { context, .. }
            | Self::Execution { context, .. }
            | Self::Workflow { context, .. }
            | Self::Git { context, .. }
            | Self::Validation { context, .. }
            | Self::Other { context, .. } => {
                context.push(ctx);
            }
        }
        self
    }

    /// Add context with source location tracking
    #[track_caller]
    pub fn context_at(mut self, message: impl Into<String>) -> Self {
        let location = std::panic::Location::caller();
        let ctx = ErrorContext {
            message: message.into(),
            location: Some(location.file()),
        };
        match &mut self {
            Self::Config { context, .. }
            | Self::Session { context, .. }
            | Self::Storage { context, .. }
            | Self::Execution { context, .. }
            | Self::Workflow { context, .. }
            | Self::Git { context, .. }
            | Self::Validation { context, .. }
            | Self::Other { context, .. } => {
                context.push(ctx);
            }
        }
        self
    }

    /// Chain with another ProdigyError as source
    pub fn with_error_source(mut self, source: ProdigyError) -> Self {
        match &mut self {
            Self::Config { error_source, .. }
            | Self::Session { error_source, .. }
            | Self::Storage { error_source, .. }
            | Self::Execution { error_source, .. }
            | Self::Workflow { error_source, .. }
            | Self::Git { error_source, .. }
            | Self::Validation { error_source, .. }
            | Self::Other { error_source, .. } => {
                *error_source = Some(Arc::new(source));
            }
        }
        self
    }

    /// Get context chain
    pub fn chain(&self) -> &[ErrorContext] {
        match self {
            Self::Config { context, .. }
            | Self::Session { context, .. }
            | Self::Storage { context, .. }
            | Self::Execution { context, .. }
            | Self::Workflow { context, .. }
            | Self::Git { context, .. }
            | Self::Validation { context, .. }
            | Self::Other { context, .. } => context,
        }
    }

    /// Get root error (follows error_source chain)
    pub fn root_cause(&self) -> &ProdigyError {
        let mut current = self;
        loop {
            match current {
                Self::Config { error_source, .. }
                | Self::Session { error_source, .. }
                | Self::Storage { error_source, .. }
                | Self::Execution { error_source, .. }
                | Self::Workflow { error_source, .. }
                | Self::Git { error_source, .. }
                | Self::Validation { error_source, .. }
                | Self::Other { error_source, .. } => {
                    if let Some(ref src) = error_source {
                        current = src;
                    } else {
                        return current;
                    }
                }
            }
        }
    }

    /// Get a reference to the error_source if present
    pub fn error_source(&self) -> Option<&ProdigyError> {
        match self {
            Self::Config { error_source, .. }
            | Self::Session { error_source, .. }
            | Self::Storage { error_source, .. }
            | Self::Execution { error_source, .. }
            | Self::Workflow { error_source, .. }
            | Self::Git { error_source, .. }
            | Self::Validation { error_source, .. }
            | Self::Other { error_source, .. } => error_source.as_deref(),
        }
    }

    /// Get the exit code for this error
    pub fn exit_code(&self) -> i32 {
        match self {
            Self::Config { .. } => 2,
            Self::Session { .. } => 3,
            Self::Storage { .. } => 4,
            Self::Execution { .. } => 5,
            Self::Workflow { .. } => 6,
            Self::Git { .. } => 7,
            Self::Validation { .. } => 8,
            Self::Other { .. } => 1,
        }
    }

    /// Get the error code
    pub fn code(&self) -> u16 {
        match self {
            Self::Config { code, .. }
            | Self::Session { code, .. }
            | Self::Storage { code, .. }
            | Self::Execution { code, .. }
            | Self::Workflow { code, .. }
            | Self::Git { code, .. }
            | Self::Validation { code, .. }
            | Self::Other { code, .. } => *code,
        }
    }

    /// Get a user-friendly error message
    pub fn user_message(&self) -> String {
        match self {
            Self::Config { message, .. } => format!("Configuration problem: {}", message),
            Self::Session {
                message,
                session_id,
                ..
            } => {
                if let Some(id) = session_id {
                    format!("Session {} error: {}", id, message)
                } else {
                    format!("Session error: {}", message)
                }
            }
            Self::Storage { message, path, .. } => {
                if let Some(p) = path {
                    format!("Storage error at {}: {}", p.display(), message)
                } else {
                    format!("Storage error: {}", message)
                }
            }
            Self::Execution {
                message, command, ..
            } => {
                if let Some(cmd) = command {
                    format!("Command '{}' failed: {}", cmd, message)
                } else {
                    format!("Execution error: {}", message)
                }
            }
            Self::Workflow {
                message,
                workflow_name,
                step,
                ..
            } => {
                let mut msg = String::from("Workflow error");
                if let Some(name) = workflow_name {
                    msg.push_str(&format!(" in '{}'", name));
                }
                if let Some(s) = step {
                    msg.push_str(&format!(" at step '{}'", s));
                }
                format!("{}: {}", msg, message)
            }
            Self::Git {
                message, operation, ..
            } => {
                format!("Git {} failed: {}", operation, message)
            }
            Self::Validation { message, field, .. } => {
                if let Some(f) = field {
                    format!("Validation error for '{}': {}", f, message)
                } else {
                    format!("Validation error: {}", message)
                }
            }
            Self::Other { message, .. } => message.clone(),
        }
    }

    /// Get a developer-friendly error message with full chain
    pub fn developer_message(&self) -> String {
        let mut msg = format!("{:#}", self);

        // Add context chain if present
        let context_chain = self.chain();
        if !context_chain.is_empty() {
            msg.push_str("\n\nContext chain:");
            for (i, ctx) in context_chain.iter().enumerate() {
                msg.push_str(&format!("\n  {}: {}", i, ctx.message));
                if let Some(loc) = ctx.location {
                    msg.push_str(&format!(" (at {})", loc));
                }
            }
        }

        // Add error source chain if present
        if let Some(src) = self.error_source() {
            msg.push_str("\n\nCaused by:");
            msg.push_str(&format!("\n  {}", src.developer_message()));
        }

        msg
    }

    /// Check if this is a recoverable error
    pub fn is_recoverable(&self) -> bool {
        match self {
            Self::Execution {
                exit_code: Some(code),
                ..
            } => {
                // Non-zero but not fatal exit codes
                *code != 0 && *code < 128
            }
            Self::Storage { code, .. } => {
                // Temporary storage issues are recoverable
                *code == ErrorCode::STORAGE_TEMPORARY || *code == ErrorCode::STORAGE_LOCK_BUSY
            }
            _ => false,
        }
    }

    /// Set the exit code for an execution error
    pub fn with_exit_code(mut self, exit_code: i32) -> Self {
        if let Self::Execution {
            exit_code: ref mut ec,
            ..
        } = self
        {
            *ec = Some(exit_code);
        }
        self
    }

    /// Set the workflow step for a workflow error
    pub fn with_step(mut self, step: impl Into<String>) -> Self {
        if let Self::Workflow {
            step: ref mut s, ..
        } = self
        {
            *s = Some(step.into());
        }
        self
    }
}

/// Type alias for Results using ProdigyError
pub type Result<T> = std::result::Result<T, ProdigyError>;

/// Type alias for library Results (same as Result for now)
pub type LibResult<T> = std::result::Result<T, ProdigyError>;

/// Type alias for application Results (using anyhow for flexibility)
pub type AppResult<T> = anyhow::Result<T>;

// Conversion from common error types

impl From<std::io::Error> for ProdigyError {
    fn from(err: std::io::Error) -> Self {
        use std::io::ErrorKind;

        let (code, message) = match err.kind() {
            ErrorKind::NotFound => (ErrorCode::STORAGE_NOT_FOUND, "File or directory not found"),
            ErrorKind::PermissionDenied => {
                (ErrorCode::STORAGE_PERMISSION_DENIED, "Permission denied")
            }
            ErrorKind::AlreadyExists => (ErrorCode::STORAGE_ALREADY_EXISTS, "Already exists"),
            ErrorKind::InvalidInput => (ErrorCode::VALIDATION_INVALID_INPUT, "Invalid input"),
            ErrorKind::InvalidData => (ErrorCode::VALIDATION_INVALID_DATA, "Invalid data"),
            ErrorKind::TimedOut => (ErrorCode::EXEC_TIMEOUT, "Operation timed out"),
            ErrorKind::Interrupted => (ErrorCode::EXEC_INTERRUPTED, "Operation interrupted"),
            ErrorKind::WouldBlock => (
                ErrorCode::STORAGE_LOCK_BUSY,
                "Resource temporarily unavailable",
            ),
            _ => (ErrorCode::STORAGE_IO_ERROR, "IO operation failed"),
        };

        ProdigyError::storage_with_code(code, message, None).with_source(err)
    }
}

impl From<serde_yaml::Error> for ProdigyError {
    fn from(err: serde_yaml::Error) -> Self {
        ProdigyError::config_with_code(ErrorCode::CONFIG_INVALID_YAML, "Invalid YAML syntax")
            .with_source(err)
    }
}

impl From<serde_json::Error> for ProdigyError {
    fn from(err: serde_json::Error) -> Self {
        ProdigyError::config_with_code(ErrorCode::CONFIG_INVALID_JSON, "Invalid JSON syntax")
            .with_source(err)
    }
}

// Note: ProdigyError automatically converts to anyhow::Error because it implements std::error::Error