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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Default function for serde to return true
fn default_true() -> bool {
    true
}

/// Default cache duration in seconds (5 minutes)
fn default_cache_duration() -> u64 {
    300
}

/// Represents a command argument that can be a literal value or a variable
#[derive(Debug, Clone, PartialEq)]
pub enum CommandArg {
    /// A literal string value
    Literal(String),
    /// A variable reference (e.g., "$FILE", "$ARG")
    Variable(String),
}

// Custom serialization for CommandArg
impl Serialize for CommandArg {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            CommandArg::Literal(s) => serializer.serialize_str(s),
            CommandArg::Variable(var) => serializer.serialize_str(&format!("${{{var}}}")),
        }
    }
}

// Custom deserialization for CommandArg
impl<'de> Deserialize<'de> for CommandArg {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(CommandArg::parse(&s))
    }
}

impl CommandArg {
    /// Check if this is a variable reference
    #[must_use]
    pub fn is_variable(&self) -> bool {
        matches!(self, CommandArg::Variable(_))
    }

    /// Resolve the argument value given a context
    #[must_use]
    pub fn resolve(&self, variables: &HashMap<String, String>) -> String {
        match self {
            CommandArg::Literal(s) => s.clone(),
            CommandArg::Variable(var) => variables.get(var).cloned().unwrap_or_else(|| {
                // Return the variable reference if not found
                format!("${var}")
            }),
        }
    }

    /// Parse from a string, detecting variables by $ prefix
    #[must_use]
    pub fn parse(s: &str) -> Self {
        // Handle ${VAR} format
        if s.starts_with("${") && s.ends_with('}') {
            CommandArg::Variable(s[2..s.len() - 1].to_string())
        } else if let Some(var) = s.strip_prefix('$') {
            // Handle $VAR format
            CommandArg::Variable(var.to_string())
        } else {
            CommandArg::Literal(s.to_string())
        }
    }
}

/// Structured command representation for workflow execution
///
/// Represents a fully-specified command with its arguments, options,
/// inputs, outputs, and metadata. This is the primary command format
/// for complex workflows with data flow between commands.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct Command {
    /// The command name (e.g., "prodigy-code-review")
    pub name: String,

    /// Positional arguments for the command
    #[serde(default)]
    pub args: Vec<CommandArg>,

    /// Named options/flags for the command
    #[serde(default)]
    pub options: HashMap<String, serde_json::Value>,

    /// Command-specific metadata
    #[serde(default)]
    pub metadata: CommandMetadata,

    /// Unique identifier for this command in the workflow
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    /// Outputs this command produces
    #[serde(skip_serializing_if = "Option::is_none")]
    pub outputs: Option<HashMap<String, OutputDeclaration>>,

    /// Analysis requirements for this command (convenience field)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub analysis: Option<AnalysisConfig>,
}

/// Configuration for per-step analysis requirements
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnalysisConfig {
    /// Force fresh analysis even if cached
    #[serde(default)]
    pub force_refresh: bool,

    /// Maximum age of cached analysis in seconds
    #[serde(default = "default_cache_duration")]
    pub max_cache_age: u64,
}

/// Metadata for command execution control
///
/// Contains optional parameters that control how a command is executed,
/// including retry behavior, timeouts, and error handling strategies.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct CommandMetadata {
    /// Number of retry attempts (overrides global setting)
    pub retries: Option<u32>,

    /// Timeout in seconds
    pub timeout: Option<u64>,

    /// Continue workflow on command failure
    pub continue_on_error: Option<bool>,

    /// Environment variables to set
    #[serde(default)]
    pub env: HashMap<String, String>,

    /// Whether this command is required to create commits (defaults to false)
    #[serde(default)]
    pub commit_required: bool,

    /// Analysis requirements for this command
    #[serde(skip_serializing_if = "Option::is_none")]
    pub analysis: Option<AnalysisConfig>,
}

/// Declaration of a command output
///
/// Specifies how to extract and name outputs from command execution
/// for use by subsequent commands in the workflow.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OutputDeclaration {
    /// File pattern for git commit extraction (since we only extract from git commits)
    pub file_pattern: String,
}

/// Configuration for test debugging on failure
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TestDebugConfig {
    /// Claude command to run on test failure
    pub claude: String,

    /// Maximum number of retry attempts
    #[serde(default = "default_max_attempts")]
    pub max_attempts: u32,

    /// Whether to fail the workflow if max attempts reached
    #[serde(default)]
    pub fail_workflow: bool,

    /// Whether the debug command should create commits
    #[serde(default = "default_true")]
    pub commit_required: bool,
}

fn default_max_attempts() -> u32 {
    3
}

/// Foreach configuration for simple parallel iteration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ForeachConfig {
    /// Input source (command or list)
    #[serde(rename = "foreach")]
    pub input: ForeachInput,

    /// Parallel execution config (bool or number)
    #[serde(default)]
    pub parallel: ParallelConfig,

    /// Commands to execute per item (renamed from "do" to avoid keyword)
    #[serde(rename = "do")]
    pub do_block: Vec<Box<WorkflowStepCommand>>,

    /// Continue on item failure
    #[serde(default)]
    pub continue_on_error: bool,

    /// Maximum items to process
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_items: Option<usize>,
}

/// Input source for foreach - either a command or a list
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ForeachInput {
    /// Command to execute whose output becomes items
    Command(String),
    /// Static list of items
    List(Vec<String>),
}

/// Parallel execution configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ParallelConfig {
    /// Boolean flag (true = default parallel count, false = sequential)
    Boolean(bool),
    /// Specific parallel count
    Count(usize),
}

impl Default for ParallelConfig {
    fn default() -> Self {
        ParallelConfig::Boolean(false)
    }
}

/// Test command configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TestCommand {
    /// The test command to execute
    pub command: String,

    /// Configuration for handling test failures
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_failure: Option<TestDebugConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum WorkflowCommand {
    /// Legacy string format
    Simple(String),
    /// Full structured format (check before WorkflowStep since it's more specific)
    Structured(Box<Command>),
    /// New workflow step format (must have claude or shell field)
    WorkflowStep(Box<WorkflowStepCommand>),
    /// Simple object format
    SimpleObject(SimpleCommand),
}

/// Simple command representation for basic workflows
///
/// Represents a command as a simple object with optional properties,
/// used for backward compatibility and simple workflows.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SimpleCommand {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub commit_required: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub analysis: Option<AnalysisConfig>,
}

/// Configuration for write_file command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct WriteFileConfig {
    /// Path to write file (supports variable interpolation)
    pub path: String,

    /// Content to write (supports variable interpolation)
    pub content: String,

    /// Format to use when writing (default: text)
    #[serde(default)]
    pub format: WriteFileFormat,

    /// File permissions in octal format (default: "0644")
    #[serde(default = "default_file_mode")]
    pub mode: String,

    /// Create parent directories if they don't exist (default: false)
    #[serde(default)]
    pub create_dirs: bool,
}

/// File format for write_file command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum WriteFileFormat {
    /// Plain text (no processing)
    #[default]
    Text,

    /// JSON with validation and pretty-printing
    Json,

    /// YAML with validation and formatting
    Yaml,
}

fn default_file_mode() -> String {
    "0644".to_string()
}

/// New workflow step command format supporting claude:, shell:, analyze:, and test: syntax
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct WorkflowStepCommand {
    /// Claude CLI command with args
    #[serde(skip_serializing_if = "Option::is_none")]
    pub claude: Option<String>,

    /// Shell command to execute
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shell: Option<String>,

    /// Analyze command configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub analyze: Option<HashMap<String, serde_json::Value>>,

    /// Test command configuration (deprecated, use shell with on_failure instead)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test: Option<TestCommand>,

    /// Foreach configuration for parallel iteration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub foreach: Option<ForeachConfig>,

    /// File writing configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub write_file: Option<WriteFileConfig>,

    /// Command ID for referencing outputs
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    /// Whether this command is expected to create commits
    #[serde(default)]
    pub commit_required: bool,

    /// Analysis configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub analysis: Option<AnalysisConfig>,

    /// Output declarations
    #[serde(skip_serializing_if = "Option::is_none")]
    pub outputs: Option<HashMap<String, OutputDeclaration>>,

    /// Whether to capture command output (bool for backward compat, string for variable name)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture_output: Option<CaptureOutputConfig>,

    /// Conditional execution on failure (for shell commands, replaces test on_failure)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_failure: Option<TestDebugConfig>,

    /// Conditional execution on success
    #[serde(skip_serializing_if = "Option::is_none")]
    pub on_success: Option<Box<WorkflowStepCommand>>,

    /// Validation configuration for checking implementation completeness
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validate: Option<crate::cook::workflow::validation::ValidationConfig>,

    /// Timeout in seconds for command execution
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout: Option<u64>,

    /// Conditional execution expression
    #[serde(skip_serializing_if = "Option::is_none")]
    pub when: Option<String>,

    /// Format for captured output (json, text, lines)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_format: Option<String>,

    /// Which streams to capture (stdout, stderr, both)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_streams: Option<String>,

    /// File to redirect output to
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_file: Option<String>,
}

/// Configuration for output capture
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum CaptureOutputConfig {
    /// Simple boolean for backward compatibility
    Boolean(bool),
    /// Variable name to capture to
    Variable(String),
}

impl<'de> Deserialize<'de> for WorkflowStepCommand {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Helper {
            claude: Option<String>,
            shell: Option<String>,
            analyze: Option<HashMap<String, serde_json::Value>>,
            test: Option<TestCommand>,
            foreach: Option<ForeachConfig>,
            write_file: Option<WriteFileConfig>,
            id: Option<String>,
            #[serde(default)]
            commit_required: bool,
            analysis: Option<AnalysisConfig>,
            outputs: Option<HashMap<String, OutputDeclaration>>,
            #[serde(default)]
            capture_output: Option<CaptureOutputConfig>,
            on_failure: Option<TestDebugConfig>,
            on_success: Option<Box<WorkflowStepCommand>>,
            validate: Option<crate::cook::workflow::validation::ValidationConfig>,
            timeout: Option<u64>,
            when: Option<String>,
            capture_format: Option<String>,
            capture_streams: Option<String>,
            output_file: Option<String>,
        }

        let helper = Helper::deserialize(deserializer)?;

        // Handle deprecated test command - convert to shell with on_failure
        let (shell, test, on_failure) = if let Some(test_cmd) = helper.test {
            // Show deprecation warning
            eprintln!("Warning: 'test:' command syntax is deprecated. Use 'shell:' with 'on_failure:' instead.");
            eprintln!(
                "  Old: test: {{ command: \"{}\", on_failure: ... }}",
                test_cmd.command
            );
            eprintln!("  New: shell: \"{}\"", test_cmd.command);
            eprintln!("       on_failure: ...");

            // Convert test command to shell command
            let shell_cmd = Some(test_cmd.command.clone());
            let on_failure_config = test_cmd.on_failure.clone().or(helper.on_failure);
            (shell_cmd, None, on_failure_config)
        } else {
            (helper.shell, None, helper.on_failure)
        };

        // Validate that at least one command field is present
        if helper.claude.is_none()
            && shell.is_none()
            && helper.analyze.is_none()
            && helper.foreach.is_none()
            && helper.write_file.is_none()
        {
            return Err(serde::de::Error::custom(
                "WorkflowStepCommand must have 'claude', 'shell', 'analyze', 'foreach', or 'write_file' field",
            ));
        }

        Ok(WorkflowStepCommand {
            claude: helper.claude,
            shell,
            analyze: helper.analyze,
            test,
            foreach: helper.foreach,
            write_file: helper.write_file,
            id: helper.id,
            commit_required: helper.commit_required,
            analysis: helper.analysis,
            outputs: helper.outputs,
            capture_output: helper.capture_output,
            on_failure,
            on_success: helper.on_success,
            validate: helper.validate,
            timeout: helper.timeout,
            when: helper.when,
            capture_format: helper.capture_format,
            capture_streams: helper.capture_streams,
            output_file: helper.output_file,
        })
    }
}

impl WorkflowCommand {
    /// Convert a `WorkflowCommand` to a unified `Command` representation
    ///
    /// This method handles the conversion of various workflow command formats
    /// into a unified `Command` type suitable for execution. The conversion flow:
    ///
    /// 1. **Simple**: Direct string parsing via `Command::from_string`
    /// 2. **Structured**: Clone the boxed Command
    /// 3. **WorkflowStep**: Extract command string, parse, and apply metadata
    /// 4. **SimpleObject**: Build command with optional args and metadata
    ///
    /// The method uses helper functions to maintain low complexity:
    /// - `extract_command_string`: Handles command type branching
    /// - `apply_workflow_metadata`: Configures commit and analysis settings
    /// - `build_simple_command`: Constructs from SimpleCommand object
    #[must_use]
    pub fn to_command(&self) -> Command {
        match self {
            WorkflowCommand::Simple(s) => Command::from_string(s),
            WorkflowCommand::Structured(c) => *c.clone(),
            WorkflowCommand::WorkflowStep(step) => {
                let step = &**step;
                let command_str = extract_command_string(step);
                let mut cmd = Command::from_string(&command_str);
                apply_workflow_metadata(&mut cmd, step);
                cmd
            }
            WorkflowCommand::SimpleObject(simple) => build_simple_command(simple),
        }
    }
}

/// Extract command string from a WorkflowStepCommand
///
/// Pure function that converts various command types (claude, shell, analyze, etc.)
/// into a string representation suitable for Command::from_string.
fn extract_command_string(step: &WorkflowStepCommand) -> String {
    if let Some(claude_cmd) = &step.claude {
        claude_cmd.clone()
    } else if let Some(shell_cmd) = &step.shell {
        // For shell commands, we might need special handling
        // For now, treat it as a simple command
        format!("shell {shell_cmd}")
    } else if let Some(_analyze_attrs) = &step.analyze {
        // Analyze commands are handled via modular handlers
        "analyze".to_string()
    } else if let Some(test_cmd) = &step.test {
        // For test commands, we need special handling
        format!("test {}", test_cmd.command)
    } else if let Some(foreach_config) = &step.foreach {
        // For foreach commands, we need special handling
        match &foreach_config.input {
            ForeachInput::Command(cmd) => format!("foreach {cmd}"),
            ForeachInput::List(items) => format!("foreach {} items", items.len()),
        }
    } else if let Some(write_file_config) = &step.write_file {
        // For write_file commands
        format!("write_file {}", write_file_config.path)
    } else {
        // No command specified
        String::new()
    }
}

/// Apply workflow metadata to a Command
///
/// Configures commit requirements, analysis settings, ID, and outputs
/// from the WorkflowStepCommand to the Command.
fn apply_workflow_metadata(cmd: &mut Command, step: &WorkflowStepCommand) {
    // Apply metadata
    cmd.metadata.commit_required = step.commit_required;
    if let Some(analysis) = &step.analysis {
        cmd.analysis = Some(analysis.clone());
        cmd.metadata.analysis = Some(analysis.clone());
    }

    // Apply ID and outputs
    cmd.id = step.id.clone();
    cmd.outputs = step.outputs.clone();
}

/// Build a Command from a SimpleCommand
///
/// Constructs a Command with optional commit requirements, arguments,
/// and analysis configuration from a SimpleCommand object.
fn build_simple_command(simple: &SimpleCommand) -> Command {
    let mut cmd = Command::new(&simple.name);

    if let Some(commit_required) = simple.commit_required {
        cmd.metadata.commit_required = commit_required;
    }

    if let Some(args) = &simple.args {
        for arg in args {
            cmd.args.push(CommandArg::parse(arg));
        }
    }

    if let Some(analysis) = simple.analysis.clone() {
        cmd.analysis = Some(analysis.clone());
        cmd.metadata.analysis = Some(analysis);
    }

    cmd
}

impl Command {
    /// Create a new command with default metadata
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            args: Vec::new(),
            options: HashMap::new(),
            metadata: CommandMetadata::default(),
            id: None,
            outputs: None,
            analysis: None,
        }
    }

    /// Parse a command from a simple string format
    #[must_use]
    pub fn from_string(s: &str) -> Self {
        // Use the command parser for proper argument handling
        match crate::config::command_parser::parse_command_string(s) {
            Ok(cmd) => cmd,
            Err(_) => {
                // Fallback to simple name-only command for backward compatibility
                let s = s.strip_prefix('/').unwrap_or(s);
                Self::new(s)
            }
        }
    }

    /// Add a positional argument
    pub fn with_arg(mut self, arg: impl Into<String>) -> Self {
        let arg_str = arg.into();
        self.args.push(CommandArg::parse(&arg_str));
        self
    }

    /// Add an option
    pub fn with_option(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.options.insert(key.into(), value);
        self
    }

    /// Set retries
    #[must_use]
    pub fn with_retries(mut self, retries: u32) -> Self {
        self.metadata.retries = Some(retries);
        self
    }

    /// Set timeout
    #[must_use]
    pub fn with_timeout(mut self, timeout: u64) -> Self {
        self.metadata.timeout = Some(timeout);
        self
    }

    /// Set continue on error
    #[must_use]
    pub fn with_continue_on_error(mut self, continue_on_error: bool) -> Self {
        self.metadata.continue_on_error = Some(continue_on_error);
        self
    }

    /// Add environment variable
    pub fn with_env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.env.insert(key.into(), value.into());
        self
    }
}

// Custom deserialization for Command to handle top-level commit_required
impl<'de> Deserialize<'de> for Command {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct CommandHelper {
            name: String,
            #[serde(default)]
            args: Vec<CommandArg>,
            #[serde(default)]
            options: HashMap<String, serde_json::Value>,
            #[serde(default)]
            metadata: CommandMetadata,
            id: Option<String>,
            outputs: Option<HashMap<String, OutputDeclaration>>,
            // Allow commit_required at top level for convenience
            commit_required: Option<bool>,
            // Allow analysis at top level for convenience
            analysis: Option<AnalysisConfig>,
        }

        let helper = CommandHelper::deserialize(deserializer)?;

        let mut metadata = helper.metadata;
        // If commit_required is specified at top level, use it
        if let Some(commit_required) = helper.commit_required {
            metadata.commit_required = commit_required;
        }

        // Handle analysis configuration - prefer top-level over metadata.analysis
        let analysis = helper.analysis.or(metadata.analysis.clone());
        if analysis.is_some() {
            metadata.analysis = analysis.clone();
        }

        Ok(Command {
            name: helper.name,
            args: helper.args,
            options: helper.options,
            metadata,
            id: helper.id,
            outputs: helper.outputs,
            analysis,
        })
    }
}

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

    #[test]
    fn test_command_creation() {
        let cmd = Command::new("prodigy-code-review")
            .with_arg("test")
            .with_option("focus", serde_json::json!("security"))
            .with_retries(3)
            .with_timeout(300);

        assert_eq!(cmd.name, "prodigy-code-review");
        assert_eq!(cmd.args.len(), 1);
        assert_eq!(cmd.args[0], CommandArg::Literal("test".to_string()));
        assert_eq!(
            cmd.options.get("focus"),
            Some(&serde_json::json!("security"))
        );
        assert_eq!(cmd.metadata.retries, Some(3));
        assert_eq!(cmd.metadata.timeout, Some(300));
    }

    #[test]
    fn test_command_from_string() {
        let cmd1 = Command::from_string("prodigy-code-review");
        assert_eq!(cmd1.name, "prodigy-code-review");
        assert!(cmd1.args.is_empty());

        let cmd2 = Command::from_string("/prodigy-lint");
        assert_eq!(cmd2.name, "prodigy-lint");

        // Test parsing commands with arguments
        let cmd3 = Command::from_string("prodigy-implement-spec iteration-123");
        assert_eq!(cmd3.name, "prodigy-implement-spec");
        assert_eq!(cmd3.args.len(), 1);
        assert_eq!(
            cmd3.args[0],
            CommandArg::Literal("iteration-123".to_string())
        );

        // Test parsing commands with options
        let cmd4 = Command::from_string("prodigy-code-review --focus security");
        assert_eq!(cmd4.name, "prodigy-code-review");
        assert_eq!(
            cmd4.options.get("focus"),
            Some(&serde_json::json!("security"))
        );
    }

    #[test]
    fn test_workflow_command_conversion() {
        let simple = WorkflowCommand::Simple("prodigy-code-review".to_string());
        let cmd = simple.to_command();
        assert_eq!(cmd.name, "prodigy-code-review");

        let simple_obj = WorkflowCommand::SimpleObject(SimpleCommand {
            name: "prodigy-code-review".to_string(),
            commit_required: None,
            args: None,
            analysis: None,
        });
        let cmd = simple_obj.to_command();
        assert_eq!(cmd.name, "prodigy-code-review");

        let structured = WorkflowCommand::Structured(Box::new(Command::new("prodigy-lint")));
        let cmd = structured.to_command();
        assert_eq!(cmd.name, "prodigy-lint");
    }

    #[test]
    fn test_command_serialization() {
        let cmd = Command::new("prodigy-code-review")
            .with_option("focus", serde_json::json!("performance"));

        let json = serde_json::to_string(&cmd).unwrap();
        let deserialized: Command = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.name, cmd.name);
        assert_eq!(deserialized.options, cmd.options);
    }

    #[test]
    fn test_commit_required_field() {
        // Test default value
        let cmd = Command::new("prodigy-implement-spec");
        assert!(!cmd.metadata.commit_required);

        // Test SimpleCommand with commit_required set to false
        let simple_obj = WorkflowCommand::SimpleObject(SimpleCommand {
            name: "prodigy-lint".to_string(),
            commit_required: Some(false),
            args: None,
            analysis: None,
        });
        let cmd = simple_obj.to_command();
        assert_eq!(cmd.name, "prodigy-lint");
        assert!(!cmd.metadata.commit_required);

        // Test SimpleCommand with commit_required set to true
        let simple_obj = WorkflowCommand::SimpleObject(SimpleCommand {
            name: "prodigy-fix".to_string(),
            commit_required: Some(true),
            args: None,
            analysis: None,
        });
        let cmd = simple_obj.to_command();
        assert_eq!(cmd.name, "prodigy-fix");
        assert!(cmd.metadata.commit_required);

        // Test SimpleCommand with commit_required not set (should default to false)
        let simple_obj = WorkflowCommand::SimpleObject(SimpleCommand {
            name: "prodigy-refactor".to_string(),
            commit_required: None,
            args: None,
            analysis: None,
        });
        let cmd = simple_obj.to_command();
        assert_eq!(cmd.name, "prodigy-refactor");
        assert!(!cmd.metadata.commit_required);
    }

    #[test]
    fn test_commit_required_serialization() {
        // Test serialization and deserialization of SimpleCommand with commit_required
        let simple_cmd = SimpleCommand {
            name: "prodigy-lint".to_string(),
            commit_required: Some(false),
            args: None,
            analysis: None,
        };

        let json = serde_json::to_string(&simple_cmd).unwrap();
        assert!(json.contains("\"commit_required\":false"));

        let deserialized: SimpleCommand = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.name, "prodigy-lint");
        assert_eq!(deserialized.commit_required, Some(false));

        // Test that commit_required is omitted when None
        let simple_cmd_none = SimpleCommand {
            name: "prodigy-test".to_string(),
            commit_required: None,
            args: None,
            analysis: None,
        };
        let json_none = serde_json::to_string(&simple_cmd_none).unwrap();
        assert!(!json_none.contains("commit_required"));
    }

    #[test]
    fn test_analysis_config_defaults() {
        let analysis_config = AnalysisConfig {
            force_refresh: false,
            max_cache_age: 300,
        };

        assert!(!analysis_config.force_refresh);
        assert_eq!(analysis_config.max_cache_age, 300);
    }

    #[test]
    fn test_analysis_config_serialization() {
        let analysis_config = AnalysisConfig {
            force_refresh: true,
            max_cache_age: 600,
        };

        let json = serde_json::to_string(&analysis_config).unwrap();
        let deserialized: AnalysisConfig = serde_json::from_str(&json).unwrap();

        assert!(deserialized.force_refresh);
        assert_eq!(deserialized.max_cache_age, 600);
    }

    #[test]
    fn test_command_with_analysis_config() {
        let mut cmd = Command::new("prodigy-code-review");
        cmd.metadata.analysis = Some(AnalysisConfig {
            force_refresh: false,
            max_cache_age: 300,
        });

        let json = serde_json::to_string(&cmd).unwrap();
        assert!(json.contains("\"analysis\""));
        assert!(json.contains("\"max_cache_age\":300"));

        let deserialized: Command = serde_json::from_str(&json).unwrap();
        assert!(deserialized.metadata.analysis.is_some());
        let analysis = deserialized.metadata.analysis.unwrap();
        assert_eq!(analysis.max_cache_age, 300);
    }

    #[test]
    fn test_default_cache_duration() {
        assert_eq!(default_cache_duration(), 300);
    }

    #[test]
    fn test_analysis_config_with_defaults() {
        // Test that deserializing with minimal fields works
        let json = r#"{
            "force_refresh": true
        }"#;
        let deserialized: AnalysisConfig = serde_json::from_str(json).unwrap();
        assert!(deserialized.force_refresh);
        assert_eq!(deserialized.max_cache_age, 300); // Should use default
    }

    #[test]
    fn test_workflow_step_command_parsing() {
        // Test parsing of new workflow step format
        let yaml = r#"
claude: "/prodigy-coverage"
id: coverage
commit_required: false
outputs:
  spec:
    file_pattern: "*-coverage-improvements.md"
analysis:
  max_cache_age: 300
"#;

        let step: WorkflowStepCommand = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(step.claude, Some("/prodigy-coverage".to_string()));
        assert_eq!(step.id, Some("coverage".to_string()));
        assert!(!step.commit_required);
        assert!(step.outputs.is_some());
        assert!(step.analysis.is_some());
        assert!(step.when.is_none());
    }

    #[test]
    fn test_workflow_step_command_with_when_clause() {
        // Test parsing with when clause
        let yaml = r#"
claude: "/prodigy-test"
when: "${build.success} == true"
"#;

        let step: WorkflowStepCommand = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(step.claude, Some("/prodigy-test".to_string()));
        assert_eq!(step.when, Some("${build.success} == true".to_string()));
    }

    #[test]
    fn test_conditional_workflow_serialization() {
        // Test serialization and deserialization of when clauses
        let step = WorkflowStepCommand {
            claude: Some("/prodigy-test".to_string()),
            shell: None,
            analyze: None,
            test: None,
            foreach: None,
            write_file: None,
            id: Some("test-step".to_string()),
            commit_required: false,
            analysis: None,
            outputs: None,
            capture_output: None,
            on_failure: None,
            on_success: None,
            validate: None,
            timeout: None,
            when: Some("${env} == 'production'".to_string()),
            capture_format: None,
            capture_streams: None,
            output_file: None,
        };

        let yaml = serde_yaml::to_string(&step).unwrap();
        assert!(yaml.contains("when:"));
        assert!(yaml.contains("${env} == 'production'"));

        let deserialized: WorkflowStepCommand = serde_yaml::from_str(&yaml).unwrap();
        assert_eq!(
            deserialized.when,
            Some("${env} == 'production'".to_string())
        );
    }

    #[test]
    fn test_workflow_command_with_workflow_step() {
        // Test the full workflow command enum with new step format
        let yaml = r#"
- claude: "/prodigy-coverage"
  id: coverage
  commit_required: false
"#;

        let commands: Vec<WorkflowCommand> = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(commands.len(), 1);

        match &commands[0] {
            WorkflowCommand::WorkflowStep(step) => {
                assert_eq!(step.claude, Some("/prodigy-coverage".to_string()));
                assert_eq!(step.id, Some("coverage".to_string()));
                assert!(!step.commit_required);
            }
            _ => panic!("Expected WorkflowStep variant"),
        }
    }

    #[test]
    fn test_untagged_enum_debug() {
        // Debug why untagged enum doesn't work
        let yaml_simple = r#"prodigy-code-review"#;
        let cmd_simple: WorkflowCommand = serde_yaml::from_str(yaml_simple).unwrap();
        assert!(matches!(cmd_simple, WorkflowCommand::Simple(_)));

        // Now test our new format FIRST since it's before SimpleObject in the enum
        let yaml_new = r#"
claude: "/prodigy-coverage"
id: coverage
"#;
        match serde_yaml::from_str::<WorkflowCommand>(yaml_new) {
            Ok(cmd) => {
                assert!(matches!(cmd, WorkflowCommand::WorkflowStep(_)));
            }
            Err(e) => panic!("Failed to parse new format: {e}"),
        }

        let yaml_simple_obj = r#"
name: prodigy-code-review
commit_required: false
"#;
        let cmd_simple_obj: WorkflowCommand = serde_yaml::from_str(yaml_simple_obj).unwrap();
        // With the new enum ordering, this parses as Structured since Command can deserialize from minimal fields
        assert!(matches!(cmd_simple_obj, WorkflowCommand::Structured(_)));
    }

    #[test]
    fn test_workflow_config_with_new_syntax() {
        let config = parse_test_workflow_config();
        assert_eq!(config.commands.len(), 3);

        verify_coverage_command(&config.commands[0]);
        verify_implement_spec_command(&config.commands[1]);
        verify_lint_command(&config.commands[2]);
    }

    fn parse_test_workflow_config() -> WorkflowConfig {
        let yaml = r#"
commands:
    - claude: "/prodigy-coverage"
      id: coverage
      commit_required: false
      outputs:
        spec:
          file_pattern: "*-coverage-improvements.md"
      analysis:
        max_cache_age: 300
    
    - claude: "/prodigy-implement-spec ${coverage.spec}"
    
    - claude: "/prodigy-lint"
      commit_required: false
"#;

        serde_yaml::from_str(yaml).unwrap_or_else(|e| {
            debug_workflow_parsing_error(yaml, &e);
            panic!("Failed to parse WorkflowConfig: {e}");
        })
    }

    fn debug_workflow_parsing_error(yaml: &str, _error: &serde_yaml::Error) {
        let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
        if let Some(commands) = yaml_value.get("commands") {
            println!("Commands value: {commands:?}");
            if let Some(seq) = commands.as_sequence() {
                debug_command_sequence(seq);
            }
        }
    }

    fn debug_command_sequence(seq: &[serde_yaml::Value]) {
        for (i, cmd) in seq.iter().enumerate() {
            println!("\nCommand {i}: {cmd:?}");
            try_parse_as::<WorkflowStepCommand>(cmd, "WorkflowStepCommand");
            try_parse_as::<WorkflowCommand>(cmd, "WorkflowCommand");
        }
    }

    fn try_parse_as<T: serde::de::DeserializeOwned + std::fmt::Debug>(
        value: &serde_yaml::Value,
        type_name: &str,
    ) {
        match serde_yaml::from_value::<T>(value.clone()) {
            Ok(parsed) => println!("  Parsed as {type_name}: {parsed:?}"),
            Err(e) => println!("  Failed as {type_name}: {e}"),
        }
    }

    fn verify_coverage_command(command: &WorkflowCommand) {
        match command {
            WorkflowCommand::WorkflowStep(step) => {
                assert_eq!(step.claude, Some("/prodigy-coverage".to_string()));
                assert_eq!(step.id, Some("coverage".to_string()));
                assert!(!step.commit_required);
                assert!(step.outputs.is_some());
                assert!(step.analysis.is_some());
            }
            _ => panic!("Expected WorkflowStep variant for coverage command"),
        }
    }

    fn verify_implement_spec_command(command: &WorkflowCommand) {
        match command {
            WorkflowCommand::WorkflowStep(step) => {
                assert_eq!(
                    step.claude,
                    Some("/prodigy-implement-spec ${coverage.spec}".to_string())
                );
            }
            _ => panic!("Expected WorkflowStep variant for implement-spec command"),
        }
    }

    fn verify_lint_command(command: &WorkflowCommand) {
        match command {
            WorkflowCommand::WorkflowStep(step) => {
                assert_eq!(step.claude, Some("/prodigy-lint".to_string()));
                assert!(!step.commit_required);
            }
            _ => panic!("Expected WorkflowStep variant for lint command"),
        }
    }
}