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
//! Pure functions for environment resolution
//!
//! This module provides pure, stateless functions for resolving working directories
//! and building command environments. All functions are side-effect free and fully
//! testable without mocks.
//!
//! # Functional Programming Principles
//!
//! - **Pure Functions**: All functions have no side effects
//! - **Referential Transparency**: Same inputs always produce same outputs
//! - **Explicit Inputs**: All data dependencies are function parameters
//! - **Testability**: No mocks needed - just test with concrete values
//!
//! # Why Pure Functions?
//!
//! Previous implementation used mutable `EnvironmentManager` with hidden state that
//! caused bugs in MapReduce workflows. These pure functions make all logic explicit
//! and eliminate hidden state mutations.

use super::context::ImmutableEnvironmentContext;
use crate::cook::orchestrator::ExecutionEnvironment;
use crate::cook::workflow::WorkflowStep;
use std::collections::HashMap;
use std::path::PathBuf;

/// Resolve working directory for a step (PURE FUNCTION)
///
/// Determines which directory to use for command execution based on:
/// 1. Explicit step.working_dir (highest priority)
/// 2. Environment context base directory (from worktree or repo)
///
/// # Arguments
///
/// * `step` - Workflow step (may specify explicit working_dir)
/// * `_env` - Execution environment (reserved for future use)
/// * `context` - Environment context (from builder)
///
/// # Returns
///
/// PathBuf representing the resolved working directory
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
/// use prodigy::cook::environment::pure::resolve_working_directory;
/// use prodigy::cook::environment::context::ImmutableEnvironmentContext;
/// use prodigy::cook::workflow::WorkflowStep;
/// use prodigy::cook::orchestrator::ExecutionEnvironment;
/// use std::sync::Arc;
///
/// let step = WorkflowStep {
///     working_dir: Some(PathBuf::from("/custom")),
///     ..Default::default()
/// };
/// let context = ImmutableEnvironmentContext::new(PathBuf::from("/base"));
/// let env = ExecutionEnvironment {
///     working_dir: Arc::new(PathBuf::from("/env")),
///     project_dir: Arc::new(PathBuf::from("/project")),
///     worktree_name: None,
///     session_id: Arc::from("test"),
/// };
///
/// let working_dir = resolve_working_directory(&step, &env, &context);
/// assert_eq!(working_dir, PathBuf::from("/custom"));
/// ```
///
/// # Why This Is Pure
///
/// - Takes all inputs as parameters
/// - Returns new value, doesn't mutate
/// - No I/O, no hidden state
/// - Same inputs → same output always
pub fn resolve_working_directory(
    step: &WorkflowStep,
    _env: &ExecutionEnvironment,
    context: &ImmutableEnvironmentContext,
) -> PathBuf {
    // 1. Explicit step working_dir takes highest precedence
    if let Some(ref dir) = step.working_dir {
        return dir.clone();
    }

    // 2. Use environment context base directory (set by caller)
    //    This allows MapReduce workflows to explicitly set worktree directory
    context.working_dir().to_path_buf()

    // Note: We intentionally do NOT fall back to env.working_dir here
    // because context.base_working_dir should always be correctly set
    // by the caller (either to repo dir or worktree dir)
}

/// Build complete environment variables for command execution (PURE FUNCTION)
///
/// Combines global environment config, step-specific env vars, and
/// workflow variables to produce the final environment for a command.
///
/// # Arguments
///
/// * `step` - Workflow step with step-specific env vars
/// * `context` - Environment context with base env vars
/// * `workflow_vars` - Variables from workflow context (for interpolation)
///
/// # Returns
///
/// HashMap of all environment variables for command
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use std::path::PathBuf;
/// use prodigy::cook::environment::pure::build_command_env;
/// use prodigy::cook::environment::context::ImmutableEnvironmentContext;
/// use prodigy::cook::workflow::WorkflowStep;
///
/// let step = WorkflowStep {
///     env: vec![("CUSTOM".to_string(), "value".to_string())]
///         .into_iter()
///         .collect(),
///     ..Default::default()
/// };
/// let context = ImmutableEnvironmentContext::new(PathBuf::from("/test"));
/// let workflow_vars = HashMap::new();
///
/// let env_vars = build_command_env(&step, &context, &workflow_vars);
/// assert_eq!(env_vars.get("CUSTOM"), Some(&"value".to_string()));
/// assert_eq!(env_vars.get("PRODIGY_AUTOMATION"), Some(&"true".to_string()));
/// ```
///
/// # Why This Is Pure
///
/// - All inputs passed as parameters
/// - Returns new HashMap, doesn't mutate
/// - No I/O or side effects
/// - Deterministic: same inputs → same output
pub fn build_command_env(
    step: &WorkflowStep,
    context: &ImmutableEnvironmentContext,
    workflow_vars: &HashMap<String, String>,
) -> HashMap<String, String> {
    // Start with context env vars (inherited from system + global config)
    let mut env = context.env_vars().clone();

    // Add step-specific environment variables with interpolation
    for (key, value) in &step.env {
        let interpolated = interpolate_value(value, workflow_vars);
        env.insert(key.clone(), interpolated);
    }

    // Add Prodigy-specific variables
    env.insert("PRODIGY_AUTOMATION".to_string(), "true".to_string());

    env
}

/// Inject positional arguments as ARG_N environment variables (PURE FUNCTION)
///
/// Converts positional arguments passed via `--args` into environment variables
/// named `ARG_1`, `ARG_2`, etc. This makes positional arguments available
/// consistently across all workflow phases (setup, map, reduce).
///
/// # Arguments
///
/// * `env_vars` - Mutable map to insert ARG_N variables into
/// * `args` - Slice of positional argument strings
///
/// # Returns
///
/// None (modifies env_vars in place)
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use prodigy::cook::environment::pure::inject_positional_args;
///
/// let mut env_vars = HashMap::new();
/// let args = vec!["file.txt".to_string(), "output.json".to_string()];
/// inject_positional_args(&mut env_vars, &args);
///
/// assert_eq!(env_vars.get("ARG_1"), Some(&"file.txt".to_string()));
/// assert_eq!(env_vars.get("ARG_2"), Some(&"output.json".to_string()));
/// ```
///
/// # Spec 163
///
/// This function implements automatic positional argument propagation as described
/// in Specification 163. Positional arguments are exported as `ARG_N` variables
/// to ensure consistency across all workflow phases, especially for MapReduce agents.
///
/// # Why This Is Pure
///
/// - Predictable transformation of input to environment variables
/// - No I/O or hidden state
/// - Deterministic: same args always produce same ARG_N variables
pub fn inject_positional_args(env_vars: &mut HashMap<String, String>, args: &[String]) {
    for (index, arg) in args.iter().enumerate() {
        let var_name = format!("ARG_{}", index + 1);
        env_vars.insert(var_name, arg.clone());
    }
}

/// Interpolate variables in a value (PURE FUNCTION)
///
/// Replaces ${var} and $var patterns with values from the variables map.
///
/// # Arguments
///
/// * `value` - String potentially containing variable references
/// * `variables` - Map of variable names to values
///
/// # Returns
///
/// String with all variables interpolated
///
/// # Examples
///
/// ```
/// use std::collections::HashMap;
/// use prodigy::cook::environment::pure::interpolate_value;
///
/// let mut vars = HashMap::new();
/// vars.insert("NAME".to_string(), "World".to_string());
/// vars.insert("COUNT".to_string(), "42".to_string());
///
/// assert_eq!(
///     interpolate_value("Hello ${NAME}!", &vars),
///     "Hello World!"
/// );
/// assert_eq!(
///     interpolate_value("Count: $COUNT", &vars),
///     "Count: 42"
/// );
/// ```
///
/// # Why This Is Pure
///
/// - Only string manipulation
/// - No I/O or mutation
/// - Deterministic output
pub fn interpolate_value(value: &str, variables: &HashMap<String, String>) -> String {
    let mut result = value.to_string();

    // Simple ${var} and $var interpolation
    for (key, val) in variables {
        result = result.replace(&format!("${{{}}}", key), val);
        result = result.replace(&format!("${}", key), val);
    }

    result
}

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

    fn create_test_env() -> ExecutionEnvironment {
        ExecutionEnvironment {
            working_dir: Arc::new(PathBuf::from("/env")),
            project_dir: Arc::new(PathBuf::from("/project")),
            worktree_name: None,
            session_id: Arc::from("test"),
        }
    }

    #[test]
    fn test_resolve_working_directory_explicit_step() {
        let step = WorkflowStep {
            working_dir: Some(PathBuf::from("/explicit")),
            ..Default::default()
        };
        let env = create_test_env();
        let context = ImmutableEnvironmentContext::new(PathBuf::from("/context"));

        let result = resolve_working_directory(&step, &env, &context);
        assert_eq!(result, PathBuf::from("/explicit"));
    }

    #[test]
    fn test_resolve_working_directory_from_context() {
        let step = WorkflowStep {
            working_dir: None,
            ..Default::default()
        };
        let env = create_test_env();
        let context = ImmutableEnvironmentContext::new(PathBuf::from("/worktree"));

        let result = resolve_working_directory(&step, &env, &context);
        assert_eq!(result, PathBuf::from("/worktree"));
    }

    #[test]
    fn test_resolve_working_directory_is_pure() {
        let step = WorkflowStep {
            working_dir: None,
            ..Default::default()
        };
        let env = create_test_env();
        let context = ImmutableEnvironmentContext::new(PathBuf::from("/test"));

        // Calling multiple times should always return same result
        let result1 = resolve_working_directory(&step, &env, &context);
        let result2 = resolve_working_directory(&step, &env, &context);
        let result3 = resolve_working_directory(&step, &env, &context);

        assert_eq!(result1, result2);
        assert_eq!(result2, result3);
    }

    #[test]
    fn test_build_command_env_step_vars() {
        let step = WorkflowStep {
            env: vec![("CUSTOM".to_string(), "value".to_string())]
                .into_iter()
                .collect(),
            ..Default::default()
        };
        let context = ImmutableEnvironmentContext::new(PathBuf::from("/test"));
        let workflow_vars = HashMap::new();

        let result = build_command_env(&step, &context, &workflow_vars);

        assert_eq!(result.get("CUSTOM"), Some(&"value".to_string()));
        assert_eq!(result.get("PRODIGY_AUTOMATION"), Some(&"true".to_string()));
    }

    #[test]
    fn test_build_command_env_interpolation() {
        let step = WorkflowStep {
            env: vec![("MESSAGE".to_string(), "Hello ${NAME}".to_string())]
                .into_iter()
                .collect(),
            ..Default::default()
        };
        let context = ImmutableEnvironmentContext::new(PathBuf::from("/test"));
        let mut workflow_vars = HashMap::new();
        workflow_vars.insert("NAME".to_string(), "World".to_string());

        let result = build_command_env(&step, &context, &workflow_vars);

        assert_eq!(result.get("MESSAGE"), Some(&"Hello World".to_string()));
    }

    #[test]
    fn test_build_command_env_inherits_context_vars() {
        let step = WorkflowStep {
            env: HashMap::new(),
            ..Default::default()
        };

        // Create context with some env vars
        let mut env_vars = HashMap::new();
        env_vars.insert("FROM_CONTEXT".to_string(), "context_value".to_string());

        let context = ImmutableEnvironmentContext {
            base_working_dir: Arc::new(PathBuf::from("/test")),
            env_vars: Arc::new(env_vars),
            secret_keys: Arc::new(Vec::new()),
            profile: None,
        };

        let workflow_vars = HashMap::new();
        let result = build_command_env(&step, &context, &workflow_vars);

        assert_eq!(
            result.get("FROM_CONTEXT"),
            Some(&"context_value".to_string())
        );
        assert_eq!(result.get("PRODIGY_AUTOMATION"), Some(&"true".to_string()));
    }

    #[test]
    fn test_interpolate_value_bracketed() {
        let mut variables = HashMap::new();
        variables.insert("VAR".to_string(), "value".to_string());

        let result = interpolate_value("prefix-${VAR}-suffix", &variables);
        assert_eq!(result, "prefix-value-suffix");
    }

    #[test]
    fn test_interpolate_value_simple() {
        let mut variables = HashMap::new();
        variables.insert("VAR".to_string(), "value".to_string());

        let result = interpolate_value("prefix-$VAR-suffix", &variables);
        assert_eq!(result, "prefix-value-suffix");
    }

    #[test]
    fn test_interpolate_value_multiple() {
        let mut variables = HashMap::new();
        variables.insert("A".to_string(), "1".to_string());
        variables.insert("B".to_string(), "2".to_string());

        let result = interpolate_value("${A} and ${B} and $A and $B", &variables);
        assert_eq!(result, "1 and 2 and 1 and 2");
    }

    #[test]
    fn test_interpolate_value_no_variables() {
        let variables = HashMap::new();
        let result = interpolate_value("no variables here", &variables);
        assert_eq!(result, "no variables here");
    }

    #[test]
    fn test_interpolate_value_missing_variable() {
        let variables = HashMap::new();
        let result = interpolate_value("missing ${VAR} here", &variables);
        // Missing variables are left as-is
        assert_eq!(result, "missing ${VAR} here");
    }

    #[test]
    fn test_build_command_env_is_pure() {
        let step = WorkflowStep {
            env: vec![("KEY".to_string(), "value".to_string())]
                .into_iter()
                .collect(),
            ..Default::default()
        };
        let context = ImmutableEnvironmentContext::new(PathBuf::from("/test"));
        let workflow_vars = HashMap::new();

        // Calling multiple times should produce identical results
        let result1 = build_command_env(&step, &context, &workflow_vars);
        let result2 = build_command_env(&step, &context, &workflow_vars);

        assert_eq!(result1, result2);
    }

    #[test]
    fn test_inject_positional_args() {
        let mut env = HashMap::new();
        let args = vec!["file.txt".to_string(), "output.json".to_string()];
        inject_positional_args(&mut env, &args);

        assert_eq!(env.get("ARG_1"), Some(&"file.txt".to_string()));
        assert_eq!(env.get("ARG_2"), Some(&"output.json".to_string()));
    }

    #[test]
    fn test_inject_positional_args_empty() {
        let mut env = HashMap::new();
        let args: Vec<String> = vec![];
        inject_positional_args(&mut env, &args);

        assert!(env.is_empty());
    }

    #[test]
    fn test_inject_positional_args_with_special_chars() {
        let mut env = HashMap::new();
        let args = vec!["path/with spaces/file.md".to_string()];
        inject_positional_args(&mut env, &args);

        assert_eq!(
            env.get("ARG_1"),
            Some(&"path/with spaces/file.md".to_string())
        );
    }

    #[test]
    fn test_inject_positional_args_preserves_existing() {
        let mut env = HashMap::new();
        env.insert("EXISTING".to_string(), "value".to_string());

        let args = vec!["arg1".to_string()];
        inject_positional_args(&mut env, &args);

        assert_eq!(env.get("EXISTING"), Some(&"value".to_string()));
        assert_eq!(env.get("ARG_1"), Some(&"arg1".to_string()));
    }

    #[test]
    fn test_inject_positional_args_is_pure() {
        let args = vec!["test".to_string()];

        // Multiple calls should produce same result
        let mut env1 = HashMap::new();
        inject_positional_args(&mut env1, &args);

        let mut env2 = HashMap::new();
        inject_positional_args(&mut env2, &args);

        assert_eq!(env1, env2);
    }
}