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
//! Pure utility functions for MapReduce operations
//!
//! This module contains pure functions extracted from the main MapReduce executor
//! to improve testability, maintainability, and functional programming practices.

use crate::cook::execution::interpolation::InterpolationContext;
use crate::cook::execution::mapreduce::{AgentResult, AgentStatus};
use serde_json::json;
use std::collections::HashMap;

/// Summary statistics for map results
#[derive(Debug, Clone, PartialEq)]
pub struct MapResultSummary {
    pub successful: usize,
    pub failed: usize,
    pub total: usize,
}

/// Agent status enumeration for classification
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AgentEventType {
    Completed,
    Failed,
    TimedOut,
    Retrying,
    InProgress,
}

// ============================================================================
// Result Aggregation Functions
// ============================================================================

/// Calculate summary statistics from map results (pure function)
///
/// # Arguments
/// * `map_results` - Collection of agent results to summarize
///
/// # Returns
/// Summary containing counts of successful, failed, and total agents
pub fn calculate_map_result_summary(map_results: &[AgentResult]) -> MapResultSummary {
    let successful = map_results
        .iter()
        .filter(|r| matches!(r.status, AgentStatus::Success))
        .count();

    let failed = map_results
        .iter()
        .filter(|r| matches!(r.status, AgentStatus::Failed(_) | AgentStatus::Timeout))
        .count();

    MapResultSummary {
        successful,
        failed,
        total: map_results.len(),
    }
}

/// Build InterpolationContext with map results (pure function)
///
/// # Arguments
/// * `map_results` - Collection of agent results
/// * `summary` - Pre-calculated summary statistics
///
/// # Returns
/// InterpolationContext populated with map results and statistics
pub fn build_map_results_interpolation_context(
    map_results: &[AgentResult],
    summary: &MapResultSummary,
) -> Result<InterpolationContext, serde_json::Error> {
    let mut context = InterpolationContext::new();

    // Add summary statistics
    context.set(
        "map",
        json!({
            "successful": summary.successful,
            "failed": summary.failed,
            "total": summary.total
        }),
    );

    // Add complete results as JSON value
    let results_value = serde_json::to_value(map_results)?;
    context.set("map.results", results_value);

    // Add individual result access
    for (index, result) in map_results.iter().enumerate() {
        let result_value = serde_json::to_value(result)?;
        context.set(format!("results[{}]", index), result_value);
    }

    Ok(context)
}

// ============================================================================
// Variable Transformation Functions
// ============================================================================

/// Build AgentContext variables for shell commands (pure function)
///
/// # Arguments
/// * `map_results` - Collection of agent results
/// * `summary` - Pre-calculated summary statistics
///
/// # Returns
/// HashMap of variable names to string values for shell command substitution
pub fn build_agent_context_variables(
    map_results: &[AgentResult],
    summary: &MapResultSummary,
) -> Result<HashMap<String, String>, serde_json::Error> {
    let mut variables = HashMap::new();

    // Add summary statistics as strings for shell command substitution
    variables.insert("map.successful".to_string(), summary.successful.to_string());
    variables.insert("map.failed".to_string(), summary.failed.to_string());
    variables.insert("map.total".to_string(), summary.total.to_string());

    // Add complete results as JSON string for complex access patterns
    let results_json = serde_json::to_string(map_results)?;
    variables.insert("map.results_json".to_string(), results_json.clone());
    variables.insert("map.results".to_string(), results_json);

    // Add individual result summaries for easier access in shell commands
    for (index, result) in map_results.iter().enumerate() {
        add_individual_result_variables(&mut variables, index, result);
    }

    Ok(variables)
}

/// Add variables for a single agent result (pure function)
///
/// # Arguments
/// * `variables` - HashMap to populate with result variables
/// * `index` - Index of the result in the collection
/// * `result` - Individual agent result to process
pub fn add_individual_result_variables(
    variables: &mut HashMap<String, String>,
    index: usize,
    result: &AgentResult,
) {
    // Add basic result info
    variables.insert(format!("result.{}.item_id", index), result.item_id.clone());

    let status_string = match &result.status {
        AgentStatus::Success => "success".to_string(),
        AgentStatus::Failed(err) => format!("failed: {}", err),
        AgentStatus::Timeout => "timeout".to_string(),
        AgentStatus::Pending => "pending".to_string(),
        AgentStatus::Running => "running".to_string(),
        AgentStatus::Retrying(attempt) => format!("retrying: {}", attempt),
    };
    variables.insert(format!("result.{}.status", index), status_string);

    // Add output if available (truncated for safety)
    if let Some(ref output) = result.output {
        let truncated_output = truncate_output(output, 500);
        variables.insert(format!("result.{}.output", index), truncated_output);
    }

    // Add commit count
    variables.insert(
        format!("result.{}.commits", index),
        result.commits.len().to_string(),
    );
}

// ============================================================================
// ID Generation Functions
// ============================================================================

/// Generate agent ID from index and item ID (pure function)
///
/// # Arguments
/// * `agent_index` - Numeric index of the agent
/// * `item_id` - Unique identifier for the work item
///
/// # Returns
/// Formatted agent ID string
pub fn generate_agent_id(agent_index: usize, item_id: &str) -> String {
    format!("agent-{}-{}", agent_index, item_id)
}

/// Generate branch name for an agent (pure function)
///
/// # Arguments
/// * `session_id` - Session identifier for the MapReduce job
/// * `item_id` - Unique identifier for the work item
///
/// # Returns
/// Formatted git branch name
pub fn generate_agent_branch_name(session_id: &str, item_id: &str) -> String {
    format!("prodigy-agent-{}-{}", session_id, item_id)
}

// ============================================================================
// Error Classification Functions
// ============================================================================

/// Classify agent status for event logging (pure function)
///
/// # Arguments
/// * `status` - Agent status to classify
///
/// # Returns
/// Corresponding event type for the status
pub fn classify_agent_status(status: &AgentStatus) -> AgentEventType {
    match status {
        AgentStatus::Success => AgentEventType::Completed,
        AgentStatus::Failed(_) => AgentEventType::Failed,
        AgentStatus::Timeout => AgentEventType::TimedOut,
        AgentStatus::Retrying(_) => AgentEventType::Retrying,
        _ => AgentEventType::InProgress,
    }
}

// ============================================================================
// Text Processing Functions
// ============================================================================

/// Truncate output to safe length (pure function)
///
/// # Arguments
/// * `output` - Text to potentially truncate
/// * `max_length` - Maximum allowed length
///
/// # Returns
/// Truncated string with indicator if truncation occurred
pub fn truncate_output(output: &str, max_length: usize) -> String {
    if output.len() > max_length {
        format!("{}...[truncated]", &output[..max_length])
    } else {
        output.to_string()
    }
}

/// Truncate command for display (pure function)
///
/// # Arguments
/// * `cmd` - Command string to truncate
/// * `max_len` - Maximum display length
///
/// # Returns
/// Truncated command suitable for display
pub fn truncate_command(cmd: &str, max_len: usize) -> String {
    if cmd.len() <= max_len {
        cmd.to_string()
    } else {
        format!("{}...", &cmd[..max_len - 3])
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    /// Helper function to create test AgentResult
    fn create_test_agent_result(
        item_id: &str,
        status: AgentStatus,
        output: Option<String>,
        commits: Vec<String>,
    ) -> AgentResult {
        AgentResult {
            item_id: item_id.to_string(),
            status,
            output,
            commits,
            duration: Duration::from_secs(1),
            error: None,
            worktree_path: None,
            branch_name: None,
            worktree_session_id: None,
            files_modified: vec![],
            json_log_location: None,
            cleanup_status: None,
        }
    }

    #[test]
    fn test_calculate_map_result_summary_mixed_results() {
        let map_results = vec![
            create_test_agent_result(
                "item1",
                AgentStatus::Success,
                Some("success output".to_string()),
                vec!["commit1".to_string()],
            ),
            create_test_agent_result(
                "item2",
                AgentStatus::Failed("error".to_string()),
                Some("error output".to_string()),
                vec![],
            ),
            create_test_agent_result(
                "item3",
                AgentStatus::Success,
                Some("success output 2".to_string()),
                vec!["commit2".to_string(), "commit3".to_string()],
            ),
        ];

        let summary = calculate_map_result_summary(&map_results);

        assert_eq!(summary.successful, 2);
        assert_eq!(summary.failed, 1);
        assert_eq!(summary.total, 3);
    }

    #[test]
    fn test_calculate_map_result_summary_all_successful() {
        let map_results = vec![
            create_test_agent_result(
                "item1",
                AgentStatus::Success,
                Some("success".to_string()),
                vec!["commit1".to_string()],
            ),
            create_test_agent_result(
                "item2",
                AgentStatus::Success,
                Some("success".to_string()),
                vec!["commit2".to_string()],
            ),
        ];

        let summary = calculate_map_result_summary(&map_results);

        assert_eq!(summary.successful, 2);
        assert_eq!(summary.failed, 0);
        assert_eq!(summary.total, 2);
    }

    #[test]
    fn test_calculate_map_result_summary_all_failed() {
        let map_results = vec![
            create_test_agent_result(
                "item1",
                AgentStatus::Failed("error1".to_string()),
                None,
                vec![],
            ),
            create_test_agent_result("item2", AgentStatus::Timeout, None, vec![]),
        ];

        let summary = calculate_map_result_summary(&map_results);

        assert_eq!(summary.successful, 0);
        assert_eq!(summary.failed, 2);
        assert_eq!(summary.total, 2);
    }

    #[test]
    fn test_calculate_map_result_summary_empty() {
        let map_results: Vec<AgentResult> = vec![];
        let summary = calculate_map_result_summary(&map_results);

        assert_eq!(summary.successful, 0);
        assert_eq!(summary.failed, 0);
        assert_eq!(summary.total, 0);
    }

    #[test]
    fn test_generate_agent_id() {
        assert_eq!(generate_agent_id(0, "abc-123"), "agent-0-abc-123");
        assert_eq!(generate_agent_id(42, "item"), "agent-42-item");
    }

    #[test]
    fn test_generate_agent_branch_name() {
        assert_eq!(
            generate_agent_branch_name("session-123", "abc"),
            "prodigy-agent-session-123-abc"
        );
    }

    #[test]
    fn test_classify_agent_status() {
        assert_eq!(
            classify_agent_status(&AgentStatus::Success),
            AgentEventType::Completed
        );
        assert_eq!(
            classify_agent_status(&AgentStatus::Failed("error".to_string())),
            AgentEventType::Failed
        );
        assert_eq!(
            classify_agent_status(&AgentStatus::Timeout),
            AgentEventType::TimedOut
        );
        assert_eq!(
            classify_agent_status(&AgentStatus::Retrying(1)),
            AgentEventType::Retrying
        );
        assert_eq!(
            classify_agent_status(&AgentStatus::Pending),
            AgentEventType::InProgress
        );
        assert_eq!(
            classify_agent_status(&AgentStatus::Running),
            AgentEventType::InProgress
        );
    }

    #[test]
    fn test_truncate_output() {
        assert_eq!(truncate_output("short", 10), "short");
        assert_eq!(
            truncate_output("this is a very long output", 10),
            "this is a ...[truncated]"
        );
    }

    #[test]
    fn test_truncate_command() {
        assert_eq!(truncate_command("ls", 10), "ls");
        assert_eq!(
            truncate_command("very long command with many arguments", 15),
            "very long co..."
        );
    }

    #[test]
    fn test_build_agent_context_variables() {
        let map_results = vec![
            create_test_agent_result(
                "item1",
                AgentStatus::Success,
                Some("output1".to_string()),
                vec!["commit1".to_string()],
            ),
            create_test_agent_result(
                "item2",
                AgentStatus::Failed("error".to_string()),
                None,
                vec![],
            ),
        ];

        let summary = calculate_map_result_summary(&map_results);
        let variables = build_agent_context_variables(&map_results, &summary).unwrap();

        assert_eq!(variables.get("map.successful").unwrap(), "1");
        assert_eq!(variables.get("map.failed").unwrap(), "1");
        assert_eq!(variables.get("map.total").unwrap(), "2");
        assert_eq!(variables.get("result.0.item_id").unwrap(), "item1");
        assert_eq!(variables.get("result.0.status").unwrap(), "success");
        assert_eq!(variables.get("result.0.output").unwrap(), "output1");
        assert_eq!(variables.get("result.1.item_id").unwrap(), "item2");
        assert_eq!(variables.get("result.1.status").unwrap(), "failed: error");
        assert_eq!(variables.get("result.0.commits").unwrap(), "1");
        assert_eq!(variables.get("result.1.commits").unwrap(), "0");
    }

    #[test]
    fn test_add_individual_result_variables() {
        let mut variables = HashMap::new();
        let result = create_test_agent_result(
            "test-item",
            AgentStatus::Success,
            Some("test output".to_string()),
            vec!["commit1".to_string(), "commit2".to_string()],
        );

        add_individual_result_variables(&mut variables, 0, &result);

        assert_eq!(variables.get("result.0.item_id").unwrap(), "test-item");
        assert_eq!(variables.get("result.0.status").unwrap(), "success");
        assert_eq!(variables.get("result.0.output").unwrap(), "test output");
        assert_eq!(variables.get("result.0.commits").unwrap(), "2");
    }

    #[test]
    fn test_build_map_results_interpolation_context() {
        let map_results = vec![create_test_agent_result(
            "item1",
            AgentStatus::Success,
            Some("output".to_string()),
            vec![],
        )];

        let summary = calculate_map_result_summary(&map_results);
        let context = build_map_results_interpolation_context(&map_results, &summary).unwrap();

        // Test summary in context
        let map_value = context.variables.get("map").unwrap();
        assert_eq!(map_value.get("successful").unwrap(), 1);
        assert_eq!(map_value.get("failed").unwrap(), 0);
        assert_eq!(map_value.get("total").unwrap(), 1);

        // Test results array
        let results_value = context.variables.get("map.results").unwrap();
        assert!(results_value.is_array());
        assert_eq!(results_value.as_array().unwrap().len(), 1);
    }
}