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
//! Claude command handler for AI-powered operations

use crate::commands::{
    AttributeSchema, AttributeValue, CommandHandler, CommandResult, ExecutionContext,
};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use std::time::Instant;

/// Handler for Claude CLI integration
pub struct ClaudeHandler;

impl ClaudeHandler {
    /// Creates a new Claude handler
    pub fn new() -> Self {
        Self
    }

    /// Builds the full prompt by loading and prepending context files
    async fn build_prompt_with_context(
        prompt: &str,
        context_files: &[AttributeValue],
        context: &ExecutionContext,
    ) -> Result<String, String> {
        let mut file_contents = Vec::new();
        for file_val in context_files {
            if let Some(file_path) = file_val.as_string() {
                let abs_path = context.resolve_path(file_path.as_ref());
                let content = tokio::fs::read_to_string(&abs_path)
                    .await
                    .map_err(|e| format!("Failed to read context file {file_path}: {e}"))?;
                file_contents.push(format!("=== {file_path} ===\n{content}"));
            }
        }

        if file_contents.is_empty() {
            Ok(prompt.to_string())
        } else {
            Ok(format!(
                "Context files:\n{}\n\nTask:\n{}",
                file_contents.join("\n\n"),
                prompt
            ))
        }
    }

    /// Extract and validate parameters from attributes
    fn extract_parameters(
        attributes: &HashMap<String, AttributeValue>,
    ) -> Result<ClaudeParameters, String> {
        let prompt = attributes
            .get("prompt")
            .and_then(|v| v.as_string())
            .ok_or_else(|| "Missing required attribute: prompt".to_string())?
            .clone();

        let model = attributes
            .get("model")
            .and_then(|v| v.as_string())
            .cloned()
            .unwrap_or_else(|| "claude-3-sonnet".to_string());

        let temperature = attributes
            .get("temperature")
            .and_then(|v| v.as_number())
            .unwrap_or(0.7);

        let max_tokens = attributes
            .get("max_tokens")
            .and_then(|v| v.as_number())
            .map(|n| n as u32)
            .unwrap_or(4096);

        let system = attributes
            .get("system")
            .and_then(|v| v.as_string())
            .cloned();

        let timeout = attributes
            .get("timeout")
            .and_then(|v| v.as_number())
            .unwrap_or(60.0) as u64;

        Ok(ClaudeParameters {
            prompt,
            model,
            temperature,
            max_tokens,
            system,
            timeout,
        })
    }

    /// Build CLI arguments for Claude command
    fn build_cli_args(
        model: &str,
        max_tokens: u32,
        temperature: f64,
        system: &Option<String>,
        prompt: String,
    ) -> Vec<String> {
        let mut args = vec![
            "--model".to_string(),
            model.to_string(),
            "--max-tokens".to_string(),
            max_tokens.to_string(),
            "--temperature".to_string(),
            temperature.to_string(),
        ];

        if let Some(sys) = system {
            args.push("--system".to_string());
            args.push(sys.clone());
        }

        args.push(prompt);
        args
    }

    /// Process the execution result and create a CommandResult
    fn process_execution_result(
        result: Result<std::process::Output, crate::subprocess::error::ProcessError>,
        duration: u64,
        model: &str,
        temperature: f64,
        max_tokens: u32,
    ) -> CommandResult {
        match result {
            Ok(output) => {
                let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).to_string();

                if output.status.success() {
                    CommandResult::success(json!({
                        "response": stdout,
                        "metadata": {
                            "model": model,
                            "temperature": temperature,
                            "max_tokens": max_tokens,
                        }
                    }))
                    .with_duration(duration)
                } else {
                    CommandResult::error(format!("Claude CLI failed: {stderr}"))
                        .with_duration(duration)
                }
            }
            Err(e) => CommandResult::error(format!("Failed to execute Claude CLI: {e}"))
                .with_duration(duration),
        }
    }
}

/// Parameters for Claude CLI execution
struct ClaudeParameters {
    prompt: String,
    model: String,
    temperature: f64,
    max_tokens: u32,
    system: Option<String>,
    timeout: u64,
}

#[async_trait]
impl CommandHandler for ClaudeHandler {
    fn name(&self) -> &str {
        "claude"
    }

    fn schema(&self) -> AttributeSchema {
        let mut schema = AttributeSchema::new("claude");
        schema.add_required("prompt", "The prompt to send to Claude");
        schema.add_optional("model", "The model to use (default: claude-3-sonnet)");
        schema.add_optional("temperature", "Temperature for generation (0.0-1.0)");
        schema.add_optional("max_tokens", "Maximum tokens to generate");
        schema.add_optional("system", "System prompt to use");
        schema.add_optional("context_files", "Files to include as context");
        schema.add_optional_with_default(
            "timeout",
            "Request timeout in seconds",
            AttributeValue::Number(60.0),
        );
        schema
    }

    async fn execute(
        &self,
        context: &ExecutionContext,
        mut attributes: HashMap<String, AttributeValue>,
    ) -> CommandResult {
        // Apply defaults
        self.schema().apply_defaults(&mut attributes);

        // Extract and validate parameters
        let params = match Self::extract_parameters(&attributes) {
            Ok(p) => p,
            Err(e) => return CommandResult::error(e),
        };

        // Build context from files if specified
        let full_prompt = if let Some(context_files) =
            attributes.get("context_files").and_then(|v| v.as_array())
        {
            match Self::build_prompt_with_context(&params.prompt, context_files, context).await {
                Ok(p) => p,
                Err(e) => return CommandResult::error(e),
            }
        } else {
            params.prompt.clone()
        };

        let start = Instant::now();

        if context.dry_run {
            let duration = start.elapsed().as_millis() as u64;
            return CommandResult::success(json!({
                "dry_run": true,
                "model": params.model,
                "prompt": full_prompt,
                "temperature": params.temperature,
                "max_tokens": params.max_tokens,
                "system": params.system,
            }))
            .with_duration(duration);
        }

        // Build Claude CLI command
        let cmd_args = Self::build_cli_args(
            &params.model,
            params.max_tokens,
            params.temperature,
            &params.system,
            full_prompt,
        );

        // Execute Claude CLI
        let result = context
            .executor
            .execute(
                "claude",
                &cmd_args.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
                Some(&context.working_dir),
                Some(context.full_env()),
                Some(std::time::Duration::from_secs(params.timeout)),
            )
            .await;

        let duration = start.elapsed().as_millis() as u64;

        Self::process_execution_result(
            result,
            duration,
            &params.model,
            params.temperature,
            params.max_tokens,
        )
    }

    fn description(&self) -> &str {
        "Integrates with Claude CLI for AI-powered code operations"
    }

    fn examples(&self) -> Vec<String> {
        vec![
            r#"{"prompt": "Review this code for improvements"}"#.to_string(),
            r#"{"prompt": "Generate unit tests", "context_files": ["src/main.rs"], "temperature": 0.5}"#.to_string(),
            r#"{"prompt": "Explain this error", "system": "You are a helpful debugging assistant"}"#.to_string(),
        ]
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::subprocess::adapter::MockSubprocessExecutor;
    #[cfg(unix)]
    use std::os::unix::process::ExitStatusExt;
    #[cfg(windows)]
    use std::os::windows::process::ExitStatusExt;
    use std::path::PathBuf;
    use std::process::Output;
    use std::sync::Arc;

    #[tokio::test]
    async fn test_claude_handler_schema() {
        let handler = ClaudeHandler::new();
        let schema = handler.schema();

        assert!(schema.required().contains_key("prompt"));
        assert!(schema.optional().contains_key("model"));
        assert!(schema.optional().contains_key("temperature"));
    }

    #[tokio::test]
    async fn test_claude_handler_execute() {
        let handler = ClaudeHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "claude",
            vec![
                "--model",
                "claude-3-sonnet",
                "--max-tokens",
                "4096",
                "--temperature",
                "0.7",
                "Test prompt",
            ],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(60)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Claude response".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Test prompt".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        assert!(data.get("response").is_some());
    }

    #[tokio::test]
    async fn test_claude_handler_dry_run() {
        let handler = ClaudeHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test")).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Test".to_string()),
        );
        attributes.insert("temperature".to_string(), AttributeValue::Number(0.5));

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        assert_eq!(data.get("dry_run"), Some(&json!(true)));
        assert_eq!(data.get("temperature"), Some(&json!(0.5)));
    }

    #[tokio::test]
    async fn test_missing_prompt_attribute() {
        let handler = ClaudeHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test"));

        let attributes = HashMap::new();
        let result = handler.execute(&context, attributes).await;

        assert!(!result.is_success());
        assert_eq!(result.error.unwrap(), "Missing required attribute: prompt");
    }

    #[tokio::test]
    async fn test_with_custom_model() {
        let handler = ClaudeHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test")).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Test".to_string()),
        );
        attributes.insert(
            "model".to_string(),
            AttributeValue::String("claude-3-opus".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        assert_eq!(data.get("model"), Some(&json!("claude-3-opus")));
    }

    #[tokio::test]
    async fn test_with_max_tokens() {
        let handler = ClaudeHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test")).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Test".to_string()),
        );
        attributes.insert("max_tokens".to_string(), AttributeValue::Number(1024.0));

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        assert_eq!(data.get("max_tokens"), Some(&json!(1024)));
    }

    #[tokio::test]
    async fn test_with_system_prompt() {
        let handler = ClaudeHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "claude",
            vec![
                "--model",
                "claude-3-sonnet",
                "--max-tokens",
                "4096",
                "--temperature",
                "0.7",
                "--system",
                "You are a code reviewer",
                "Review this",
            ],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(60)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Review complete".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Review this".to_string()),
        );
        attributes.insert(
            "system".to_string(),
            AttributeValue::String("You are a code reviewer".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_with_context_files() {
        let handler = ClaudeHandler::new();
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("test.rs");
        tokio::fs::write(&file_path, "fn main() {}").await.unwrap();

        let context = ExecutionContext::new(temp_dir.path().to_path_buf()).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Review".to_string()),
        );
        attributes.insert(
            "context_files".to_string(),
            AttributeValue::Array(vec![AttributeValue::String("test.rs".to_string())]),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        let prompt = data.get("prompt").unwrap().as_str().unwrap();
        assert!(prompt.contains("test.rs"));
        assert!(prompt.contains("fn main() {}"));
    }

    #[tokio::test]
    async fn test_context_file_not_found() {
        let handler = ClaudeHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test"));

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Review".to_string()),
        );
        attributes.insert(
            "context_files".to_string(),
            AttributeValue::Array(vec![AttributeValue::String("nonexistent.rs".to_string())]),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert!(result
            .error
            .unwrap()
            .contains("Failed to read context file"));
    }

    #[tokio::test]
    async fn test_execution_failure() {
        let handler = ClaudeHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "claude",
            vec![
                "--model",
                "claude-3-sonnet",
                "--max-tokens",
                "4096",
                "--temperature",
                "0.7",
                "Test",
            ],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(60)),
            Output {
                status: std::process::ExitStatus::from_raw(1),
                stdout: Vec::new(),
                stderr: b"API error".to_vec(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Test".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert_eq!(result.error.unwrap(), "Claude CLI failed: API error");
    }

    #[tokio::test]
    async fn test_execution_timeout() {
        let handler = ClaudeHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test")).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Test".to_string()),
        );
        attributes.insert("timeout".to_string(), AttributeValue::Number(30.0));

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        // Timeout value is used in dry run output
        let data = result.data.unwrap();
        assert_eq!(data.get("dry_run"), Some(&json!(true)));
    }

    #[tokio::test]
    async fn test_with_multiple_context_files() {
        let handler = ClaudeHandler::new();
        let temp_dir = tempfile::tempdir().unwrap();

        let file1 = temp_dir.path().join("file1.rs");
        let file2 = temp_dir.path().join("file2.rs");
        tokio::fs::write(&file1, "// File 1").await.unwrap();
        tokio::fs::write(&file2, "// File 2").await.unwrap();

        let context = ExecutionContext::new(temp_dir.path().to_path_buf()).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Review".to_string()),
        );
        attributes.insert(
            "context_files".to_string(),
            AttributeValue::Array(vec![
                AttributeValue::String("file1.rs".to_string()),
                AttributeValue::String("file2.rs".to_string()),
            ]),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        let prompt = data.get("prompt").unwrap().as_str().unwrap();
        assert!(prompt.contains("file1.rs"));
        assert!(prompt.contains("// File 1"));
        assert!(prompt.contains("file2.rs"));
        assert!(prompt.contains("// File 2"));
    }

    #[tokio::test]
    async fn test_default_values() {
        let handler = ClaudeHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test")).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Test".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        assert_eq!(data.get("model"), Some(&json!("claude-3-sonnet")));
        assert_eq!(data.get("temperature"), Some(&json!(0.7)));
        assert_eq!(data.get("max_tokens"), Some(&json!(4096)));
    }

    #[tokio::test]
    async fn test_with_all_optional_parameters() {
        let handler = ClaudeHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test")).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "prompt".to_string(),
            AttributeValue::String("Test".to_string()),
        );
        attributes.insert(
            "model".to_string(),
            AttributeValue::String("claude-3-haiku".to_string()),
        );
        attributes.insert("temperature".to_string(), AttributeValue::Number(0.3));
        attributes.insert("max_tokens".to_string(), AttributeValue::Number(2048.0));
        attributes.insert(
            "system".to_string(),
            AttributeValue::String("System prompt".to_string()),
        );
        attributes.insert("timeout".to_string(), AttributeValue::Number(120.0));

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        assert_eq!(data.get("model"), Some(&json!("claude-3-haiku")));
        assert_eq!(data.get("temperature"), Some(&json!(0.3)));
        assert_eq!(data.get("max_tokens"), Some(&json!(2048)));
        assert_eq!(data.get("system"), Some(&json!("System prompt")));
    }
}