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
//! Git operations abstraction layer
//!
//! Provides trait-based abstraction for git commands to enable
//! testing without actual git repository access.

use crate::subprocess::{ProcessCommandBuilder, SubprocessManager};
use anyhow::Result;
use async_trait::async_trait;
use std::path::Path;
use std::sync::Arc;
use tokio::sync::Mutex;

/// Trait for git operations
#[async_trait]
pub trait GitOperations: Send + Sync {
    /// Execute a git command with exclusive access
    async fn git_command(&self, args: &[&str], description: &str) -> Result<std::process::Output>;

    /// Execute a git command with exclusive access in a specific directory
    async fn git_command_in_dir(
        &self,
        args: &[&str],
        description: &str,
        working_dir: &Path,
    ) -> Result<std::process::Output>;

    /// Get the last commit message
    async fn get_last_commit_message(&self) -> Result<String>;

    /// Check git status
    async fn check_git_status(&self) -> Result<String>;

    /// Stage all changes
    async fn stage_all_changes(&self) -> Result<()>;

    /// Create a commit
    async fn create_commit(&self, message: &str) -> Result<()>;

    /// Check if we're in a git repository
    async fn is_git_repo(&self) -> bool;

    /// Create a worktree
    async fn create_worktree(&self, name: &str, path: &Path) -> Result<()>;

    /// Get current branch name
    async fn get_current_branch(&self) -> Result<String>;

    /// Switch to a branch
    async fn switch_branch(&self, branch: &str) -> Result<()>;
}

/// Real implementation of `GitOperations`
pub struct RealGitOperations {
    /// Mutex for thread-safe git operations
    git_mutex: Arc<Mutex<()>>,
    /// Subprocess manager for executing git commands
    subprocess: SubprocessManager,
}

impl RealGitOperations {
    /// Create a new `RealGitOperations` instance
    #[must_use]
    pub fn new() -> Self {
        Self {
            git_mutex: Arc::new(Mutex::new(())),
            subprocess: SubprocessManager::production(),
        }
    }

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

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

#[async_trait]
impl GitOperations for RealGitOperations {
    async fn git_command(&self, args: &[&str], description: &str) -> Result<std::process::Output> {
        // Acquire the mutex to ensure exclusive access
        let _guard = self.git_mutex.lock().await;

        let command = ProcessCommandBuilder::new("git").args(args).build();

        let output = self
            .subprocess
            .runner()
            .run(command)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to execute git {}: {}", description, e))?;

        if !output.status.success() {
            let stderr = &output.stderr;
            return Err(anyhow::anyhow!(
                "Git {} failed: {}",
                description,
                stderr.trim()
            ));
        }

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

    async fn get_last_commit_message(&self) -> Result<String> {
        let output = self
            .git_command(&["log", "-1", "--pretty=format:%s"], "log")
            .await?;
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    async fn check_git_status(&self) -> Result<String> {
        let output = self
            .git_command(&["status", "--porcelain"], "status")
            .await?;
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    async fn stage_all_changes(&self) -> Result<()> {
        self.git_command(&["add", "."], "add").await?;
        Ok(())
    }

    async fn create_commit(&self, message: &str) -> Result<()> {
        self.git_command(&["commit", "-m", message], "commit")
            .await?;
        Ok(())
    }

    async fn is_git_repo(&self) -> bool {
        #[cfg(test)]
        let command = ProcessCommandBuilder::new("git")
            .args(["rev-parse", "--git-dir"])
            .suppress_stderr()
            .build();

        #[cfg(not(test))]
        let command = ProcessCommandBuilder::new("git")
            .args(["rev-parse", "--git-dir"])
            .build();

        self.subprocess
            .runner()
            .run(command)
            .await
            .map(|output| output.status.success())
            .unwrap_or(false)
    }

    async fn git_command_in_dir(
        &self,
        args: &[&str],
        description: &str,
        working_dir: &Path,
    ) -> Result<std::process::Output> {
        // Acquire the mutex to ensure exclusive access
        let _guard = self.git_mutex.lock().await;

        let command = ProcessCommandBuilder::new("git")
            .args(args)
            .current_dir(working_dir)
            .build();

        let output = self
            .subprocess
            .runner()
            .run(command)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to execute git {}: {}", description, e))?;

        if !output.status.success() {
            let stderr = &output.stderr;
            return Err(anyhow::anyhow!(
                "Git {} failed: {}",
                description,
                stderr.trim()
            ));
        }

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

    async fn create_worktree(&self, name: &str, path: &Path) -> Result<()> {
        let path_str = path
            .to_str()
            .ok_or_else(|| anyhow::anyhow!("Invalid path"))?;
        self.git_command(&["worktree", "add", path_str, "-b", name], "worktree add")
            .await?;
        Ok(())
    }

    async fn get_current_branch(&self) -> Result<String> {
        let output = self
            .git_command(&["rev-parse", "--abbrev-ref", "HEAD"], "get current branch")
            .await?;
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    async fn switch_branch(&self, branch: &str) -> Result<()> {
        self.git_command(&["checkout", branch], "checkout").await?;
        Ok(())
    }
}

/// Mock implementation of `GitOperations` for testing
pub struct MockGitOperations {
    /// Predefined responses for git commands
    pub command_responses: Arc<Mutex<Vec<Result<std::process::Output>>>>,
    /// Predefined response for `is_git_repo`
    pub is_repo: bool,
    /// Track called commands for verification
    pub called_commands: Arc<Mutex<Vec<Vec<String>>>>,
}

use crate::abstractions::exit_status::ExitStatusExt;

impl MockGitOperations {
    /// Create a new `MockGitOperations` instance
    #[must_use]
    pub fn new() -> Self {
        Self {
            command_responses: Arc::new(Mutex::new(Vec::new())),
            is_repo: true,
            called_commands: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// Add a response for the next git command
    pub async fn add_response(&self, response: Result<std::process::Output>) {
        self.command_responses.lock().await.push(response);
    }

    /// Add a successful response with stdout content
    pub async fn add_success_response(&self, stdout: &str) {
        let output = std::process::Output {
            status: std::process::ExitStatus::from_raw(0),
            stdout: stdout.as_bytes().to_vec(),
            stderr: Vec::new(),
        };
        self.add_response(Ok(output)).await;
    }

    /// Add an error response
    pub async fn add_error_response(&self, error: &str) {
        let error_string = error.to_string();
        self.add_response(Err(anyhow::anyhow!(error_string))).await;
    }

    /// Get the list of called commands
    pub async fn get_called_commands(&self) -> Vec<Vec<String>> {
        self.called_commands.lock().await.clone()
    }
}

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

#[async_trait]
impl GitOperations for MockGitOperations {
    async fn git_command(&self, args: &[&str], _description: &str) -> Result<std::process::Output> {
        // Track the called command
        let cmd_vec: Vec<String> = args.iter().map(|s| (*s).to_string()).collect();
        self.called_commands.lock().await.push(cmd_vec);

        // Return the next predefined response
        let mut responses = self.command_responses.lock().await;
        if responses.is_empty() {
            return Err(anyhow::anyhow!("No mock response configured"));
        }
        responses.remove(0)
    }

    async fn get_last_commit_message(&self) -> Result<String> {
        let output = self
            .git_command(&["log", "-1", "--pretty=format:%s"], "log")
            .await?;
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    async fn check_git_status(&self) -> Result<String> {
        let output = self
            .git_command(&["status", "--porcelain"], "status")
            .await?;
        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    async fn stage_all_changes(&self) -> Result<()> {
        self.git_command(&["add", "."], "add").await?;
        Ok(())
    }

    async fn create_commit(&self, message: &str) -> Result<()> {
        self.git_command(&["commit", "-m", message], "commit")
            .await?;
        Ok(())
    }

    async fn is_git_repo(&self) -> bool {
        self.is_repo
    }

    async fn create_worktree(&self, name: &str, path: &Path) -> Result<()> {
        let path_str = path
            .to_str()
            .ok_or_else(|| anyhow::anyhow!("Invalid path"))?;
        self.git_command(&["worktree", "add", path_str, "-b", name], "worktree add")
            .await?;
        Ok(())
    }

    async fn get_current_branch(&self) -> Result<String> {
        let output = self
            .git_command(&["rev-parse", "--abbrev-ref", "HEAD"], "get current branch")
            .await?;
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    async fn switch_branch(&self, branch: &str) -> Result<()> {
        self.git_command(&["checkout", branch], "checkout").await?;
        Ok(())
    }

    async fn git_command_in_dir(
        &self,
        args: &[&str],
        description: &str,
        _working_dir: &Path,
    ) -> Result<std::process::Output> {
        // For mocks, just delegate to git_command since we don't actually run commands
        self.git_command(args, description).await
    }
}

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

    #[tokio::test]
    async fn test_mock_git_operations() {
        let mock = MockGitOperations::new();

        // Add responses
        mock.add_success_response("test commit message").await;
        mock.add_success_response("M  src/main.rs\nA  src/new.rs")
            .await;

        // Test get_last_commit_message
        let msg = mock.get_last_commit_message().await.unwrap();
        assert_eq!(msg, "test commit message");

        // Test check_git_status
        let status = mock.check_git_status().await.unwrap();
        assert!(status.contains("M  src/main.rs"));

        // Verify called commands
        let commands = mock.get_called_commands().await;
        assert_eq!(commands.len(), 2);
        assert_eq!(commands[0], vec!["log", "-1", "--pretty=format:%s"]);
        assert_eq!(commands[1], vec!["status", "--porcelain"]);
    }

    #[tokio::test]
    async fn test_mock_git_error() {
        let mock = MockGitOperations::new();

        // Add error response
        mock.add_error_response("fatal: not a git repository").await;

        // Test error handling
        let result = mock.get_last_commit_message().await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("not a git repository"));
    }

    #[tokio::test]
    async fn test_real_git_operations_is_git_repo() {
        use crate::subprocess::builder::ProcessCommandBuilder;
        use crate::subprocess::SubprocessManager;
        use std::process::Command;
        use tempfile::TempDir;

        // Create a temporary directory with a git repo
        let temp_dir = TempDir::new().unwrap();

        // Initialize git repo
        let output = Command::new("git")
            .args(["init"])
            .current_dir(temp_dir.path())
            .output()
            .expect("Failed to run git init");

        assert!(output.status.success(), "Git init should succeed");

        // Create a subprocess manager that runs commands in the temp directory
        let subprocess = SubprocessManager::production();

        // Test if it's a git repo by running git rev-parse in that directory
        let command = ProcessCommandBuilder::new("git")
            .args(["rev-parse", "--git-dir"])
            .current_dir(temp_dir.path())
            .suppress_stderr()
            .build();

        let result = subprocess.runner().run(command).await;

        assert!(
            result.is_ok() && result.unwrap().status.success(),
            "Should detect git repository in {}",
            temp_dir.path().display()
        );
    }
}

#[cfg(test)]
mod real_git_tests {
    use super::*;
    use tempfile::TempDir;

    #[tokio::test]
    async fn test_git_command_success() {
        let git_ops = RealGitOperations::new();

        // Test successful command execution
        let result = git_ops.git_command(&["--version"], "version check").await;
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.status.success());
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(stdout.contains("git version"));
    }

    #[tokio::test]
    async fn test_git_command_failure() {
        let git_ops = RealGitOperations::new();

        // Test failed command execution
        let result = git_ops
            .git_command(&["invalid-command"], "invalid command")
            .await;
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("Git invalid command failed"));
    }

    #[tokio::test]
    async fn test_stage_all_changes_and_commit() {
        let git_ops = RealGitOperations::new();

        // Only run if in a git repo
        if !git_ops.is_git_repo().await {
            return;
        }

        // Create a test file in a temp directory
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.txt");
        std::fs::write(&test_file, "test content").unwrap();

        // Note: Full integration testing would require a test git repo
        // This is a partial test to verify the methods don't panic
        let _ = git_ops.check_git_status().await;
    }

    #[tokio::test]
    async fn test_get_current_branch() {
        let git_ops = RealGitOperations::new();

        // This test may run in environments where we're not in a git repo
        // (e.g., when tests change directories). Skip if not in a git repo.
        if !git_ops.is_git_repo().await {
            return;
        }

        let result = git_ops.get_current_branch().await;

        match result {
            Ok(branch) => {
                // Branch name should not be empty
                assert!(!branch.is_empty());
            }
            Err(e) => {
                let error_msg = e.to_string();
                // Accept errors that indicate we're not in a git repo
                // (can happen if test environment changes between is_git_repo check and this call)
                if error_msg.contains("not a git repository") {
                    return;
                }
                // Accept errors related to working directory issues
                if error_msg.contains("Unable to read current working directory") {
                    return;
                }
                // Also accept detached HEAD state
                assert!(
                    error_msg.contains("HEAD") || error_msg.contains("detached"),
                    "Unexpected error: {error_msg}"
                );
            }
        }
    }

    #[tokio::test]
    async fn test_create_worktree_invalid_path() {
        let git_ops = RealGitOperations::new();

        if git_ops.is_git_repo().await {
            let invalid_path = Path::new("/\0invalid");
            let result = git_ops.create_worktree("test-branch", invalid_path).await;
            assert!(result.is_err());
        }
    }
}