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
use anyhow::{anyhow, Result};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

pub mod builder;
pub mod command;
pub mod command_discovery;
pub mod command_parser;
pub mod command_validator;
pub mod diagnostics;
pub mod dynamic_registry;
pub mod loader;
pub mod mapreduce;
pub mod metadata_parser;
pub mod prodigy_config;
pub mod tracing;
pub mod workflow;

pub use builder::{
    load_prodigy_config, load_prodigy_config_traced, load_prodigy_config_traced_with,
    load_prodigy_config_with, load_prodigy_config_with_options,
    load_prodigy_config_with_options_and_env, LoadOptions,
};
pub use command::{
    Command, CommandArg, CommandMetadata, OutputDeclaration, SimpleCommand, WorkflowCommand,
};
pub use command_parser::{expand_variables, parse_command_string};
pub use command_validator::{apply_command_defaults, validate_command, CommandRegistry};
pub use dynamic_registry::DynamicCommandRegistry;
pub use loader::ConfigLoader;
pub use mapreduce::{parse_mapreduce_workflow, MapReduceWorkflowConfig};
pub use prodigy_config::{
    global_config_path, project_config_path, BackendType, PluginConfig, ProdigyConfig,
    ProjectSettings, StorageSettings, VALID_LOG_LEVELS,
};
pub use workflow::WorkflowConfig;

/// Get the global Prodigy directory for storing configuration and data
pub fn get_global_prodigy_dir() -> Result<PathBuf> {
    ProjectDirs::from("com", "prodigy", "prodigy")
        .map(|dirs| dirs.data_dir().to_path_buf())
        .ok_or_else(|| anyhow!("Could not determine home directory"))
}

/// Root configuration structure for Prodigy
///
/// Contains global settings, project-specific configuration,
/// and workflow definitions. Supports hierarchical configuration
/// with project settings overriding global defaults.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Config {
    pub global: GlobalConfig,
    pub project: Option<ProjectConfig>,
    pub workflow: Option<WorkflowConfig>,
}

/// Legacy global configuration settings.
///
/// Use [`ProdigyConfig`] with [`load_prodigy_config`] instead:
///
/// ```no_run
/// use prodigy::config::load_prodigy_config;
///
/// let config = load_prodigy_config().expect("load failed");
/// let api_key = config.effective_api_key();
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlobalConfig {
    pub prodigy_home: PathBuf,
    pub default_editor: Option<String>,
    pub log_level: Option<String>,
    pub claude_api_key: Option<String>,
    pub max_concurrent_specs: Option<u32>,
    pub auto_commit: Option<bool>,
    pub plugins: Option<OldPluginConfig>,
}

/// Project-specific configuration settings
///
/// These settings override global configuration for a specific
/// project. Stored in the project's .prodigy/config.toml file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectConfig {
    pub name: String,
    pub description: Option<String>,
    pub version: Option<String>,
    pub spec_dir: Option<PathBuf>,
    pub claude_api_key: Option<String>,
    pub auto_commit: Option<bool>,
    pub variables: Option<toml::Table>,
}

/// Legacy plugin system configuration.
///
/// **Deprecated**: Use [`PluginConfig`] from [`prodigy_config`] module instead.
///
/// Controls plugin discovery, loading, and execution.
/// Plugins extend Prodigy's functionality with custom commands
/// and workflows.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OldPluginConfig {
    pub enabled: bool,
    pub directory: PathBuf,
    pub auto_load: Vec<String>,
}

impl Default for GlobalConfig {
    fn default() -> Self {
        Self {
            prodigy_home: get_global_prodigy_dir().unwrap_or_else(|_| PathBuf::from("~/.prodigy")),
            default_editor: None,
            log_level: Some("info".to_string()),
            claude_api_key: None,
            max_concurrent_specs: Some(1),
            auto_commit: Some(true),
            plugins: None,
        }
    }
}

impl GlobalConfig {
    /// Convert from the new ProdigyConfig type to the legacy GlobalConfig.
    pub fn from_prodigy_config(config: &ProdigyConfig) -> Self {
        GlobalConfig {
            prodigy_home: config.get_prodigy_home(),
            default_editor: config.default_editor.clone(),
            log_level: Some(config.log_level.clone()),
            claude_api_key: config.claude_api_key.clone(),
            max_concurrent_specs: Some(config.max_concurrent_specs as u32),
            auto_commit: Some(config.auto_commit),
            plugins: if config.plugins.enabled {
                Some(OldPluginConfig {
                    enabled: config.plugins.enabled,
                    directory: config
                        .plugins
                        .directory
                        .clone()
                        .unwrap_or_else(|| PathBuf::from("plugins")),
                    auto_load: config.plugins.auto_load.clone(),
                })
            } else {
                None
            },
        }
    }
}

impl ProjectConfig {
    /// Convert from the new ProjectSettings type to the legacy ProjectConfig.
    pub fn from_project_settings(settings: &ProjectSettings) -> Self {
        ProjectConfig {
            name: settings.name.clone().unwrap_or_default(),
            description: settings.description.clone(),
            version: settings.version.clone(),
            spec_dir: settings.spec_dir.clone(),
            claude_api_key: settings.claude_api_key.clone(),
            auto_commit: settings.auto_commit,
            variables: settings
                .variables
                .iter()
                .fold(toml::Table::new(), |mut acc, (k, v)| {
                    // Convert serde_json::Value to toml::Value
                    if let Ok(toml_val) = serde_json::from_value::<toml::Value>(v.clone()) {
                        acc.insert(k.clone(), toml_val);
                    }
                    acc
                })
                .into(),
        }
    }
}

impl Config {
    pub fn new() -> Self {
        Self {
            global: GlobalConfig::default(),
            project: None,
            workflow: None,
        }
    }

    pub fn merge_env_vars(&mut self) {
        if let Ok(api_key) = std::env::var("PRODIGY_CLAUDE_API_KEY") {
            self.global.claude_api_key = Some(api_key);
        }

        if let Ok(log_level) = std::env::var("PRODIGY_LOG_LEVEL") {
            self.global.log_level = Some(log_level);
        }

        if let Ok(editor) = std::env::var("PRODIGY_EDITOR") {
            self.global.default_editor = Some(editor);
        } else if let Ok(editor) = std::env::var("EDITOR") {
            self.global.default_editor = Some(editor);
        }

        if let Ok(auto_commit) = std::env::var("PRODIGY_AUTO_COMMIT") {
            if let Ok(value) = auto_commit.parse::<bool>() {
                self.global.auto_commit = Some(value);
            }
        }
    }

    pub fn get_claude_api_key(&self) -> Option<&str> {
        self.project
            .as_ref()
            .and_then(|p| p.claude_api_key.as_deref())
            .or(self.global.claude_api_key.as_deref())
    }

    pub fn get_auto_commit(&self) -> bool {
        self.project
            .as_ref()
            .and_then(|p| p.auto_commit)
            .or(self.global.auto_commit)
            .unwrap_or(true)
    }

    pub fn get_spec_dir(&self) -> PathBuf {
        self.project
            .as_ref()
            .and_then(|p| p.spec_dir.clone())
            .unwrap_or_else(|| PathBuf::from("specs"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::command::{Command, WorkflowCommand};
    use crate::config::command_parser::parse_command_string;

    #[test]
    fn test_simple_workflow_config_parsing() {
        // Test simple string format
        let yaml_str = r#"
commands:
  - prodigy-code-review
  - prodigy-implement-spec
  - prodigy-lint
"#;

        let config: WorkflowConfig = serde_yaml::from_str(yaml_str).unwrap();
        assert_eq!(config.commands.len(), 3);

        // Verify commands are parsed as Simple variants
        match &config.commands[0] {
            WorkflowCommand::Simple(s) => assert_eq!(s, "prodigy-code-review"),
            _ => unreachable!("Expected Simple command"),
        }
    }

    #[test]
    fn test_structured_workflow_config_parsing() {
        // Test structured format with focus
        let yaml_str = r#"
commands:
  - name: prodigy-code-review
    options:
      focus: security
  - name: prodigy-implement-spec
    args: ["${SPEC_ID}"]
  - prodigy-lint
"#;

        let config: WorkflowConfig = serde_yaml::from_str(yaml_str).unwrap();
        assert_eq!(config.commands.len(), 3);

        // Verify first command (Structured with focus in options)
        let cmd = config.commands[0].to_command();
        assert_eq!(cmd.name, "prodigy-code-review");
        assert_eq!(
            cmd.options.get("focus"),
            Some(&serde_json::json!("security"))
        );

        // Verify second command (Structured with args)
        let cmd = config.commands[1].to_command();
        assert_eq!(cmd.name, "prodigy-implement-spec");
        assert_eq!(cmd.args, vec![CommandArg::parse("${SPEC_ID}")]);
    }

    #[test]
    fn test_mixed_workflow_config() {
        // Test mixed format (legacy and structured)
        let yaml_str = r#"
max_iterations: 5
commands:
  - "prodigy-code-review"
  - name: "prodigy-implement-spec"
    args: ["iteration-123"]
  - "prodigy-lint"
"#;

        let config: WorkflowConfig = serde_yaml::from_str(yaml_str).unwrap();
        assert_eq!(config.commands.len(), 3);

        // First command should be Simple
        assert!(matches!(&config.commands[0], WorkflowCommand::Simple(_)));

        // Second command should be Structured
        let cmd = config.commands[1].to_command();
        assert_eq!(cmd.name, "prodigy-implement-spec");
        assert_eq!(cmd.args, vec![CommandArg::parse("iteration-123")]);

        // Third command should be Simple
        assert!(matches!(&config.commands[2], WorkflowCommand::Simple(_)));
    }

    #[test]
    fn test_command_string_parsing() {
        // Test various command string formats
        let test_cases = vec![
            ("prodigy-code-review", "prodigy-code-review", vec![], vec![]),
            ("/prodigy-lint", "prodigy-lint", vec![], vec![]),
            (
                "prodigy-implement-spec iteration-123",
                "prodigy-implement-spec",
                vec!["iteration-123"],
                vec![],
            ),
            (
                "prodigy-code-review --focus security",
                "prodigy-code-review",
                vec![],
                vec![("focus", "security")],
            ),
            (
                "prodigy-test arg1 arg2 --flag",
                "prodigy-test",
                vec!["arg1", "arg2"],
                vec![("flag", "true")],
            ),
        ];

        for (input, expected_name, expected_args, expected_options) in test_cases {
            let cmd = parse_command_string(input).unwrap();
            assert_eq!(cmd.name, expected_name);
            let expected_args_cmd: Vec<CommandArg> =
                expected_args.into_iter().map(CommandArg::parse).collect();
            assert_eq!(cmd.args, expected_args_cmd);

            for (key, value) in expected_options {
                let expected_value = if value == "true" {
                    serde_json::json!(true)
                } else {
                    serde_json::json!(value)
                };
                assert_eq!(
                    cmd.options.get(key),
                    Some(&expected_value),
                    "Failed for input: {input}"
                );
            }
        }
    }

    #[test]
    fn test_command_validation() {
        use crate::config::command_validator::CommandRegistry;

        let registry = CommandRegistry::new();

        // Valid commands
        let valid_commands = vec![
            Command::new("prodigy-code-review"),
            Command::new("prodigy-implement-spec").with_arg("spec-123"),
            Command::new("prodigy-lint"),
        ];

        for cmd in valid_commands {
            assert!(registry.validate_command(&cmd).is_ok());
        }

        // Invalid commands
        let invalid_commands = vec![
            Command::new("unknown-command"),
            Command::new("prodigy-implement-spec"), // Missing required arg
        ];

        for cmd in invalid_commands {
            assert!(registry.validate_command(&cmd).is_err());
        }
    }

    #[test]
    fn test_variable_expansion() {
        use crate::config::command_parser::expand_variables;
        use std::collections::HashMap;

        let mut cmd = Command::new("prodigy-implement-spec")
            .with_arg("${SPEC_ID}")
            .with_option("path", serde_json::json!("${PROJECT_ROOT}/src"))
            .with_env("CUSTOM_VAR", "${USER_NAME}");

        let mut vars = HashMap::new();
        vars.insert("SPEC_ID".to_string(), "iteration-123".to_string());
        vars.insert("PROJECT_ROOT".to_string(), "/home/user/project".to_string());
        vars.insert("USER_NAME".to_string(), "test-user".to_string());

        expand_variables(&mut cmd, &vars);

        // expand_variables doesn't change CommandArg anymore, so this test doesn't apply the same way
        // The variable would be resolved at execution time
        assert!(matches!(&cmd.args[0], CommandArg::Variable(var) if var == "SPEC_ID"));
        assert_eq!(
            cmd.options.get("path"),
            Some(&serde_json::json!("/home/user/project/src"))
        );
        assert_eq!(
            cmd.metadata.env.get("CUSTOM_VAR"),
            Some(&"test-user".to_string())
        );
    }

    #[test]
    fn test_command_metadata_defaults() {
        use crate::config::command_validator::apply_command_defaults;

        let mut cmd = Command::new("prodigy-code-review");

        // Before applying defaults
        assert!(cmd.metadata.retries.is_none());
        assert!(cmd.metadata.timeout.is_none());

        // Apply defaults
        apply_command_defaults(&mut cmd);

        // After applying defaults
        assert_eq!(cmd.metadata.retries, Some(2));
        assert_eq!(cmd.metadata.timeout, Some(300));
        assert_eq!(cmd.metadata.continue_on_error, Some(false));
    }

    #[test]
    fn test_command_serialization_roundtrip() {
        let original = Command::new("prodigy-code-review")
            .with_arg("file.rs")
            .with_option("focus", serde_json::json!("performance"))
            .with_retries(3)
            .with_timeout(600)
            .with_continue_on_error(true)
            .with_env("DEBUG", "true");

        // Serialize to JSON
        let json = serde_json::to_string(&original).unwrap();

        // Deserialize back
        let deserialized: Command = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.name, original.name);
        assert_eq!(deserialized.args, original.args);
        assert_eq!(deserialized.options, original.options);
        assert_eq!(deserialized.metadata.retries, original.metadata.retries);
        assert_eq!(deserialized.metadata.timeout, original.metadata.timeout);
        assert_eq!(
            deserialized.metadata.continue_on_error,
            original.metadata.continue_on_error
        );
        assert_eq!(deserialized.metadata.env, original.metadata.env);
    }

    #[test]
    fn test_config_new_creates_defaults() {
        let config = Config::new();

        assert!(config.project.is_none());
        assert!(config.workflow.is_none());
        assert_eq!(config.global.log_level, Some("info".to_string()));
        assert_eq!(config.global.max_concurrent_specs, Some(1));
        assert_eq!(config.global.auto_commit, Some(true));
    }

    #[test]
    fn test_get_claude_api_key_precedence() {
        let mut config = Config::new();

        // No API key set
        assert!(config.get_claude_api_key().is_none());

        // Global API key only
        config.global.claude_api_key = Some("global-key".to_string());
        assert_eq!(config.get_claude_api_key(), Some("global-key"));

        // Project API key takes precedence
        config.project = Some(ProjectConfig {
            name: "test".to_string(),
            description: None,
            version: None,
            spec_dir: None,
            claude_api_key: Some("project-key".to_string()),
            auto_commit: None,
            variables: None,
        });
        assert_eq!(config.get_claude_api_key(), Some("project-key"));
    }

    #[test]
    fn test_get_claude_api_key_from_config() {
        let mut config = Config::default();
        config.global.claude_api_key = Some("test-key-123".to_string());

        let result = config.get_claude_api_key();
        assert_eq!(result, Some("test-key-123"));
    }

    // Note: Legacy tests for merge_env_vars have been removed.
    // Environment variable handling is now tested through the new ProdigyConfig
    // system in src/config/builder.rs using MockEnv for proper test isolation.
    // See: test_legacy_env_vars_*, test_load_with_env_override, etc.

    #[test]
    fn test_get_auto_commit_precedence() {
        let mut config = Config::new();

        // Default value
        assert!(config.get_auto_commit());

        // Global setting
        config.global.auto_commit = Some(false);
        assert!(!config.get_auto_commit());

        // Project setting takes precedence
        config.project = Some(ProjectConfig {
            name: "test".to_string(),
            description: None,
            version: None,
            spec_dir: None,
            claude_api_key: None,
            auto_commit: Some(true),
            variables: None,
        });
        assert!(config.get_auto_commit());
    }

    #[test]
    fn test_get_spec_dir() {
        let mut config = Config::new();

        // Default value
        assert_eq!(config.get_spec_dir(), PathBuf::from("specs"));

        // Project setting
        config.project = Some(ProjectConfig {
            name: "test".to_string(),
            description: None,
            version: None,
            spec_dir: Some(PathBuf::from("custom/specs")),
            claude_api_key: None,
            auto_commit: None,
            variables: None,
        });
        assert_eq!(config.get_spec_dir(), PathBuf::from("custom/specs"));
    }

    #[test]
    fn test_global_config_default() {
        let global = GlobalConfig::default();

        // The home directory should be set to something
        assert!(!global.prodigy_home.as_os_str().is_empty());
        assert_eq!(global.log_level, Some("info".to_string()));
        assert_eq!(global.max_concurrent_specs, Some(1));
        assert_eq!(global.auto_commit, Some(true));
        assert!(global.default_editor.is_none());
        assert!(global.claude_api_key.is_none());
        assert!(global.plugins.is_none());
    }

    #[test]
    fn test_get_global_prodigy_dir_success() {
        // Test normal operation
        let result = get_global_prodigy_dir();
        assert!(result.is_ok());

        let path = result.unwrap();
        assert!(path.is_absolute());
        assert!(path.to_string_lossy().contains("prodigy"));
    }

    #[test]
    fn test_get_global_prodigy_dir_path_structure() {
        // Test path structure is correct
        let path = get_global_prodigy_dir().unwrap();

        // The path ends with the full app identifier "com.prodigy.prodigy" on most platforms
        let file_name = path.file_name().unwrap().to_string_lossy();
        assert!(
            file_name == "com.prodigy.prodigy" || file_name == "prodigy",
            "Expected directory name to be 'com.prodigy.prodigy' or 'prodigy', got '{file_name}'"
        );

        // Should be an absolute path
        assert!(path.is_absolute());
    }
}