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
//! Command runner implementation

use super::{CommandExecutor, ExecutionContext, ExecutionResult};
use crate::abstractions::exit_status::ExitStatusExt;
use crate::subprocess::runner::ProcessOutput;
use crate::subprocess::streaming::StreamingOutput;
use crate::subprocess::{ProcessCommand, ProcessCommandBuilder, SubprocessManager};
use anyhow::{Context, Result};
use async_trait::async_trait;
use std::collections::HashMap;

/// Build a ProcessCommand from execution context
///
/// This is a pure function that constructs a command with all configuration
/// from the execution context (working directory, env vars, timeout, stdin).
fn build_command_from_context(
    cmd: &str,
    args: &[String],
    context: &ExecutionContext,
) -> ProcessCommand {
    let mut builder = ProcessCommandBuilder::new(cmd)
        .args(args)
        .current_dir(&context.working_directory);

    // Set environment variables
    for (key, value) in &context.env_vars {
        builder = builder.env(key, value);
    }

    // Set timeout if specified
    if let Some(timeout) = context.timeout_seconds {
        builder = builder.timeout(std::time::Duration::from_secs(timeout));
    }

    // Set stdin if specified
    if let Some(stdin) = &context.stdin {
        builder = builder.stdin(stdin.clone());
    }

    builder.build()
}

/// Transform streaming output to ExecutionResult
///
/// This is a pure function that converts StreamingOutput (with stdout/stderr as `Vec<String>`)
/// into ExecutionResult (with stdout/stderr as joined strings).
fn streaming_output_to_result(output: StreamingOutput) -> ExecutionResult {
    ExecutionResult {
        success: output.status.success(),
        stdout: output.stdout.join("\n"),
        stderr: output.stderr.join("\n"),
        exit_code: output.status.code(),
        metadata: HashMap::new(),
    }
}

/// Transform batch output to ExecutionResult
///
/// This is a pure function that converts ProcessOutput (with stdout/stderr as String)
/// into ExecutionResult with the same string format.
fn batch_output_to_result(output: ProcessOutput) -> ExecutionResult {
    ExecutionResult {
        success: output.status.success(),
        stdout: output.stdout,
        stderr: output.stderr,
        exit_code: output.status.code(),
        metadata: HashMap::new(),
    }
}

/// Determine if streaming mode should be used
///
/// This is a pure function that checks the execution context to determine
/// whether to use streaming or batch mode for command execution.
fn should_use_streaming(context: &ExecutionContext) -> bool {
    context
        .streaming_config
        .as_ref()
        .map(|config| config.enabled)
        .unwrap_or(false)
}

/// Trait for running system commands
#[async_trait]
pub trait CommandRunner: Send + Sync {
    /// Run a command and return output
    async fn run_command(&self, cmd: &str, args: &[String]) -> Result<std::process::Output>;

    /// Run a command with full control
    async fn run_with_context(
        &self,
        cmd: &str,
        args: &[String],
        context: &ExecutionContext,
    ) -> Result<ExecutionResult>;

    /// Run a command with streaming output processing
    /// Default implementation falls back to buffered execution
    async fn run_with_streaming(
        &self,
        cmd: &str,
        args: &[String],
        context: &ExecutionContext,
        _output_handler: Box<dyn crate::subprocess::streaming::StreamProcessor>,
    ) -> Result<ExecutionResult> {
        // Default implementation falls back to buffered execution
        self.run_with_context(cmd, args, context).await
    }
}

/// Real implementation of command runner
pub struct RealCommandRunner {
    subprocess: SubprocessManager,
}

impl RealCommandRunner {
    /// Create a new command runner
    pub fn new() -> Self {
        Self {
            subprocess: SubprocessManager::production(),
        }
    }

    /// Create a new instance with custom subprocess manager (for testing)
    #[cfg(test)]
    pub fn with_subprocess(subprocess: SubprocessManager) -> Self {
        Self { subprocess }
    }

    /// Create stream processors from configuration
    fn create_processors(
        &self,
        config: &crate::subprocess::streaming::StreamingConfig,
    ) -> Result<Vec<Box<dyn crate::subprocess::streaming::StreamProcessor>>> {
        use crate::subprocess::streaming::{
            JsonLineProcessor, PatternMatchProcessor, ProcessorConfig, StreamProcessor,
        };

        let mut processors: Vec<Box<dyn StreamProcessor>> = Vec::new();

        for processor_config in &config.processors {
            match processor_config {
                ProcessorConfig::JsonLines { emit_events } => {
                    let (sender, _receiver) = tokio::sync::mpsc::channel(100);
                    processors.push(Box::new(JsonLineProcessor::new(sender, *emit_events)));
                }
                ProcessorConfig::PatternMatcher { patterns } => {
                    let (sender, _receiver) = tokio::sync::mpsc::channel(100);
                    processors.push(Box::new(PatternMatchProcessor::new(
                        patterns.clone(),
                        sender,
                    )));
                }
                ProcessorConfig::EventEmitter { .. } => {
                    // TODO: Implement event emitter when event system is ready
                    tracing::debug!("EventEmitter processor not yet implemented");
                }
                ProcessorConfig::Custom { id } => {
                    tracing::debug!("Custom processor '{}' not available in this context", id);
                }
            }
        }

        // Apply backpressure management if configured
        if let Some(max_lines) = config.buffer_config.max_lines {
            use crate::subprocess::streaming::BufferedStreamProcessor;

            processors = processors
                .into_iter()
                .map(|processor| {
                    Box::new(BufferedStreamProcessor::new(
                        processor,
                        max_lines,
                        config.buffer_config.overflow_strategy.clone(),
                        config.buffer_config.block_timeout,
                    )) as Box<dyn StreamProcessor>
                })
                .collect();
        }

        Ok(processors)
    }
}

impl Default for RealCommandRunner {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl CommandRunner for RealCommandRunner {
    async fn run_command(&self, cmd: &str, args: &[String]) -> Result<std::process::Output> {
        let command = ProcessCommandBuilder::new(cmd).args(args).build();

        let output = self
            .subprocess
            .runner()
            .run(command)
            .await
            .context(format!("Failed to execute command: {cmd}"))?;

        Ok(std::process::Output {
            status: std::process::ExitStatus::from_raw(output.status.code().unwrap_or(1)),
            stdout: output.stdout.into_bytes(),
            stderr: output.stderr.into_bytes(),
        })
    }

    async fn run_with_context(
        &self,
        cmd: &str,
        args: &[String],
        context: &ExecutionContext,
    ) -> Result<ExecutionResult> {
        let command = build_command_from_context(cmd, args, context);

        // Check if streaming is enabled
        if should_use_streaming(context) {
            if let Some(streaming_config) = &context.streaming_config {
                // Use streaming runner with the subprocess manager's runner
                let processors = self.create_processors(streaming_config)?;

                // Create streaming runner using TokioProcessRunner directly for now
                let streaming_runner = crate::subprocess::streaming::StreamingCommandRunner::new(
                    Box::new(crate::subprocess::runner::TokioProcessRunner),
                );

                let output = streaming_runner
                    .run_streaming(command, processors)
                    .await
                    .context(format!("Failed to execute command with streaming: {cmd}"))?;

                return Ok(streaming_output_to_result(output));
            }
        }

        // Fall back to batch mode
        let output = self
            .subprocess
            .runner()
            .run(command)
            .await
            .context(format!("Failed to execute command: {cmd}"))?;

        Ok(batch_output_to_result(output))
    }

    async fn run_with_streaming(
        &self,
        cmd: &str,
        args: &[String],
        context: &ExecutionContext,
        output_handler: Box<dyn crate::subprocess::streaming::StreamProcessor>,
    ) -> Result<ExecutionResult> {
        let command = build_command_from_context(cmd, args, context);

        // Create streaming runner
        let streaming_runner = crate::subprocess::streaming::StreamingCommandRunner::new(Box::new(
            crate::subprocess::runner::TokioProcessRunner,
        ));

        // Run with streaming, passing the single output handler
        let output = streaming_runner
            .run_streaming(command, vec![output_handler])
            .await
            .context(format!("Failed to execute command with streaming: {cmd}"))?;

        Ok(streaming_output_to_result(output))
    }
}

#[async_trait]
impl CommandExecutor for RealCommandRunner {
    async fn execute(
        &self,
        command: &str,
        args: &[String],
        context: ExecutionContext,
    ) -> Result<ExecutionResult> {
        self.run_with_context(command, args, &context).await
    }
}

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

    #[test]
    fn test_build_command_basic() {
        let context = ExecutionContext::default();
        let command = build_command_from_context("echo", &["hello".to_string()], &context);

        assert_eq!(command.program, "echo");
        assert_eq!(command.args, vec!["hello"]);
    }

    #[test]
    fn test_build_command_with_env_vars() {
        let mut context = ExecutionContext::default();
        context
            .env_vars
            .insert("TEST_VAR".to_string(), "test_value".to_string());
        context
            .env_vars
            .insert("ANOTHER_VAR".to_string(), "another_value".to_string());

        let command = build_command_from_context("test", &[], &context);

        assert_eq!(command.env.get("TEST_VAR"), Some(&"test_value".to_string()));
        assert_eq!(
            command.env.get("ANOTHER_VAR"),
            Some(&"another_value".to_string())
        );
    }

    #[test]
    fn test_build_command_with_timeout() {
        let context = ExecutionContext {
            timeout_seconds: Some(60),
            ..Default::default()
        };

        let command = build_command_from_context("sleep", &["10".to_string()], &context);

        assert_eq!(command.timeout, Some(Duration::from_secs(60)));
    }

    #[test]
    fn test_build_command_with_stdin() {
        let context = ExecutionContext {
            stdin: Some("input data".to_string()),
            ..Default::default()
        };

        let command = build_command_from_context("cat", &[], &context);

        assert_eq!(command.stdin, Some("input data".to_string()));
    }

    #[test]
    fn test_streaming_output_to_result_success() {
        use crate::subprocess::streaming::StreamingOutput;
        use std::time::Duration;

        let output = StreamingOutput {
            status: std::process::ExitStatus::from_raw(0),
            stdout: vec!["line1".to_string(), "line2".to_string()],
            stderr: vec!["error1".to_string()],
            duration: Duration::from_secs(1),
        };

        let result = streaming_output_to_result(output);

        assert!(result.success);
        assert_eq!(result.stdout, "line1\nline2");
        assert_eq!(result.stderr, "error1");
        assert_eq!(result.exit_code, Some(0));
    }

    #[test]
    fn test_streaming_output_to_result_failure() {
        use crate::subprocess::streaming::StreamingOutput;
        use std::time::Duration;

        let output = StreamingOutput {
            status: std::process::ExitStatus::from_raw(256), // Exit code 1 is encoded as 256 on Unix
            stdout: vec![],
            stderr: vec!["error message".to_string()],
            duration: Duration::from_secs(1),
        };

        let result = streaming_output_to_result(output);

        assert!(!result.success);
        assert_eq!(result.stdout, "");
        assert_eq!(result.stderr, "error message");
        assert_eq!(result.exit_code, Some(1));
    }

    #[test]
    fn test_batch_output_to_result_success() {
        use crate::subprocess::runner::{ExitStatus, ProcessOutput};
        use std::time::Duration;

        let output = ProcessOutput {
            status: ExitStatus::Success,
            stdout: "output text".to_string(),
            stderr: String::new(),
            duration: Duration::from_secs(1),
        };

        let result = batch_output_to_result(output);

        assert!(result.success);
        assert_eq!(result.stdout, "output text");
        assert_eq!(result.stderr, "");
        assert_eq!(result.exit_code, Some(0));
    }

    #[test]
    fn test_batch_output_to_result_failure() {
        use crate::subprocess::runner::{ExitStatus, ProcessOutput};
        use std::time::Duration;

        let output = ProcessOutput {
            status: ExitStatus::Error(42),
            stdout: String::new(),
            stderr: "error output".to_string(),
            duration: Duration::from_secs(1),
        };

        let result = batch_output_to_result(output);

        assert!(!result.success);
        assert_eq!(result.stdout, "");
        assert_eq!(result.stderr, "error output");
        assert_eq!(result.exit_code, Some(42));
    }

    #[test]
    fn test_should_use_streaming_no_config() {
        let context = ExecutionContext::default();
        assert!(!should_use_streaming(&context));
    }

    #[test]
    fn test_should_use_streaming_disabled() {
        use crate::subprocess::streaming::{BufferConfig, StreamingConfig, StreamingMode};

        let context = ExecutionContext {
            streaming_config: Some(StreamingConfig {
                enabled: false,
                mode: StreamingMode::Streaming,
                processors: vec![],
                buffer_config: BufferConfig::default(),
            }),
            ..Default::default()
        };

        assert!(!should_use_streaming(&context));
    }

    #[test]
    fn test_should_use_streaming_enabled() {
        use crate::subprocess::streaming::{BufferConfig, StreamingConfig, StreamingMode};

        let context = ExecutionContext {
            streaming_config: Some(StreamingConfig {
                enabled: true,
                mode: StreamingMode::Streaming,
                processors: vec![],
                buffer_config: BufferConfig::default(),
            }),
            ..Default::default()
        };

        assert!(should_use_streaming(&context));
    }

    #[test]
    fn test_build_command_with_all_options() {
        let mut context = ExecutionContext::default();
        context
            .env_vars
            .insert("VAR1".to_string(), "value1".to_string());
        context.timeout_seconds = Some(30);
        context.stdin = Some("test input".to_string());

        let command = build_command_from_context(
            "sh",
            &["-c".to_string(), "echo $VAR1".to_string()],
            &context,
        );

        assert_eq!(command.program, "sh");
        assert_eq!(command.args, vec!["-c", "echo $VAR1"]);
        assert_eq!(command.env.get("VAR1"), Some(&"value1".to_string()));
        assert_eq!(command.timeout, Some(Duration::from_secs(30)));
        assert_eq!(command.stdin, Some("test input".to_string()));
    }

    #[tokio::test]
    async fn test_real_command_runner() {
        let runner = RealCommandRunner::new();

        // Test simple echo command
        let result = runner
            .run_command("echo", &["hello".to_string()])
            .await
            .unwrap();
        assert!(result.status.success());
        assert!(String::from_utf8_lossy(&result.stdout).contains("hello"));
    }

    #[tokio::test]
    async fn test_command_with_context() {
        let runner = RealCommandRunner::new();
        let mut context = ExecutionContext::default();
        context
            .env_vars
            .insert("TEST_VAR".to_string(), "test_value".to_string());

        // Test with environment variable
        let result = runner
            .run_with_context(
                "sh",
                &["-c".to_string(), "echo $TEST_VAR".to_string()],
                &context,
            )
            .await
            .unwrap();

        assert!(result.success);
        assert!(result.stdout.contains("test_value"));
    }

    // Mock implementation for testing
    pub struct MockCommandRunner {
        responses: std::sync::Mutex<Vec<ExecutionResult>>,
    }

    impl Default for MockCommandRunner {
        fn default() -> Self {
            Self::new()
        }
    }

    impl MockCommandRunner {
        pub fn new() -> Self {
            Self {
                responses: std::sync::Mutex::new(Vec::new()),
            }
        }

        pub fn add_response(&self, result: ExecutionResult) {
            self.responses.lock().unwrap().push(result);
        }
    }

    #[async_trait]
    impl CommandRunner for MockCommandRunner {
        async fn run_command(&self, _cmd: &str, _args: &[String]) -> Result<std::process::Output> {
            let mut responses = self.responses.lock().unwrap();
            if let Some(result) = responses.pop() {
                Ok(std::process::Output {
                    status: std::process::ExitStatus::from_raw(if result.success { 0 } else { 1 }),
                    stdout: result.stdout.into_bytes(),
                    stderr: result.stderr.into_bytes(),
                })
            } else {
                anyhow::bail!("No mock response configured")
            }
        }

        async fn run_with_context(
            &self,
            _cmd: &str,
            _args: &[String],
            _context: &ExecutionContext,
        ) -> Result<ExecutionResult> {
            let mut responses = self.responses.lock().unwrap();
            responses
                .pop()
                .ok_or_else(|| anyhow::anyhow!("No mock response configured"))
        }

        async fn run_with_streaming(
            &self,
            _cmd: &str,
            _args: &[String],
            _context: &ExecutionContext,
            output_handler: Box<dyn crate::subprocess::streaming::StreamProcessor>,
        ) -> Result<ExecutionResult> {
            // For testing, simulate streaming by sending lines to the processor
            let result = {
                let mut responses = self.responses.lock().unwrap();
                responses.pop()
            };

            if let Some(result) = result {
                // Simulate line-by-line processing
                for line in result.stdout.lines() {
                    let _ = output_handler
                        .process_line(line, crate::subprocess::streaming::StreamSource::Stdout)
                        .await;
                }
                for line in result.stderr.lines() {
                    let _ = output_handler
                        .process_line(line, crate::subprocess::streaming::StreamSource::Stderr)
                        .await;
                }
                let _ = output_handler.on_complete(result.exit_code).await;
                Ok(result)
            } else {
                anyhow::bail!("No mock response configured")
            }
        }
    }

    #[tokio::test]
    async fn test_mock_command_runner() {
        let mock = MockCommandRunner::new();
        mock.add_response(ExecutionResult {
            success: true,
            stdout: "mocked output".to_string(),
            stderr: String::new(),
            exit_code: Some(0),
            metadata: HashMap::new(),
        });

        let result = mock
            .run_with_context("test", &[], &ExecutionContext::default())
            .await
            .unwrap();

        assert!(result.success);
        assert_eq!(result.stdout, "mocked output");
    }
}