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
//! Validation and conditional execution logic
//!
//! Handles workflow validation, condition evaluation, and execution decisions.

use super::super::step_validation::StepValidationSpec;
use super::super::validation::{ValidationConfig, ValidationResult};
use super::{pure, StepResult, WorkflowContext, WorkflowExecutor, WorkflowStep};
use crate::cook::execution::ExecutionContext;
use crate::cook::expression::{ExpressionEvaluator, VariableContext};
use crate::cook::orchestrator::ExecutionEnvironment;
use anyhow::{anyhow, Context, Result};
use std::collections::HashMap;
use std::sync::Arc;

// ============================================================================
// Pure decision functions for validation retry logic
// ============================================================================

/// Determine if the retry loop should continue
///
/// Returns true if:
/// - attempts < max_attempts AND
/// - validation is incomplete
pub(super) fn should_continue_retry(attempts: u32, max_attempts: u32, is_complete: bool) -> bool {
    attempts < max_attempts && !is_complete
}

/// Handler type for incomplete validation
#[derive(Debug, Clone, PartialEq)]
pub(super) enum HandlerType {
    MultiCommand,
    SingleCommand,
    NoHandler,
}

/// Determine what type of handler is configured
pub(super) fn determine_handler_type(
    on_incomplete: &crate::cook::workflow::validation::OnIncompleteConfig,
) -> HandlerType {
    if on_incomplete.commands.is_some() {
        HandlerType::MultiCommand
    } else if on_incomplete.claude.is_some() || on_incomplete.shell.is_some() {
        HandlerType::SingleCommand
    } else {
        HandlerType::NoHandler
    }
}

/// Retry progress information
#[derive(Debug, Clone, PartialEq)]
#[allow(dead_code)]
pub(super) struct RetryProgress {
    pub(super) attempts: u32,
    pub(super) max_attempts: u32,
    pub(super) completion_percentage: f64,
}

/// Calculate retry progress for display/logging
#[allow(dead_code)]
pub(super) fn calculate_retry_progress(
    attempts: u32,
    max_attempts: u32,
    completion: f64,
) -> RetryProgress {
    RetryProgress {
        attempts,
        max_attempts,
        completion_percentage: completion,
    }
}

/// Determine if the workflow should fail based on validation state
///
/// Returns true if validation is incomplete AND fail_workflow is true
pub(super) fn should_fail_workflow(
    is_complete: bool,
    fail_workflow_flag: bool,
    _attempts: u32,
) -> bool {
    !is_complete && fail_workflow_flag
}

// ============================================================================
// Pure decision functions for execute_validation
// ============================================================================

/// Command mode for validation execution (renamed to avoid collision with step_validation::ValidationCommandType)
#[derive(Debug, Clone, PartialEq)]
pub(super) enum ValidationExecutionMode {
    CommandsArray,
    Claude,
    Shell,
    NoCommand,
}

/// Determine which command mode to execute (lines 539-621)
pub(super) fn determine_validation_execution_mode(
    config: &super::super::validation::ValidationConfig,
) -> ValidationExecutionMode {
    if config.commands.is_some() {
        ValidationExecutionMode::CommandsArray
    } else if config.claude.is_some() {
        ValidationExecutionMode::Claude
    } else if config.shell.is_some() || config.command.is_some() {
        ValidationExecutionMode::Shell
    } else {
        ValidationExecutionMode::NoCommand
    }
}

/// Check if result_file should be parsed after commands execution
pub(super) fn should_read_result_file_after_commands(
    config: &super::super::validation::ValidationConfig,
) -> bool {
    config.commands.is_some() && config.result_file.is_some()
}

/// Check if result_file should be used instead of stdout (legacy mode)
pub(super) fn should_use_result_file(config: &super::super::validation::ValidationConfig) -> bool {
    config.commands.is_none() && config.result_file.is_some()
}

/// Parse validation JSON with fallback to simple complete/failed result
pub(super) fn parse_validation_result_with_fallback(
    json_content: &str,
    command_success: bool,
) -> super::super::validation::ValidationResult {
    use super::super::validation::ValidationResult;

    match ValidationResult::from_json(json_content) {
        Ok(validation) => validation,
        Err(_) => {
            // If not JSON, treat as simple pass/fail based on command success
            if command_success {
                ValidationResult::complete()
            } else {
                ValidationResult::failed("Validation failed (non-JSON output)".to_string())
            }
        }
    }
}

/// Create a failed validation result for a command step failure
pub(super) fn create_command_step_failure_result(
    step_idx: usize,
    stdout: &str,
) -> super::super::validation::ValidationResult {
    super::super::validation::ValidationResult::failed(format!(
        "Validation step {} failed: {}",
        step_idx + 1,
        stdout
    ))
}

/// Create a failed validation result for file read errors
pub(super) fn create_file_read_error_result(
    file_path: &str,
    error: &str,
) -> super::super::validation::ValidationResult {
    super::super::validation::ValidationResult::failed(format!(
        "Failed to read validation result from {}: {}",
        file_path, error
    ))
}

/// Create a failed validation result for command execution failure
pub(super) fn create_command_execution_failure_result(
    exit_code: i32,
) -> super::super::validation::ValidationResult {
    super::super::validation::ValidationResult::failed(format!(
        "Validation command failed with exit code: {}",
        exit_code
    ))
}

/// Parse result file content with fallback to complete on non-JSON
pub(super) fn parse_result_file_content(
    content: &str,
) -> super::super::validation::ValidationResult {
    use super::super::validation::ValidationResult;

    match ValidationResult::from_json(content) {
        Ok(validation) => validation,
        Err(_) => ValidationResult::complete(),
    }
}

// ============================================================================
// Pure formatting functions for validation messages
// ============================================================================

/// Format a success message for passed validation
pub(super) fn format_validation_passed_message(results_count: usize, attempts: u32) -> String {
    format!(
        "Step validation passed ({} validation{}, {} attempt{})",
        results_count,
        if results_count == 1 { "" } else { "s" },
        attempts,
        if attempts == 1 { "" } else { "s" }
    )
}

/// Format a warning message for failed validation
pub(super) fn format_validation_failed_message(results_count: usize, attempts: u32) -> String {
    format!(
        "Step validation failed ({} validation{}, {} attempt{})",
        results_count,
        if results_count == 1 { "" } else { "s" },
        attempts,
        if attempts == 1 { "" } else { "s" }
    )
}

/// Format detailed message for a single failed validation
pub(super) fn format_failed_validation_detail(idx: usize, message: &str, exit_code: i32) -> String {
    format!(
        "  Validation {}: {} (exit code: {})",
        idx + 1,
        message,
        exit_code
    )
}

/// Determine step name for logging based on step properties
pub(super) fn determine_step_name(step: &WorkflowStep) -> &str {
    step.name.as_deref().unwrap_or_else(|| {
        if step.claude.is_some() {
            "claude command"
        } else if step.shell.is_some() {
            "shell command"
        } else {
            "workflow step"
        }
    })
}

// ============================================================================
// Pure helper functions for validation executor setup
// ============================================================================

/// Create execution context for step validation
///
/// Pure function that builds ExecutionContext with validation-specific settings
pub(super) fn create_validation_execution_context(
    working_directory: std::path::PathBuf,
    timeout_seconds: Option<u64>,
) -> ExecutionContext {
    ExecutionContext {
        working_directory,
        env_vars: std::collections::HashMap::new(),
        capture_output: true,
        timeout_seconds,
        stdin: None,
        capture_streaming: false,
        streaming_config: None,
    }
}

/// Create a timeout failure result for step validation
///
/// Pure function that builds StepValidationResult representing a timeout
pub(super) fn create_validation_timeout_result(
    timeout_secs: u64,
) -> super::super::step_validation::StepValidationResult {
    super::super::step_validation::StepValidationResult {
        passed: false,
        results: vec![],
        duration: std::time::Duration::from_secs(timeout_secs),
        attempts: 1,
    }
}

impl WorkflowExecutor {
    // ============================================================================
    // Validation functions
    // ============================================================================

    /// Handle workflow-level validation with retry logic
    pub(super) async fn handle_validation(
        &mut self,
        validation_config: &ValidationConfig,
        env: &ExecutionEnvironment,
        ctx: &mut WorkflowContext,
    ) -> Result<()> {
        // Skip validation execution in dry-run mode
        if self.dry_run {
            // Display what validation would be performed
            if let Some(claude_cmd) = &validation_config.claude {
                let validation_desc = format!("validation: claude {}", claude_cmd);
                println!("[DRY RUN] Would run validation (Claude): {}", claude_cmd);
                self.dry_run_validations.push(validation_desc);
            } else if let Some(shell_cmd) = validation_config
                .shell
                .as_ref()
                .or(validation_config.command.as_ref())
            {
                let validation_desc = format!("validation: shell {}", shell_cmd);
                println!("[DRY RUN] Would run validation (shell): {}", shell_cmd);
                self.dry_run_validations.push(validation_desc);
            }

            // Track potential on_incomplete handler
            if let Some(on_incomplete) = &validation_config.on_incomplete {
                let handler_desc = if let Some(commands) = &on_incomplete.commands {
                    format!("on_incomplete: {} commands", commands.len())
                } else if let Some(claude) = &on_incomplete.claude {
                    format!("on_incomplete: claude {}", claude)
                } else if let Some(shell) = &on_incomplete.shell {
                    format!("on_incomplete: shell {}", shell)
                } else {
                    "on_incomplete: unknown".to_string()
                };
                self.dry_run_potential_handlers.push(format!(
                    "{} (max {} attempts)",
                    handler_desc, on_incomplete.max_attempts
                ));
            }

            println!(
                "[DRY RUN] Validation threshold: {:.1}%",
                validation_config.threshold
            );
            println!("[DRY RUN] Assuming validation would pass");
            return Ok(());
        }

        // Execute validation
        let validation_result = self.execute_validation(validation_config, env, ctx).await?;

        // Store validation result in context
        ctx.validation_results
            .insert("validation".to_string(), validation_result.clone());

        // Always display validation percentage
        let percentage = validation_result.completion_percentage;
        let threshold = validation_config.threshold;

        // Check if validation passed
        if validation_config.is_complete(&validation_result) {
            self.user_interaction.display_success(&format!(
                "Validation passed: {:.1}% complete (threshold: {:.1}%)",
                percentage, threshold
            ));
        } else {
            self.user_interaction.display_warning(&format!(
                "Validation incomplete: {:.1}% complete (threshold: {:.1}%)",
                percentage, threshold
            ));

            // Handle incomplete validation
            if let Some(on_incomplete) = &validation_config.on_incomplete {
                self.handle_incomplete_validation(
                    validation_config,
                    on_incomplete,
                    validation_result,
                    env,
                    ctx,
                )
                .await?;
            }
        }
        Ok(())
    }

    /// Handle incomplete validation with retry logic
    async fn handle_incomplete_validation(
        &mut self,
        validation_config: &ValidationConfig,
        on_incomplete: &crate::cook::workflow::validation::OnIncompleteConfig,
        initial_result: ValidationResult,
        env: &ExecutionEnvironment,
        ctx: &mut WorkflowContext,
    ) -> Result<()> {
        let mut attempts = 0;
        let mut current_result = initial_result;

        while should_continue_retry(
            attempts,
            on_incomplete.max_attempts,
            validation_config.is_complete(&current_result),
        ) {
            attempts += 1;

            self.user_interaction.display_info(&format!(
                "Attempting to complete implementation (attempt {}/{})",
                attempts, on_incomplete.max_attempts
            ));

            // Execute the completion handler(s) based on handler type
            let handler_success = match determine_handler_type(on_incomplete) {
                HandlerType::MultiCommand => {
                    // Execute array of commands
                    let commands = on_incomplete.commands.as_ref().unwrap();
                    self.user_interaction
                        .display_progress(&format!("Running {} recovery commands", commands.len()));

                    let mut all_success = true;
                    for (idx, cmd) in commands.iter().enumerate() {
                        let step = self.convert_workflow_command_to_step(cmd, ctx)?;
                        let step_display = self.get_interpolated_step_display_name(&step, ctx);
                        self.user_interaction.display_progress(&format!(
                            "  Recovery step {}/{}: {}",
                            idx + 1,
                            commands.len(),
                            step_display
                        ));

                        let handler_result = Box::pin(self.execute_step(&step, env, ctx)).await?;

                        if !handler_result.success {
                            self.user_interaction
                                .display_error(&format!("Recovery step {} failed", idx + 1));
                            all_success = false;
                            break;
                        }
                    }
                    all_success
                }
                HandlerType::SingleCommand => {
                    // Execute single command (legacy)
                    let handler_step = self.create_validation_handler(on_incomplete, ctx).unwrap();
                    let step_display = self.get_interpolated_step_display_name(&handler_step, ctx);
                    self.user_interaction
                        .display_progress(&format!("Running recovery step: {}", step_display));

                    let handler_result =
                        Box::pin(self.execute_step(&handler_step, env, ctx)).await?;
                    handler_result.success
                }
                HandlerType::NoHandler => {
                    self.user_interaction
                        .display_error("No recovery commands configured");
                    false
                }
            };

            if !handler_success {
                break;
            }

            // Re-run validation
            current_result = self.execute_validation(validation_config, env, ctx).await?;

            // Display validation percentage after each attempt
            let percentage = current_result.completion_percentage;
            let threshold = validation_config.threshold;
            if validation_config.is_complete(&current_result) {
                self.user_interaction.display_success(&format!(
                    "Validation passed: {:.1}% complete (threshold: {:.1}%)",
                    percentage, threshold
                ));
            } else {
                self.user_interaction.display_info(&format!(
                    "Validation still incomplete: {:.1}% complete (threshold: {:.1}%)",
                    percentage, threshold
                ));
            }

            // Update context
            ctx.validation_results
                .insert("validation".to_string(), current_result.clone());
        }

        // Interactive mode (outside the retry loop)
        if !validation_config.is_complete(&current_result) {
            if let Some(on_incomplete_cfg) = &validation_config.on_incomplete {
                if let Some(ref prompt) = on_incomplete_cfg.prompt {
                    let _should_continue =
                        self.user_interaction.prompt_confirmation(prompt).await?;
                    // User was prompted, continue with workflow
                }
            }
        }

        // Check if we should fail the workflow
        if should_fail_workflow(
            validation_config.is_complete(&current_result),
            on_incomplete.fail_workflow,
            attempts,
        ) {
            return Err(anyhow!(
                "Validation failed after {} attempts. Completion: {:.1}%",
                attempts,
                current_result.completion_percentage
            ));
        }

        Ok(())
    }

    /// Handle step validation (first-class validation feature)
    pub(super) async fn handle_step_validation(
        &mut self,
        validation_spec: &StepValidationSpec,
        env: &ExecutionEnvironment,
        ctx: &mut WorkflowContext,
        step: &WorkflowStep,
    ) -> Result<super::super::step_validation::StepValidationResult> {
        // Skip validation execution in dry-run mode
        if self.dry_run {
            // Display what validation would be performed
            match validation_spec {
                StepValidationSpec::Single(cmd) => {
                    println!("[DRY RUN] Would run step validation: {}", cmd);
                }
                StepValidationSpec::Multiple(cmds) => {
                    println!("[DRY RUN] Would run step validation commands:");
                    for cmd in cmds {
                        println!("[DRY RUN]   - {}", cmd);
                    }
                }
                StepValidationSpec::Detailed(config) => {
                    println!("[DRY RUN] Would run detailed step validation commands:");
                    for cmd in &config.commands {
                        println!("[DRY RUN]   - {}", cmd.command);
                    }
                }
            }
            println!("[DRY RUN] Assuming step validation would pass");

            // Return a simulated successful validation result
            return Ok(super::super::step_validation::StepValidationResult {
                passed: true,
                results: vec![],
                duration: std::time::Duration::from_secs(0),
                attempts: 0,
            });
        }

        // Create a validation executor with the command executor
        let validation_executor = super::super::step_validation::StepValidationExecutor::new(
            Arc::new(super::StepValidationCommandExecutor {
                workflow_executor: self as *mut WorkflowExecutor,
                env: env.clone(),
                ctx: ctx.clone(),
            }) as Arc<dyn crate::cook::execution::CommandExecutor>,
        );

        // Create execution context for validation
        let exec_context = create_validation_execution_context(
            env.working_dir.to_path_buf(),
            step.validation_timeout,
        );

        // Get step name for logging
        let step_name = determine_step_name(step);

        // Execute validation with timeout if specified
        let validation_future =
            validation_executor.validate_step(validation_spec, &exec_context, step_name);

        let validation_result = if let Some(timeout_secs) = step.validation_timeout {
            let timeout = tokio::time::Duration::from_secs(timeout_secs);
            match tokio::time::timeout(timeout, validation_future).await {
                Ok(result) => result?,
                Err(_) => {
                    self.user_interaction.display_error(&format!(
                        "Step validation timed out after {} seconds",
                        timeout_secs
                    ));
                    create_validation_timeout_result(timeout_secs)
                }
            }
        } else {
            validation_future.await?
        };

        // Display validation result
        if validation_result.passed {
            let message = format_validation_passed_message(
                validation_result.results.len(),
                validation_result.attempts,
            );
            self.user_interaction.display_success(&message);
        } else {
            let message = format_validation_failed_message(
                validation_result.results.len(),
                validation_result.attempts,
            );
            self.user_interaction.display_warning(&message);

            // Show details of failed validations
            for (idx, result) in validation_result.results.iter().enumerate() {
                if !result.passed {
                    let detail =
                        format_failed_validation_detail(idx, &result.message, result.exit_code);
                    self.user_interaction.display_info(&detail);
                }
            }
        }

        Ok(validation_result)
    }

    /// Execute step-level validation (legacy and first-class)
    pub(super) async fn execute_step_validation(
        &mut self,
        step: &WorkflowStep,
        result: &mut StepResult,
        actual_env: &ExecutionEnvironment,
        ctx: &mut WorkflowContext,
    ) -> Result<()> {
        // Skip validation in dry-run mode since validation was already simulated in execute_command_by_type
        if !result.success || self.dry_run {
            return Ok(());
        }

        // Handle legacy validation config
        if let Some(validation_config) = &step.validate {
            self.handle_validation(validation_config, actual_env, ctx)
                .await?;
        }

        // Handle step validation (first-class validation feature)
        if let Some(step_validation) = &step.step_validate {
            if !step.skip_validation {
                let validation_result = self
                    .handle_step_validation(step_validation, actual_env, ctx, step)
                    .await?;

                // Update result based on validation
                if !validation_result.passed && !step.ignore_validation_failure {
                    result.success = false;
                    result.stdout.push_str(&format!(
                        "\n[Validation Failed: {} validation(s) executed, {} attempt(s) made]",
                        validation_result.results.len(),
                        validation_result.attempts
                    ));
                    if result.exit_code == Some(0) {
                        result.exit_code = Some(1); // Set exit code to indicate validation failure
                    }
                }
            }
        }

        Ok(())
    }

    /// Execute validation command and parse result
    pub(super) async fn execute_validation(
        &mut self,
        validation_config: &ValidationConfig,
        env: &ExecutionEnvironment,
        ctx: &mut WorkflowContext,
    ) -> Result<ValidationResult> {
        use crate::cook::workflow::validation::ValidationResult;

        // Determine which command mode to execute using pure function
        match determine_validation_execution_mode(validation_config) {
            ValidationExecutionMode::CommandsArray => {
                self.execute_validation_commands_array(validation_config, env, ctx)
                    .await
            }
            ValidationExecutionMode::Claude | ValidationExecutionMode::Shell => {
                self.execute_validation_single_command(validation_config, env, ctx)
                    .await
            }
            ValidationExecutionMode::NoCommand => Ok(ValidationResult::failed(
                "No validation command specified".to_string(),
            )),
        }
    }

    /// Execute validation using commands array
    async fn execute_validation_commands_array(
        &mut self,
        validation_config: &ValidationConfig,
        env: &ExecutionEnvironment,
        ctx: &mut WorkflowContext,
    ) -> Result<ValidationResult> {
        use crate::cook::workflow::validation::ValidationResult;

        let commands = validation_config.commands.as_ref().unwrap();

        self.user_interaction.display_progress(&format!(
            "Running validation with {} commands",
            commands.len()
        ));

        for (idx, cmd) in commands.iter().enumerate() {
            self.user_interaction.display_progress(&format!(
                "  Validation step {}/{}",
                idx + 1,
                commands.len()
            ));

            // Execute each command as a workflow step
            let step = self.convert_workflow_command_to_step(cmd, ctx)?;
            // Box the future to avoid recursion issues
            let step_result = Box::pin(self.execute_step(&step, env, ctx)).await?;

            if !step_result.success {
                return Ok(create_command_step_failure_result(idx, &step_result.stdout));
            }
        }

        // After executing all commands, check for result_file using pure function
        if should_read_result_file_after_commands(validation_config) {
            let result_file = validation_config.result_file.as_ref().unwrap();
            let (interpolated_file, _) = ctx.interpolate_with_tracking(result_file);
            let file_path = env.working_dir.join(&interpolated_file);

            match tokio::fs::read_to_string(&file_path).await {
                Ok(content) => return Ok(parse_result_file_content(&content)),
                Err(e) => {
                    return Ok(create_file_read_error_result(
                        &interpolated_file,
                        &e.to_string(),
                    ));
                }
            }
        }

        // All commands succeeded, return complete
        Ok(ValidationResult::complete())
    }

    /// Execute validation using single command (Claude or Shell)
    async fn execute_validation_single_command(
        &mut self,
        validation_config: &ValidationConfig,
        env: &ExecutionEnvironment,
        ctx: &mut WorkflowContext,
    ) -> Result<ValidationResult> {
        use crate::cook::workflow::validation::ValidationResult;

        // Execute either claude or shell command (legacy single-command mode)
        let result = if let Some(claude_cmd) = &validation_config.claude {
            let (command, resolutions) = ctx.interpolate_with_tracking(claude_cmd);
            self.log_variable_resolutions(&resolutions);
            self.user_interaction
                .display_progress(&format!("Running validation (Claude): {}", command));

            // Execute Claude command for validation
            // Use prepare_env_vars to get environment variables with proper streaming flag propagation
            let dummy_step = WorkflowStep::default();
            let env_vars = self.prepare_env_vars(&dummy_step, env, ctx);
            self.execute_claude_command(&command, env, env_vars).await?
        } else if let Some(shell_cmd) = validation_config
            .shell
            .as_ref()
            .or(validation_config.command.as_ref())
        {
            // Prefer 'shell' field, fall back to 'command' for backward compatibility
            let (command, resolutions) = ctx.interpolate_with_tracking(shell_cmd);
            self.log_variable_resolutions(&resolutions);
            self.user_interaction
                .display_progress(&format!("Running validation (shell): {}", command));

            // Execute shell command
            let mut env_vars = HashMap::new();
            env_vars.insert("PRODIGY_VALIDATION".to_string(), "true".to_string());

            self.execute_shell_command(&command, env, env_vars, validation_config.timeout)
                .await?
        } else {
            // This should not happen because determine_validation_command_type already checked
            return Ok(ValidationResult::failed(
                "No validation command specified".to_string(),
            ));
        };

        // Check if command execution failed using pure function
        if !result.success {
            return Ok(create_command_execution_failure_result(
                result.exit_code.unwrap_or(-1),
            ));
        }

        // Get JSON content from result_file or stdout using pure function decision
        let json_content = if should_use_result_file(validation_config) {
            let result_file = validation_config.result_file.as_ref().unwrap();
            let (interpolated_file, _resolutions) = ctx.interpolate_with_tracking(result_file);
            let file_path = env.working_dir.join(&interpolated_file);

            match tokio::fs::read_to_string(&file_path).await {
                Ok(content) => content,
                Err(e) => {
                    return Ok(create_file_read_error_result(
                        &interpolated_file,
                        &e.to_string(),
                    ));
                }
            }
        } else {
            result.stdout.clone()
        };

        // Parse JSON with fallback using pure function
        let mut validation = parse_validation_result_with_fallback(&json_content, result.success);
        validation.raw_output = Some(result.stdout);
        Ok(validation)
    }

    // ============================================================================
    // Conditional execution functions
    // ============================================================================

    /// Handle conditional execution (on_failure, on_success, on_exit_code)
    pub(super) async fn handle_conditional_execution(
        &mut self,
        step: &WorkflowStep,
        mut result: StepResult,
        env: &ExecutionEnvironment,
        ctx: &mut WorkflowContext,
    ) -> Result<StepResult> {
        // Handle failure
        if !result.success {
            if let Some(on_failure_config) = &step.on_failure {
                result = self
                    .handle_on_failure(step, result, on_failure_config, env, ctx)
                    .await?;
            }
        } else if let Some(on_success) = &step.on_success {
            // Handle success
            self.user_interaction
                .display_info("Executing on_success step...");
            let success_result = Box::pin(self.execute_step(on_success, env, ctx)).await?;
            result.stdout.push_str("\n--- on_success output ---\n");
            result.stdout.push_str(&success_result.stdout);
        }

        // Handle exit code specific steps
        if let Some(exit_code) = result.exit_code {
            if let Some(exit_step) = step.on_exit_code.get(&exit_code) {
                self.user_interaction
                    .display_info(&format!("Executing on_exit_code[{exit_code}] step..."));
                let exit_result = Box::pin(self.execute_step(exit_step, env, ctx)).await?;
                result
                    .stdout
                    .push_str(&format!("\n--- on_exit_code[{exit_code}] output ---\n"));
                result.stdout.push_str(&exit_result.stdout);
            }
        }

        Ok(result)
    }

    /// Evaluate a when condition expression
    pub(crate) fn evaluate_when_condition(
        &self,
        when_expr: &str,
        context: &WorkflowContext,
    ) -> Result<bool> {
        let evaluator = ExpressionEvaluator::new();
        let mut variable_context = VariableContext::new();

        // Add workflow context variables to expression context
        for (key, value) in &context.variables {
            variable_context.set_string(key.clone(), value.clone());
        }

        // Add command outputs to expression context
        for (key, value) in &context.captured_outputs {
            variable_context.set_string(key.clone(), value.clone());
        }

        // Evaluate the expression
        evaluator
            .evaluate(when_expr, &variable_context)
            .with_context(|| format!("Failed to evaluate when condition: {}", when_expr))
    }

    // ============================================================================
    // Decision functions
    // ============================================================================

    /// Determine if workflow should fail based on command result (delegated to pure module)
    pub(super) fn should_fail_workflow_for_step(
        step_result: &StepResult,
        step: &WorkflowStep,
    ) -> bool {
        pure::should_fail_workflow_for_step(step_result, step)
    }

    /// Determine if workflow should continue iterations
    pub(super) async fn should_continue_iterations(
        &self,
        _env: &ExecutionEnvironment,
    ) -> Result<bool> {
        // Always continue iterations until max_iterations is reached
        // The iteration loop already handles the max_iterations check
        Ok(true)
    }

    // ============================================================================
    // Test helper functions
    // ============================================================================

    /// Check if this is the focus tracking test
    pub(crate) fn is_focus_tracking_test(&self) -> bool {
        self.test_config.as_ref().is_some_and(|c| c.track_focus)
    }

    /// Check if we should stop early in test mode
    pub fn should_stop_early_in_test_mode(&self) -> bool {
        // Check if we're configured to simulate no changes
        self.test_config.as_ref().is_some_and(|c| {
            c.no_changes_commands
                .iter()
                .any(|cmd| cmd.trim() == "prodigy-code-review" || cmd.trim() == "prodigy-lint")
        })
    }

    /// Check if this is a test mode command that should simulate no changes
    pub fn is_test_mode_no_changes_command(&self, command: &str) -> bool {
        if let Some(config) = &self.test_config {
            let command_name = command.trim_start_matches('/');
            // Extract just the command name, ignoring arguments
            let command_name = command_name
                .split_whitespace()
                .next()
                .unwrap_or(command_name);
            return config
                .no_changes_commands
                .iter()
                .any(|cmd| cmd.trim() == command_name);
        }
        false
    }
}