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
//! Storage configuration types and utilities

use premortem::{ConfigEnv, RealEnv};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::Duration;

/// Storage backend type
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BackendType {
    /// File-based storage (default)
    File,
    /// Memory storage (for testing)
    Memory,
}

impl Default for BackendType {
    fn default() -> Self {
        Self::File
    }
}

/// Main storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    /// Storage backend type
    pub backend: BackendType,

    /// Connection pool size for database backends
    #[serde(default = "default_pool_size")]
    pub connection_pool_size: usize,

    /// Retry policy for failed operations
    #[serde(default)]
    pub retry_policy: RetryPolicy,

    /// Default timeout for operations
    #[serde(with = "humantime_serde", default = "default_timeout")]
    pub timeout: Duration,

    /// Backend-specific configuration
    pub backend_config: BackendConfig,

    /// Enable distributed locking
    #[serde(default = "default_true")]
    pub enable_locking: bool,

    /// Enable caching layer
    #[serde(default)]
    pub enable_cache: bool,

    /// Cache configuration
    #[serde(default)]
    pub cache_config: CacheConfig,
}

/// Backend-specific configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum BackendConfig {
    File(FileConfig),
    Memory(MemoryConfig),
}

/// File storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileConfig {
    /// Base directory for storage
    pub base_dir: PathBuf,

    /// Use global storage (~/.prodigy) - local storage is deprecated
    #[serde(default = "default_true")]
    pub use_global: bool,

    /// Enable file-based locking
    #[serde(default = "default_true")]
    pub enable_file_locks: bool,

    /// Maximum file size before rotation (bytes)
    #[serde(default = "default_max_file_size")]
    pub max_file_size: u64,

    /// Compression for archived files
    #[serde(default)]
    pub enable_compression: bool,
}

/// Memory storage configuration (for testing)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryConfig {
    /// Maximum memory usage (bytes)
    #[serde(default = "default_memory_limit")]
    pub max_memory: u64,

    /// Enable persistence to disk
    #[serde(default)]
    pub persist_to_disk: bool,

    /// Persistence file path
    pub persistence_path: Option<PathBuf>,
}

impl Default for MemoryConfig {
    fn default() -> Self {
        Self {
            max_memory: 100 * 1024 * 1024, // 100 MB
            persist_to_disk: false,
            persistence_path: None,
        }
    }
}

/// Retry policy configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetryPolicy {
    /// Maximum retry attempts
    #[serde(default = "default_max_retries")]
    pub max_retries: u32,

    /// Initial retry delay
    #[serde(with = "humantime_serde", default = "default_retry_delay")]
    pub initial_delay: Duration,

    /// Maximum retry delay
    #[serde(with = "humantime_serde", default = "default_max_retry_delay")]
    pub max_delay: Duration,

    /// Exponential backoff multiplier
    #[serde(default = "default_backoff_multiplier")]
    pub backoff_multiplier: f64,

    /// Enable jitter
    #[serde(default = "default_true")]
    pub jitter: bool,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            max_retries: default_max_retries(),
            initial_delay: default_retry_delay(),
            max_delay: default_max_retry_delay(),
            backoff_multiplier: default_backoff_multiplier(),
            jitter: true,
        }
    }
}

/// Cache configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    /// Cache size limit (entries)
    #[serde(default = "default_cache_size")]
    pub max_entries: usize,

    /// Cache TTL
    #[serde(with = "humantime_serde", default = "default_cache_ttl")]
    pub ttl: Duration,

    /// Cache implementation
    #[serde(default)]
    pub cache_type: CacheType,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_entries: default_cache_size(),
            ttl: default_cache_ttl(),
            cache_type: CacheType::default(),
        }
    }
}

/// Cache implementation type
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CacheType {
    #[default]
    Memory,
}

// Default value functions for serde
fn default_pool_size() -> usize {
    10
}

fn default_timeout() -> Duration {
    Duration::from_secs(30)
}

fn default_true() -> bool {
    true
}

fn default_max_file_size() -> u64 {
    100 * 1024 * 1024 // 100MB
}

fn default_memory_limit() -> u64 {
    1024 * 1024 * 1024 // 1GB
}

fn default_max_retries() -> u32 {
    3
}

fn default_retry_delay() -> Duration {
    Duration::from_secs(1)
}

fn default_max_retry_delay() -> Duration {
    Duration::from_secs(30)
}

fn default_backoff_multiplier() -> f64 {
    2.0
}

fn default_cache_size() -> usize {
    1000
}

fn default_cache_ttl() -> Duration {
    Duration::from_secs(3600) // 1 hour
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            backend: BackendType::default(),
            connection_pool_size: default_pool_size(),
            retry_policy: RetryPolicy::default(),
            timeout: default_timeout(),
            backend_config: BackendConfig::Memory(MemoryConfig::default()),
            enable_locking: true,
            enable_cache: false,
            cache_config: CacheConfig::default(),
        }
    }
}

impl StorageConfig {
    /// Create configuration from environment variables (production).
    ///
    /// This uses the real system environment. For testing, use
    /// [`from_env_with`](Self::from_env_with) with a `MockEnv`.
    pub fn from_env() -> crate::LibResult<Self> {
        Self::from_env_with(&RealEnv)
    }

    /// Create configuration from environment variables (testable).
    ///
    /// Accepts any `ConfigEnv` implementation, allowing tests to use
    /// `MockEnv` instead of manipulating global environment variables.
    ///
    /// # Example
    ///
    /// ```
    /// use premortem::MockEnv;
    /// use prodigy::storage::{StorageConfig, BackendType};
    ///
    /// let env = MockEnv::new()
    ///     .with_env("PRODIGY_STORAGE_TYPE", "memory");
    ///
    /// let config = StorageConfig::from_env_with(&env).unwrap();
    /// assert_eq!(config.backend, BackendType::Memory);
    /// ```
    pub fn from_env_with<E: ConfigEnv>(env: &E) -> crate::LibResult<Self> {
        // Check for backend type - now only File or Memory supported
        let backend = env
            .get_env("PRODIGY_STORAGE_TYPE")
            .and_then(|s| match s.to_lowercase().as_str() {
                "file" => Some(BackendType::File),
                "memory" => Some(BackendType::Memory),
                _ => None,
            })
            .unwrap_or_default();

        let backend_config = match backend {
            BackendType::File => BackendConfig::File(FileConfig {
                base_dir: env
                    .get_env("PRODIGY_STORAGE_BASE_PATH")
                    .or_else(|| env.get_env("PRODIGY_STORAGE_DIR"))
                    .or_else(|| env.get_env("PRODIGY_STORAGE_PATH"))
                    .map(PathBuf::from)
                    .unwrap_or_else(|| {
                        directories::BaseDirs::new()
                            .map(|dirs| dirs.home_dir().join(".prodigy"))
                            .unwrap_or_else(|| PathBuf::from("/tmp").join(".prodigy"))
                    }),
                use_global: true, // Always use global storage
                enable_file_locks: true,
                max_file_size: default_max_file_size(),
                enable_compression: false,
            }),
            BackendType::Memory => BackendConfig::Memory(Default::default()),
        };

        Ok(Self {
            backend,
            connection_pool_size: default_pool_size(),
            retry_policy: Default::default(),
            timeout: default_timeout(),
            backend_config,
            enable_locking: true,
            enable_cache: false,
            cache_config: Default::default(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use premortem::MockEnv;
    use std::time::Duration;

    #[test]
    fn test_backend_type_default() {
        assert_eq!(BackendType::default(), BackendType::File);
    }

    #[test]
    fn test_backend_type_serialization() {
        let backend = BackendType::File;
        let json = serde_json::to_string(&backend).unwrap();
        assert_eq!(json, r#""file""#);

        let backend = BackendType::Memory;
        let json = serde_json::to_string(&backend).unwrap();
        assert_eq!(json, r#""memory""#);
    }

    #[test]
    fn test_backend_type_deserialization() {
        let backend: BackendType = serde_json::from_str(r#""file""#).unwrap();
        assert_eq!(backend, BackendType::File);

        let backend: BackendType = serde_json::from_str(r#""memory""#).unwrap();
        assert_eq!(backend, BackendType::Memory);
    }

    #[test]
    fn test_storage_config_default() {
        let config = StorageConfig::default();

        assert_eq!(config.backend, BackendType::File);
        assert_eq!(config.connection_pool_size, 10);
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert!(config.enable_locking);
        assert!(!config.enable_cache);
    }

    #[test]
    fn test_file_config_defaults() {
        let config = FileConfig {
            base_dir: PathBuf::from("/test"),
            use_global: default_true(),
            enable_file_locks: default_true(),
            max_file_size: default_max_file_size(),
            enable_compression: false,
        };

        assert_eq!(config.base_dir, PathBuf::from("/test"));
        assert!(config.use_global);
        assert!(config.enable_file_locks);
        assert_eq!(config.max_file_size, 100 * 1024 * 1024); // 100 MB
    }

    #[test]
    fn test_memory_config_defaults() {
        let config = MemoryConfig::default();

        assert_eq!(config.max_memory, 100 * 1024 * 1024); // 100 MB
    }

    #[test]
    fn test_retry_policy_default() {
        let policy = RetryPolicy::default();

        assert!(policy.max_retries > 0);
        assert!(policy.initial_delay > Duration::from_secs(0));
        assert!(policy.max_delay > Duration::from_secs(0));
        assert!(policy.backoff_multiplier > 1.0);
    }

    #[test]
    fn test_cache_config_default() {
        let config = CacheConfig::default();

        assert!(config.max_entries > 0);
        assert!(config.ttl > Duration::from_secs(0));
    }

    #[test]
    fn test_storage_config_from_env_defaults() {
        // Empty MockEnv simulates no env vars being set
        let env = MockEnv::new();

        let config = StorageConfig::from_env_with(&env).unwrap();

        assert_eq!(config.backend, BackendType::File);
        assert!(config.enable_locking);
        assert!(!config.enable_cache);

        if let BackendConfig::File(file_config) = config.backend_config {
            // Should use home directory
            assert!(file_config.base_dir.to_string_lossy().contains(".prodigy"));
            assert!(file_config.use_global);
        } else {
            panic!("Expected FileConfig");
        }
    }

    #[test]
    fn test_storage_config_from_env_file_type() {
        let env = MockEnv::new()
            .with_env("PRODIGY_STORAGE_TYPE", "file")
            .with_env("PRODIGY_STORAGE_BASE_PATH", "/custom/path");

        let config = StorageConfig::from_env_with(&env).unwrap();

        assert_eq!(config.backend, BackendType::File);

        if let BackendConfig::File(file_config) = config.backend_config {
            assert_eq!(file_config.base_dir, PathBuf::from("/custom/path"));
        } else {
            panic!("Expected FileConfig");
        }
        // No cleanup needed - MockEnv is dropped automatically
    }

    #[test]
    fn test_storage_config_from_env_memory_type() {
        let env = MockEnv::new().with_env("PRODIGY_STORAGE_TYPE", "memory");

        let config = StorageConfig::from_env_with(&env).unwrap();

        assert_eq!(config.backend, BackendType::Memory);

        if let BackendConfig::Memory(memory_config) = config.backend_config {
            assert_eq!(memory_config.max_memory, 100 * 1024 * 1024);
        } else {
            panic!("Expected MemoryConfig");
        }
        // No cleanup needed - MockEnv is dropped automatically
    }

    #[test]
    fn test_storage_config_from_env_invalid_type() {
        let env = MockEnv::new().with_env("PRODIGY_STORAGE_TYPE", "invalid");

        let result = StorageConfig::from_env_with(&env);
        // Invalid types should default to File backend
        assert!(result.is_ok());
        let config = result.unwrap();
        assert_eq!(config.backend, BackendType::File);
        // No cleanup needed - MockEnv is dropped automatically
    }

    #[test]
    fn test_storage_config_serialization() {
        let config = StorageConfig::default();
        let json = serde_json::to_string(&config).unwrap();
        let deserialized: StorageConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(config.backend, deserialized.backend);
        assert_eq!(
            config.connection_pool_size,
            deserialized.connection_pool_size
        );
        assert_eq!(config.enable_locking, deserialized.enable_locking);
    }

    #[test]
    fn test_file_config_serialization() {
        let config = FileConfig {
            base_dir: PathBuf::from("/test/path"),
            use_global: true,
            enable_file_locks: false,
            max_file_size: 1024,
            enable_compression: true,
        };

        let json = serde_json::to_string(&config).unwrap();
        let deserialized: FileConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(config.base_dir, deserialized.base_dir);
        assert_eq!(config.use_global, deserialized.use_global);
        assert_eq!(config.enable_file_locks, deserialized.enable_file_locks);
        assert_eq!(config.max_file_size, deserialized.max_file_size);
    }

    #[test]
    fn test_default_helper_functions() {
        assert!(default_true());
        // default_false doesn't exist, just test default_true
        assert_eq!(default_pool_size(), 10);
        assert_eq!(default_timeout(), Duration::from_secs(30));
        assert_eq!(default_max_file_size(), 100 * 1024 * 1024);
    }

    #[test]
    fn test_backend_config_untagged_enum() {
        // Test that BackendConfig can be deserialized from JSON without type tags
        let file_json = r#"{
            "base_dir": "/test",
            "use_global": true,
            "enable_file_locks": true,
            "max_file_size": 1000000,
            "enable_compression": false
        }"#;

        let backend_config: BackendConfig = serde_json::from_str(file_json).unwrap();

        if let BackendConfig::File(config) = backend_config {
            assert_eq!(config.base_dir, PathBuf::from("/test"));
            assert!(config.use_global);
        } else {
            panic!("Expected FileConfig");
        }
    }

    #[test]
    fn test_retry_policy_validation() {
        let policy = RetryPolicy {
            max_retries: 5,
            initial_delay: Duration::from_millis(50),
            max_delay: Duration::from_secs(60),
            backoff_multiplier: 2.0,
            jitter: true,
        };

        assert_eq!(policy.max_retries, 5);
        assert_eq!(policy.initial_delay, Duration::from_millis(50));
        assert_eq!(policy.max_delay, Duration::from_secs(60));
        assert_eq!(policy.backoff_multiplier, 2.0);
        assert!(policy.jitter);
    }

    #[test]
    fn test_cache_config_with_custom_values() {
        let config = CacheConfig {
            max_entries: 5000,
            ttl: Duration::from_secs(600),
            cache_type: Default::default(),
        };

        assert_eq!(config.max_entries, 5000);
        assert_eq!(config.ttl, Duration::from_secs(600));
    }
}