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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! Git operations for MapReduce agents

use crate::cook::execution::errors::{MapReduceError, MapReduceResult};
use crate::cook::orchestrator::ExecutionEnvironment;
use std::path::Path;
use tokio::process::Command;
use tracing::{info, warn};

use super::git_operations::{GitOperationsConfig, GitOperationsService, GitResultExt};

/// Handles git operations for MapReduce agents
pub struct GitOperations {
    service: GitOperationsService,
}

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

impl GitOperations {
    /// Create a new git operations handler
    pub fn new() -> Self {
        Self {
            service: GitOperationsService::new(GitOperationsConfig::default()),
        }
    }

    /// Create a branch for an agent in its worktree
    pub async fn create_agent_branch(
        &self,
        worktree_path: &Path,
        branch_name: &str,
    ) -> MapReduceResult<()> {
        // Create branch from current HEAD
        let output = Command::new("git")
            .args(["checkout", "-b", branch_name])
            .current_dir(worktree_path)
            .output()
            .await
            .map_err(|e| self.create_git_error("create_branch", &e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(self.create_git_error("create_branch", &stderr));
        }

        info!(
            "Created branch {} in worktree at {}",
            branch_name,
            worktree_path.display()
        );
        Ok(())
    }

    /// Validate that we're in a worktree context
    ///
    /// Pure function that checks if the execution environment has a worktree name.
    /// Returns the working directory path if valid, error message otherwise.
    fn validate_worktree_context(
        env: &ExecutionEnvironment,
    ) -> Result<&std::sync::Arc<std::path::PathBuf>, &'static str> {
        if env.worktree_name.is_some() {
            Ok(&env.working_dir)
        } else {
            Err("Cannot merge: not running in a worktree context")
        }
    }

    /// Check if there's an incomplete merge in progress
    ///
    /// Pure function that checks for the existence of .git/MERGE_HEAD file.
    /// Returns true if an incomplete merge exists.
    fn has_incomplete_merge(parent_path: &Path) -> bool {
        parent_path.join(".git/MERGE_HEAD").exists()
    }

    /// Determine action based on git status output
    ///
    /// Pure function that parses git status --porcelain output
    /// to decide whether to commit staged changes or abort.
    fn should_commit_staged_changes(status_output: &str) -> bool {
        !status_output.trim().is_empty()
    }

    /// Check git status in a repository
    ///
    /// Runs `git status --porcelain` and returns the output.
    async fn check_git_status(&self, repo_path: &Path) -> MapReduceResult<String> {
        let output = Command::new("git")
            .args(["status", "--porcelain"])
            .current_dir(repo_path)
            .output()
            .await
            .map_err(|e| self.create_git_error("git_status", &e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(self.create_git_error("git_status", &stderr));
        }

        Ok(String::from_utf8_lossy(&output.stdout).to_string())
    }

    /// Commit staged changes without prompting for a message
    ///
    /// Uses --no-edit to commit with the existing merge message.
    async fn commit_staged_changes(&self, repo_path: &Path) -> MapReduceResult<()> {
        let output = Command::new("git")
            .args(["commit", "--no-edit"])
            .current_dir(repo_path)
            .output()
            .await
            .map_err(|e| self.create_git_error("git_commit", &e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(self.create_git_error("git_commit", &stderr));
        }

        Ok(())
    }

    /// Abort an in-progress merge
    ///
    /// Best-effort operation that ignores errors.
    async fn abort_merge(&self, repo_path: &Path) {
        let _ = Command::new("git")
            .args(["merge", "--abort"])
            .current_dir(repo_path)
            .output()
            .await;
    }

    /// Recover from an incomplete merge
    ///
    /// Handles the merge recovery logic by either committing staged changes
    /// or aborting the incomplete merge.
    async fn recover_incomplete_merge(
        &self,
        parent_path: &Path,
        agent_branch: &str,
    ) -> MapReduceResult<()> {
        warn!(
            "Detected incomplete merge state (MERGE_HEAD exists), cleaning up before merging {}",
            agent_branch
        );

        // Get git status to decide action
        let status = self.check_git_status(parent_path).await?;

        // Decide action based on status (pure function)
        if Self::should_commit_staged_changes(&status) {
            warn!("Committing staged changes from incomplete merge");

            // Try to commit, abort on failure
            if self.commit_staged_changes(parent_path).await.is_err() {
                warn!("Failed to commit staged changes, aborting merge");
                self.abort_merge(parent_path).await;
            }
        } else {
            // No staged changes, just abort
            warn!("No staged changes, aborting incomplete merge");
            self.abort_merge(parent_path).await;
        }

        Ok(())
    }

    /// Execute a git merge
    ///
    /// Performs the actual merge with --no-ff to always create a merge commit.
    /// If the merge fails for ANY reason, triggers Claude-assisted merge as a fallback.
    /// This ensures bulletproof merge handling even in complex conflict scenarios.
    async fn execute_merge(&self, parent_path: &Path, agent_branch: &str) -> MapReduceResult<()> {
        let output = Command::new("git")
            .args([
                "merge",
                "--no-ff",
                "-m",
                &format!("Merge agent {}", agent_branch),
                agent_branch,
            ])
            .current_dir(parent_path)
            .output()
            .await
            .map_err(|e| self.create_git_error("merge_agent_branch", &e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);

            // ANY merge failure should trigger Claude-assisted merge as fallback
            // This handles: conflicts, unmerged paths, partial merges, and any edge cases
            warn!(
                "Git merge failed for {}, triggering Claude-assisted merge fallback",
                agent_branch
            );

            // Abort the failed merge to leave worktree in clean state
            self.abort_merge(parent_path).await;

            // Return the magic error string that triggers Claude-assisted merge in merge queue
            return Err(MapReduceError::General {
                message: format!(
                    "Git merge failed for agent branch '{}'. Claude-assisted merge required. Original error: {}",
                    agent_branch, stderr.trim()
                ),
                source: None,
            });
        }

        Ok(())
    }

    /// Check if working directory has uncommitted changes (excluding worktree directories)
    ///
    /// This indicates the working directory is dirty and needs cleanup before merge.
    /// We ignore untracked worktree directories (??  path/) since they're managed by git.
    async fn has_uncommitted_changes(&self, repo_path: &Path) -> MapReduceResult<bool> {
        let status = self.check_git_status(repo_path).await?;

        // Filter out worktree directories from status
        // Format: "?? worktree-name/"
        let meaningful_changes = status
            .lines()
            .filter(|line| {
                // Keep all staged/modified/deleted files
                // Skip untracked directories (potential worktrees)
                if let Some(rest) = line.strip_prefix("?? ") {
                    // If it ends with "/" it's an untracked directory - might be a worktree
                    !rest.trim().ends_with('/')
                } else {
                    // Keep all tracked changes (M , A , D , etc.)
                    true
                }
            })
            .collect::<Vec<_>>();

        Ok(!meaningful_changes.is_empty())
    }

    /// Merge an agent's branch back to the parent
    pub async fn merge_agent_to_parent(
        &self,
        agent_branch: &str,
        env: &ExecutionEnvironment,
    ) -> MapReduceResult<()> {
        // Validate worktree context (pure function)
        let parent_path = Self::validate_worktree_context(env)
            .map_err(|msg| self.create_git_error("merge_to_parent", msg))?;

        // Check if working directory is dirty BEFORE recovering incomplete merge
        // This catches leftovers from previous agent merges or conflicts from prior operations
        let had_incomplete_merge = Self::has_incomplete_merge(parent_path);
        if !had_incomplete_merge && self.has_uncommitted_changes(parent_path).await? {
            warn!(
                "Working directory has uncommitted changes before merging {}. This indicates previous merge conflicts or incomplete operations.",
                agent_branch
            );

            // Return error that will trigger Claude-assisted merge in the merge queue
            // The merge queue looks for "Claude-assisted merge required" in the error message
            return Err(MapReduceError::General {
                message: format!(
                    "Merge conflict detected: Working directory has uncommitted changes from previous operations. Claude-assisted merge required for agent branch '{}'.",
                    agent_branch
                ),
                source: None,
            });
        }

        // Recover from incomplete merge if needed (extracted function)
        if had_incomplete_merge {
            self.recover_incomplete_merge(parent_path, agent_branch)
                .await?;
        }

        // Execute the merge (extracted function)
        self.execute_merge(parent_path, agent_branch).await?;

        info!(
            "Successfully merged agent branch {} to parent",
            agent_branch
        );
        Ok(())
    }

    /// Get commits from a worktree
    pub async fn get_worktree_commits(
        &mut self,
        worktree_path: &Path,
    ) -> MapReduceResult<Vec<String>> {
        let commit_infos = self
            .service
            .get_worktree_commits(worktree_path, None, None)
            .await?;
        Ok(commit_infos.to_string_list())
    }

    /// Get modified files in a worktree
    pub async fn get_modified_files(
        &mut self,
        worktree_path: &Path,
    ) -> MapReduceResult<Vec<String>> {
        let file_infos = self
            .service
            .get_worktree_modified_files(worktree_path, None)
            .await?;
        Ok(file_infos.to_string_list())
    }

    /// Get modified files in a worktree (non-mutable version for backward compatibility)
    pub async fn get_worktree_modified_files(
        &mut self,
        worktree_path: &Path,
    ) -> MapReduceResult<Vec<String>> {
        self.get_modified_files(worktree_path).await
    }

    /// Check if a branch exists
    pub async fn branch_exists(&self, branch_name: &str, worktree_path: &Path) -> bool {
        let output = Command::new("git")
            .args(["rev-parse", "--verify", branch_name])
            .current_dir(worktree_path)
            .output()
            .await
            .ok();

        output.map(|o| o.status.success()).unwrap_or(false)
    }

    /// Delete a branch
    pub async fn delete_branch(
        &self,
        branch_name: &str,
        worktree_path: &Path,
    ) -> MapReduceResult<()> {
        let output = Command::new("git")
            .args(["branch", "-D", branch_name])
            .current_dir(worktree_path)
            .output()
            .await
            .map_err(|e| self.create_git_error("delete_branch", &e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            // It's ok if the branch doesn't exist
            if !stderr.contains("not found") {
                warn!("Failed to delete branch {}: {}", branch_name, stderr);
            }
        }

        Ok(())
    }

    /// Create a standardized git error
    fn create_git_error(&self, operation: &str, message: &str) -> MapReduceError {
        MapReduceError::General {
            message: format!("Git operation '{}' failed: {}", operation, message),
            source: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::Arc;
    use tempfile::TempDir;
    use tokio::process::Command as TokioCommand;

    /// Helper to create a temporary git repository
    async fn create_test_repo() -> (TempDir, std::path::PathBuf) {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let repo_path = temp_dir.path().to_path_buf();

        // Initialize git repo
        let init_output = TokioCommand::new("git")
            .args(["init"])
            .current_dir(&repo_path)
            .output()
            .await
            .expect("Failed to run git init");
        assert!(init_output.status.success(), "git init failed");

        // Configure git user
        TokioCommand::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(&repo_path)
            .output()
            .await
            .expect("Failed to config user.name");

        TokioCommand::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(&repo_path)
            .output()
            .await
            .expect("Failed to config user.email");

        // Create initial commit on main branch
        fs::write(repo_path.join("README.md"), "# Test Repo").expect("Failed to write README");
        TokioCommand::new("git")
            .args(["add", "."])
            .current_dir(&repo_path)
            .output()
            .await
            .expect("Failed to git add");

        let commit_output = TokioCommand::new("git")
            .args(["commit", "-m", "Initial commit"])
            .current_dir(&repo_path)
            .output()
            .await
            .expect("Failed to commit");
        assert!(commit_output.status.success(), "initial commit failed");

        (temp_dir, repo_path)
    }

    /// Helper to create a worktree from the parent repo
    async fn create_test_worktree(parent_path: &Path, worktree_name: &str) -> std::path::PathBuf {
        // Create worktree inside the parent directory to avoid conflicts between concurrent tests
        let worktree_path = parent_path.join(worktree_name);

        let output = TokioCommand::new("git")
            .args([
                "worktree",
                "add",
                worktree_path.to_str().unwrap(),
                "-b",
                worktree_name,
            ])
            .current_dir(parent_path)
            .output()
            .await
            .expect("Failed to create worktree");

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            panic!(
                "Failed to create worktree: {}\nStdout: {}\nStderr: {}",
                output.status,
                String::from_utf8_lossy(&output.stdout),
                stderr
            );
        }

        worktree_path
    }

    /// Helper to create a commit in a worktree
    async fn create_commit_in_worktree(worktree_path: &Path, file_name: &str, content: &str) {
        fs::write(worktree_path.join(file_name), content).expect("Failed to write file");

        TokioCommand::new("git")
            .args(["add", "."])
            .current_dir(worktree_path)
            .output()
            .await
            .expect("Failed to git add");

        let output = TokioCommand::new("git")
            .args(["commit", "-m", &format!("Add {}", file_name)])
            .current_dir(worktree_path)
            .output()
            .await
            .expect("Failed to commit");

        assert!(output.status.success(), "Failed to create commit");
    }

    /// Helper to create MERGE_HEAD file to simulate incomplete merge
    async fn create_merge_head(repo_path: &Path, commit_sha: &str) {
        let merge_head_path = repo_path.join(".git/MERGE_HEAD");
        fs::write(&merge_head_path, format!("{}\n", commit_sha))
            .expect("Failed to create MERGE_HEAD");
    }

    /// Helper to get current commit SHA
    async fn get_current_commit_sha(repo_path: &Path) -> String {
        let output = TokioCommand::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(repo_path)
            .output()
            .await
            .expect("Failed to get commit SHA");

        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    // Tests for pure decision logic functions
    #[test]
    fn test_validate_worktree_context_with_worktree() {
        let env = ExecutionEnvironment {
            working_dir: Arc::new(std::path::PathBuf::from("/tmp/test")),
            project_dir: Arc::new(std::path::PathBuf::from("/tmp/project")),
            worktree_name: Some(Arc::from("test-worktree")),
            session_id: Arc::from("test-session"),
        };

        let result = GitOperations::validate_worktree_context(&env);
        assert!(result.is_ok());
        assert_eq!(**result.unwrap(), std::path::PathBuf::from("/tmp/test"));
    }

    #[test]
    fn test_validate_worktree_context_without_worktree() {
        let env = ExecutionEnvironment {
            working_dir: Arc::new(std::path::PathBuf::from("/tmp/test")),
            project_dir: Arc::new(std::path::PathBuf::from("/tmp/project")),
            worktree_name: None,
            session_id: Arc::from("test-session"),
        };

        let result = GitOperations::validate_worktree_context(&env);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            "Cannot merge: not running in a worktree context"
        );
    }

    #[tokio::test]
    async fn test_has_incomplete_merge_when_merge_head_exists() {
        let (_temp_dir, repo_path) = create_test_repo().await;
        let commit_sha = get_current_commit_sha(&repo_path).await;
        create_merge_head(&repo_path, &commit_sha).await;

        assert!(GitOperations::has_incomplete_merge(&repo_path));
    }

    #[tokio::test]
    async fn test_has_incomplete_merge_when_merge_head_absent() {
        let (_temp_dir, repo_path) = create_test_repo().await;

        assert!(!GitOperations::has_incomplete_merge(&repo_path));
    }

    #[test]
    fn test_should_commit_staged_changes_with_changes() {
        let status_with_changes = "M  some_file.txt\nA  new_file.txt\n";
        assert!(GitOperations::should_commit_staged_changes(
            status_with_changes
        ));
    }

    #[test]
    fn test_should_commit_staged_changes_without_changes() {
        let status_empty = "";
        assert!(!GitOperations::should_commit_staged_changes(status_empty));

        let status_whitespace = "   \n  \n";
        assert!(!GitOperations::should_commit_staged_changes(
            status_whitespace
        ));
    }

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

        // Create ExecutionEnvironment without worktree_name (not in worktree context)
        let env = ExecutionEnvironment {
            working_dir: Arc::new(std::path::PathBuf::from("/tmp")),
            project_dir: Arc::new(std::path::PathBuf::from("/tmp")),
            worktree_name: None,
            session_id: Arc::from("test-session"),
        };

        // Should fail because we're not in a worktree context
        let result = git_ops.merge_agent_to_parent("agent-branch", &env).await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        match err {
            MapReduceError::General { message, .. } => {
                assert!(message.contains("not running in a worktree context"));
            }
            _ => panic!("Expected General error"),
        }
    }

    #[tokio::test]
    async fn test_merge_agent_to_parent_clean_merge_success() {
        let (_temp_dir, parent_path) = create_test_repo().await;
        let worktree_path = create_test_worktree(&parent_path, "agent-worktree").await;

        // Create a commit in the worktree
        create_commit_in_worktree(&worktree_path, "feature.txt", "New feature").await;

        // Create ExecutionEnvironment with worktree context
        let env = ExecutionEnvironment {
            working_dir: Arc::new(parent_path.clone()),
            project_dir: Arc::new(parent_path.clone()),
            worktree_name: Some(Arc::from("agent-worktree")),
            session_id: Arc::from("test-session"),
        };

        let git_ops = GitOperations::new();

        // Perform the merge
        let result = git_ops.merge_agent_to_parent("agent-worktree", &env).await;

        assert!(result.is_ok());

        // Verify the merge was successful by checking if the file exists in parent
        let merged_file = parent_path.join("feature.txt");
        assert!(merged_file.exists(), "Merged file should exist in parent");
    }

    #[tokio::test]
    async fn test_merge_agent_to_parent_with_merge_head_and_staged_changes_commit_succeeds() {
        let (_temp_dir, parent_path) = create_test_repo().await;

        // Get current commit SHA for MERGE_HEAD
        let commit_sha = get_current_commit_sha(&parent_path).await;

        // Create MERGE_HEAD to simulate incomplete merge
        create_merge_head(&parent_path, &commit_sha).await;

        // Create a staged change
        fs::write(parent_path.join("staged.txt"), "staged content")
            .expect("Failed to write staged file");
        let add_output = TokioCommand::new("git")
            .args(["add", "staged.txt"])
            .current_dir(&parent_path)
            .output()
            .await
            .expect("Failed to stage file");
        assert!(add_output.status.success());

        // Create a worktree and commit for the actual merge
        let worktree_path = create_test_worktree(&parent_path, "agent-worktree").await;
        create_commit_in_worktree(&worktree_path, "feature.txt", "New feature").await;

        let env = ExecutionEnvironment {
            working_dir: Arc::new(parent_path.clone()),
            project_dir: Arc::new(parent_path.clone()),
            worktree_name: Some(Arc::from("agent-worktree")),
            session_id: Arc::from("test-session"),
        };

        let git_ops = GitOperations::new();

        // Should recover from incomplete merge and then perform new merge
        let result = git_ops.merge_agent_to_parent("agent-worktree", &env).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_merge_agent_to_parent_with_merge_head_no_staged_changes_abort() {
        let (_temp_dir, parent_path) = create_test_repo().await;

        // Get current commit SHA for MERGE_HEAD
        let commit_sha = get_current_commit_sha(&parent_path).await;

        // Create MERGE_HEAD without staged changes
        create_merge_head(&parent_path, &commit_sha).await;

        // Create a worktree for actual merge
        let worktree_path = create_test_worktree(&parent_path, "agent-worktree").await;
        create_commit_in_worktree(&worktree_path, "feature.txt", "New feature").await;

        let env = ExecutionEnvironment {
            working_dir: Arc::new(parent_path.clone()),
            project_dir: Arc::new(parent_path.clone()),
            worktree_name: Some(Arc::from("agent-worktree")),
            session_id: Arc::from("test-session"),
        };

        let git_ops = GitOperations::new();

        // Should abort incomplete merge and proceed with new merge
        let result = git_ops.merge_agent_to_parent("agent-worktree", &env).await;

        assert!(result.is_ok());

        // MERGE_HEAD should be gone after merge
        assert!(!parent_path.join(".git/MERGE_HEAD").exists());
    }

    #[tokio::test]
    async fn test_merge_agent_to_parent_invalid_branch_triggers_claude_fallback() {
        let (_temp_dir, parent_path) = create_test_repo().await;

        let env = ExecutionEnvironment {
            working_dir: Arc::new(parent_path.clone()),
            project_dir: Arc::new(parent_path.clone()),
            worktree_name: Some(Arc::from("test-worktree")),
            session_id: Arc::from("test-session"),
        };

        let git_ops = GitOperations::new();

        // Try to merge a non-existent branch
        let result = git_ops
            .merge_agent_to_parent("non-existent-branch", &env)
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        match err {
            MapReduceError::General { message, .. } => {
                // Should now trigger Claude-assisted merge fallback
                assert!(message.contains("Claude-assisted merge required"));
                assert!(message.contains("non-existent-branch"));
            }
            _ => panic!("Expected General error with Claude-assisted merge required"),
        }
    }

    #[tokio::test]
    async fn test_merge_conflict_triggers_claude_fallback() {
        let (_temp_dir, parent_path) = create_test_repo().await;

        // Create two worktrees from the same initial commit
        let worktree1 = create_test_worktree(&parent_path, "agent-1").await;
        let worktree2 = create_test_worktree(&parent_path, "agent-2").await;

        // Both modify the same file in conflicting ways
        fs::write(worktree1.join("README.md"), "# Changed by agent 1")
            .expect("Failed to write file");
        TokioCommand::new("git")
            .args(["add", "."])
            .current_dir(&worktree1)
            .output()
            .await
            .expect("Failed to git add");
        TokioCommand::new("git")
            .args(["commit", "-m", "Change by agent 1"])
            .current_dir(&worktree1)
            .output()
            .await
            .expect("Failed to commit");

        fs::write(worktree2.join("README.md"), "# Changed by agent 2")
            .expect("Failed to write file");
        TokioCommand::new("git")
            .args(["add", "."])
            .current_dir(&worktree2)
            .output()
            .await
            .expect("Failed to git add");
        TokioCommand::new("git")
            .args(["commit", "-m", "Conflicting change"])
            .current_dir(&worktree2)
            .output()
            .await
            .expect("Failed to commit");

        // Merge first agent to parent - should succeed
        let env1 = ExecutionEnvironment {
            working_dir: Arc::new(parent_path.clone()),
            project_dir: Arc::new(parent_path.clone()),
            worktree_name: Some(Arc::from("agent-1")),
            session_id: Arc::from("test-session"),
        };

        let git_ops = GitOperations::new();
        let result1 = git_ops.merge_agent_to_parent("agent-1", &env1).await;
        assert!(result1.is_ok(), "First merge should succeed");

        // Try to merge second agent - should trigger Claude fallback due to conflict
        let env2 = ExecutionEnvironment {
            working_dir: Arc::new(parent_path.clone()),
            project_dir: Arc::new(parent_path.clone()),
            worktree_name: Some(Arc::from("agent-2")),
            session_id: Arc::from("test-session"),
        };

        let result2 = git_ops.merge_agent_to_parent("agent-2", &env2).await;
        assert!(result2.is_err(), "Second merge should fail with conflict");

        let err = result2.unwrap_err();
        match err {
            MapReduceError::General { message, .. } => {
                assert!(message.contains("Claude-assisted merge required"));
                assert!(message.contains("agent-2"));
            }
            _ => panic!("Expected General error with Claude-assisted merge required"),
        }
    }
}