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
//! Cook orchestrator implementation
//!
//! Coordinates all cook operations using pure planning and effect composition.
//!
//! # Architecture
//!
//! The orchestrator follows the "pure core, imperative shell" pattern:
//! - Pure planning via `plan_execution()` from `core::orchestration`
//! - Effect composition via `effects` module
//! - I/O at the boundaries only
//!
//! The refactored orchestrator:
//! - Uses pure `ExecutionPlan` to drive all decisions
//! - Delegates to specialized executors (MapReduce, Standard, etc.)
//! - Keeps only I/O coordination logic (~400 LOC)

use crate::abstractions::git::GitOperations;
use crate::config::WorkflowConfig;
use crate::core::orchestration::{plan_execution, ExecutionMode, ExecutionPlan};
use crate::testing::config::TestConfiguration;
use crate::worktree::WorktreeManager;
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use std::path::PathBuf;
use std::sync::Arc;

use crate::cook::command::CookCommand;
use crate::cook::execution::{ClaudeExecutor, CommandExecutor};
use crate::cook::interaction::UserInteraction;
use crate::cook::session::SessionManager;
// Re-export WorkflowType from workflow_classifier for backwards compatibility
pub(crate) use super::workflow_classifier::WorkflowType;

/// Configuration for cook orchestration
#[derive(Debug, Clone)]
pub struct CookConfig {
    /// Command to execute
    pub command: CookCommand,
    /// Project path
    pub project_path: Arc<PathBuf>,
    /// Workflow configuration
    pub workflow: Arc<WorkflowConfig>,
    /// MapReduce configuration (if this is a MapReduce workflow)
    pub mapreduce_config: Option<Arc<crate::config::MapReduceWorkflowConfig>>,
}

/// Trait for orchestrating cook operations
#[async_trait]
pub trait CookOrchestrator: Send + Sync {
    /// Run the cook operation
    async fn run(&self, config: CookConfig) -> Result<()>;

    /// Check prerequisites
    async fn check_prerequisites(&self) -> Result<()>;

    /// Setup working environment
    async fn setup_environment(&self, config: &CookConfig) -> Result<ExecutionEnvironment>;

    /// Execute workflow
    async fn execute_workflow(&self, env: &ExecutionEnvironment, config: &CookConfig)
        -> Result<()>;

    /// Cleanup after execution
    async fn cleanup(&self, env: &ExecutionEnvironment, config: &CookConfig) -> Result<()>;
}

/// Execution environment for cook operations
#[derive(Debug)]
pub struct ExecutionEnvironment {
    /// Working directory (may be worktree)
    pub working_dir: Arc<PathBuf>,
    /// Original project directory
    pub project_dir: Arc<PathBuf>,
    /// Worktree name if using worktree
    pub worktree_name: Option<Arc<str>>,
    /// Session ID
    pub session_id: Arc<str>,
}

impl Clone for ExecutionEnvironment {
    fn clone(&self) -> Self {
        Self {
            working_dir: Arc::clone(&self.working_dir),
            project_dir: Arc::clone(&self.project_dir),
            worktree_name: self.worktree_name.as_ref().map(Arc::clone),
            session_id: Arc::clone(&self.session_id),
        }
    }
}

/// Default implementation of cook orchestrator
///
/// Uses pure planning from `core::orchestration` to drive execution decisions.
pub struct DefaultCookOrchestrator {
    session_manager: Arc<dyn SessionManager>,
    #[allow(dead_code)]
    command_executor: Arc<dyn CommandExecutor>,
    claude_executor: Arc<dyn ClaudeExecutor>,
    user_interaction: Arc<dyn UserInteraction>,
    #[allow(dead_code)]
    git_operations: Arc<dyn GitOperations>,
    subprocess: crate::subprocess::SubprocessManager,
    #[allow(dead_code)]
    test_config: Option<Arc<TestConfiguration>>,
    session_ops: super::session_ops::SessionOperations,
    #[allow(dead_code)]
    workflow_executor: super::workflow_execution::WorkflowExecutor,
    argument_processor: super::argument_processing::ArgumentProcessor,
    execution_pipeline: super::execution_pipeline::ExecutionPipeline,
}

impl DefaultCookOrchestrator {
    /// Create a new orchestrator with dependencies
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        session_manager: Arc<dyn SessionManager>,
        command_executor: Arc<dyn CommandExecutor>,
        claude_executor: Arc<dyn ClaudeExecutor>,
        user_interaction: Arc<dyn UserInteraction>,
        git_operations: Arc<dyn GitOperations>,
        subprocess: crate::subprocess::SubprocessManager,
    ) -> Self {
        Self::from_builder(
            session_manager,
            command_executor,
            claude_executor,
            user_interaction,
            git_operations,
            subprocess,
            None,
        )
    }

    /// Internal constructor used by the builder
    #[allow(clippy::too_many_arguments)]
    pub(super) fn from_builder(
        session_manager: Arc<dyn SessionManager>,
        command_executor: Arc<dyn CommandExecutor>,
        claude_executor: Arc<dyn ClaudeExecutor>,
        user_interaction: Arc<dyn UserInteraction>,
        git_operations: Arc<dyn GitOperations>,
        subprocess: crate::subprocess::SubprocessManager,
        test_config: Option<Arc<TestConfiguration>>,
    ) -> Self {
        let session_ops = super::session_ops::SessionOperations::new(
            Arc::clone(&session_manager),
            Arc::clone(&claude_executor),
            Arc::clone(&user_interaction),
            Arc::clone(&git_operations),
            subprocess.clone(),
        );

        let workflow_executor = super::workflow_execution::WorkflowExecutor::new(
            Arc::clone(&session_manager),
            Arc::clone(&claude_executor),
            Arc::clone(&user_interaction),
            subprocess.clone(),
        );

        let argument_processor = super::argument_processing::ArgumentProcessor::new(
            Arc::clone(&claude_executor),
            Arc::clone(&session_manager),
            Arc::clone(&user_interaction),
            test_config.clone(),
        );

        let execution_pipeline = super::execution_pipeline::ExecutionPipeline::new(
            Arc::clone(&session_manager),
            Arc::clone(&user_interaction),
            Arc::clone(&claude_executor),
            Arc::clone(&git_operations),
            subprocess.clone(),
            session_ops.clone(),
            workflow_executor.clone(),
        );

        Self {
            session_manager,
            command_executor,
            claude_executor,
            user_interaction,
            git_operations,
            subprocess,
            test_config,
            session_ops,
            workflow_executor,
            argument_processor,
            execution_pipeline,
        }
    }

    /// Create a new orchestrator with test configuration
    #[allow(clippy::too_many_arguments)]
    pub fn with_test_config(
        session_manager: Arc<dyn SessionManager>,
        command_executor: Arc<dyn CommandExecutor>,
        claude_executor: Arc<dyn ClaudeExecutor>,
        user_interaction: Arc<dyn UserInteraction>,
        git_operations: Arc<dyn GitOperations>,
        subprocess: crate::subprocess::SubprocessManager,
        test_config: Arc<TestConfiguration>,
    ) -> Self {
        Self::from_builder(
            session_manager,
            command_executor,
            claude_executor,
            user_interaction,
            git_operations,
            subprocess,
            Some(test_config),
        )
    }

    /// Create workflow executor - avoids repeated Arc cloning
    pub(super) fn create_workflow_executor_internal(
        &self,
        config: &CookConfig,
    ) -> crate::cook::workflow::WorkflowExecutorImpl {
        super::construction::create_workflow_executor(
            Arc::clone(&self.claude_executor),
            Arc::clone(&self.session_manager),
            Arc::clone(&self.user_interaction),
            config.command.playbook.clone(),
        )
    }

    /// Classify workflow type using pure function
    pub(crate) fn classify_workflow_type(config: &CookConfig) -> WorkflowType {
        super::workflow_classifier::classify_workflow_type(config)
    }

    // --- I/O Operations (Thin Layer) ---

    async fn create_worktree(
        &self,
        config: &CookConfig,
        session_id: &str,
    ) -> Result<(Arc<PathBuf>, Option<Arc<str>>)> {
        let manager = WorktreeManager::with_config(
            config.project_path.to_path_buf(),
            self.subprocess.clone(),
            config.command.verbosity,
            super::construction::extract_merge_config(&config.workflow, &config.mapreduce_config),
            super::construction::extract_workflow_env(&config.workflow),
        )?;
        let session = manager.create_session_with_id(session_id).await?;
        self.user_interaction
            .display_info(&format!("Created worktree at: {}", session.path.display()));
        Ok((
            Arc::new(session.path.clone()),
            Some(Arc::from(session.name.as_ref())),
        ))
    }

    async fn cleanup_worktree(
        &self,
        env: &ExecutionEnvironment,
        config: &CookConfig,
        worktree: &str,
    ) -> Result<()> {
        let test_mode = std::env::var("PRODIGY_TEST_MODE").unwrap_or_default() == "true";
        let merge_config =
            super::construction::extract_merge_config(&config.workflow, &config.mapreduce_config);
        let workflow_env = super::construction::extract_workflow_env(&config.workflow);

        let manager = WorktreeManager::with_config(
            env.project_dir.to_path_buf(),
            self.subprocess.clone(),
            config.command.verbosity,
            merge_config,
            workflow_env,
        )?;

        let should_merge =
            match super::construction::should_merge_worktree(test_mode, config.command.auto_accept)
            {
                Some(decision) => decision,
                None => {
                    let target = manager
                        .get_merge_target(worktree)
                        .await
                        .unwrap_or_else(|_| "master".to_string());
                    self.user_interaction
                        .prompt_yes_no(&format!("Merge {} to {}", worktree, target))
                        .await?
                }
            };

        if should_merge {
            manager.merge_session(worktree).await?;
            self.user_interaction
                .display_success("Worktree changes merged successfully!");
        }
        Ok(())
    }

    // --- Execution Dispatch (Uses Pure Plan) ---

    async fn execute_by_mode(
        &self,
        env: &ExecutionEnvironment,
        config: &CookConfig,
        plan: &ExecutionPlan,
    ) -> Result<()> {
        // DryRun mode with mapreduce_config should still go through MapReduce path
        let is_mapreduce = config.mapreduce_config.is_some();
        let effective_mode = if plan.mode == ExecutionMode::DryRun && is_mapreduce {
            ExecutionMode::MapReduce
        } else {
            plan.mode
        };

        match effective_mode {
            ExecutionMode::MapReduce => {
                let mr_config = config.mapreduce_config.as_ref().ok_or_else(|| {
                    anyhow!("MapReduce workflow requires mapreduce configuration")
                })?;
                self.execution_pipeline
                    .execute_mapreduce_workflow_with_executor(
                        env,
                        config,
                        mr_config,
                        self.create_workflow_executor_internal(config)
                            .with_dry_run(config.command.dry_run),
                    )
                    .await
            }
            ExecutionMode::Iterative => {
                self.user_interaction
                    .display_info("Processing workflow with arguments or file patterns");
                self.argument_processor
                    .execute_workflow_with_args(env, config)
                    .await
            }
            // DryRun uses standard workflow path with dry_run=true on executor
            ExecutionMode::DryRun | ExecutionMode::Standard => {
                self.execute_standard_workflow(env, config).await
            }
        }
    }

    async fn execute_standard_workflow(
        &self,
        env: &ExecutionEnvironment,
        config: &CookConfig,
    ) -> Result<()> {
        if Self::classify_workflow_type(config) == WorkflowType::StructuredWithOutputs {
            return self
                .execution_pipeline
                .execute_structured_workflow(env, config)
                .await;
        }

        let extended = super::workflow_execution::build_standard_workflow_config(
            &config.workflow.commands,
            config.command.max_iterations,
        );

        let checkpoint_mgr = Arc::new(crate::cook::workflow::CheckpointManager::with_storage(
            crate::cook::workflow::CheckpointStorage::Session {
                session_id: env.session_id.to_string(),
            },
        ));
        let mut executor = self
            .create_workflow_executor_internal(config)
            .with_checkpoint_manager(
                checkpoint_mgr,
                format!("workflow-{}", chrono::Utc::now().timestamp_millis()),
            )
            .with_dry_run(config.command.dry_run);

        // Add positional args support for standard/dry-run workflows
        if !config.command.args.is_empty() {
            // Use first arg as $ARG for backward compatibility
            executor = executor.with_positional_args(config.command.args.clone());
        }

        if super::workflow_execution::has_env_config(&config.workflow) {
            executor = executor.with_environment_config(super::construction::create_env_config(
                &config.workflow,
            ))?;
        }
        executor.execute(&extended, env).await
    }
}

#[async_trait]
impl CookOrchestrator for DefaultCookOrchestrator {
    async fn run(&self, config: CookConfig) -> Result<()> {
        // Handle resume
        if let Some(session_id) = config.command.resume.clone() {
            return self
                .execution_pipeline
                .resume_workflow(&session_id, config)
                .await;
        }

        // Pure planning - drives all decisions
        let plan = plan_execution(&config);
        log::debug!(
            "Execution plan: mode={:?}, phases={}",
            plan.mode,
            plan.phase_count()
        );

        // Check prerequisites
        self.session_ops
            .check_prerequisites_with_config(&config)
            .await?;

        // Setup environment (I/O)
        let env = self.setup_environment(&config).await?;

        // Initialize session metadata
        self.execution_pipeline
            .initialize_session_metadata(&env.session_id, &config)
            .await?;

        // Setup signal handlers
        let interrupt_handler = self.execution_pipeline.setup_signal_handlers(
            &config,
            &env.session_id,
            env.worktree_name.as_ref().map(Arc::clone),
        )?;

        // Execute by mode (determined by pure plan)
        let execution_result = self.execute_by_mode(&env, &config, &plan).await;

        interrupt_handler.abort();

        // Update session status
        self.session_ops
            .update_unified_session_status(&env.session_id, execution_result.is_ok())
            .await;

        // Finalize
        self.execution_pipeline
            .finalize_session(&env, &config, execution_result, self.cleanup(&env, &config))
            .await
    }

    async fn check_prerequisites(&self) -> Result<()> {
        self.session_ops.check_prerequisites().await
    }

    async fn setup_environment(&self, config: &CookConfig) -> Result<ExecutionEnvironment> {
        let mut session_id = Arc::from(self.session_ops.generate_session_id().as_str());

        if super::construction::should_create_unified_session(
            config.mapreduce_config.is_some(),
            config.command.dry_run,
        ) {
            session_id = Arc::from(
                self.session_ops
                    .create_unified_session(config)
                    .await?
                    .as_str(),
            );
        }

        let (working_dir, worktree_name) = if !config.command.dry_run {
            self.create_worktree(config, &session_id).await?
        } else {
            self.user_interaction
                .display_info("[DRY RUN] Would create worktree for isolated execution");
            (Arc::clone(&config.project_path), None)
        };

        Ok(ExecutionEnvironment {
            working_dir,
            project_dir: Arc::clone(&config.project_path),
            worktree_name,
            session_id,
        })
    }

    async fn execute_workflow(
        &self,
        env: &ExecutionEnvironment,
        config: &CookConfig,
    ) -> Result<()> {
        // Use pure planning to determine mode
        let plan = plan_execution(config);
        self.execute_by_mode(env, config, &plan).await
    }

    async fn cleanup(&self, env: &ExecutionEnvironment, config: &CookConfig) -> Result<()> {
        let session_state_path = env.working_dir.join(".prodigy/session_state.json");
        self.session_manager.save_state(&session_state_path).await?;

        if let Some(ref worktree_name) = env.worktree_name {
            self.cleanup_worktree(env, config, worktree_name).await?;
        }
        Ok(())
    }
}