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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
//! Git command handler for version control operations

use crate::commands::{
    AttributeSchema, AttributeValue, CommandHandler, CommandResult, ExecutionContext,
};
use async_trait::async_trait;
use serde_json::json;
use std::collections::HashMap;
use std::time::Instant;

/// Handler for Git operations
pub struct GitHandler;

impl GitHandler {
    /// Creates a new Git handler
    pub fn new() -> Self {
        Self
    }

    /// Extracts files from attributes, defaulting to ["."] if not specified
    fn extract_files(attributes: &HashMap<String, AttributeValue>) -> Vec<String> {
        attributes
            .get("files")
            .and_then(|v| v.as_array())
            .map(|arr| arr.iter().filter_map(|v| v.as_string().cloned()).collect())
            .filter(|files: &Vec<String>| !files.is_empty())
            .unwrap_or_else(|| vec![".".to_string()])
    }

    /// Builds commit-specific arguments including message and optional auto-staging
    fn build_commit_args(
        operation: &str,
        attributes: &HashMap<String, AttributeValue>,
    ) -> Result<Vec<String>, String> {
        let msg = attributes
            .get("message")
            .and_then(|v| v.as_string())
            .ok_or_else(|| "Commit operation requires 'message' attribute".to_string())?;

        Ok(vec![operation.to_string(), "-m".to_string(), msg.clone()])
    }

    /// Builds checkout/switch arguments with branch and optional create flag
    fn build_checkout_args(
        operation: &str,
        attributes: &HashMap<String, AttributeValue>,
    ) -> Vec<String> {
        let mut args = vec![operation.to_string()];

        if let Some(branch) = attributes.get("branch").and_then(|v| v.as_string()) {
            // Check if we should create the branch (-b flag)
            let should_create = operation == "checkout"
                && attributes
                    .get("args")
                    .and_then(|v| v.as_string())
                    .map(|s| s.contains("-b"))
                    .unwrap_or(false);

            if should_create {
                args.push("-b".to_string());
            }
            args.push(branch.clone());
        }

        args
    }

    /// Builds push/pull arguments with optional remote and branch
    fn build_push_pull_args(
        operation: &str,
        attributes: &HashMap<String, AttributeValue>,
    ) -> Vec<String> {
        let mut args = vec![operation.to_string()];

        if let Some(remote) = attributes.get("remote").and_then(|v| v.as_string()) {
            args.push(remote.clone());
        }
        if let Some(branch) = attributes.get("branch").and_then(|v| v.as_string()) {
            args.push(branch.clone());
        }

        args
    }

    /// Builds git command arguments for any operation
    fn build_git_args(
        operation: &str,
        attributes: &HashMap<String, AttributeValue>,
    ) -> Result<Vec<String>, String> {
        let mut git_args = match operation {
            "commit" => Self::build_commit_args(operation, attributes)?,
            "checkout" | "switch" => Self::build_checkout_args(operation, attributes),
            "push" | "pull" => Self::build_push_pull_args(operation, attributes),
            _ => vec![operation.to_string()],
        };

        // Add additional args if provided
        if let Some(args) = attributes.get("args").and_then(|v| v.as_string()) {
            git_args.extend(args.split_whitespace().map(String::from));
        }

        // Add files if specified and not a commit operation
        if operation != "commit" {
            if let Some(files) = attributes.get("files").and_then(|v| v.as_array()) {
                git_args.extend(files.iter().filter_map(|v| v.as_string()).map(String::from));
            }
        }

        Ok(git_args)
    }

    /// Determines if auto-staging is required for commit operation
    fn should_auto_stage(operation: &str, attributes: &HashMap<String, AttributeValue>) -> bool {
        operation == "commit"
            && attributes
                .get("auto_stage")
                .and_then(|v| v.as_bool())
                .unwrap_or(false)
    }

    /// Validates and extracts the operation attribute
    ///
    /// Returns the operation string if present, or an error message if missing.
    fn validate_operation(attributes: &HashMap<String, AttributeValue>) -> Result<String, String> {
        attributes
            .get("operation")
            .and_then(|v| v.as_string())
            .cloned()
            .ok_or_else(|| "Missing required attribute: operation".to_string())
    }

    /// Executes auto-staging for commit operations if required
    ///
    /// This function uses an early return pattern for non-commit operations or when
    /// auto-staging is disabled, reducing cognitive complexity in the main execute flow.
    /// When auto-staging is enabled, it executes `git add` with the appropriate files.
    async fn execute_auto_staging(
        context: &ExecutionContext,
        operation: &str,
        attributes: &HashMap<String, AttributeValue>,
    ) -> Result<(), String> {
        // Early return for non-commit operations or when auto-staging is disabled
        if !Self::should_auto_stage(operation, attributes) {
            return Ok(());
        }

        let files = Self::extract_files(attributes);
        let add_args: Vec<&str> = std::iter::once("add")
            .chain(files.iter().map(|s| s.as_str()))
            .collect();

        context
            .executor
            .execute(
                "git",
                &add_args,
                Some(&context.working_dir),
                Some(context.full_env()),
                None,
            )
            .await
            .map_err(|e| format!("Failed to stage files: {e}"))?;

        Ok(())
    }

    /// Builds a dry-run response for git commands
    ///
    /// Returns a CommandResult indicating what would be executed without actually running it.
    fn build_dry_run_response(git_args: &[String], duration: u64) -> CommandResult {
        CommandResult::success(json!({
            "dry_run": true,
            "command": format!("git {}", git_args.join(" ")),
        }))
        .with_duration(duration)
    }

    /// Executes a git command and processes the result
    ///
    /// This function handles the actual command execution, stdout/stderr processing,
    /// and result transformation into a CommandResult.
    async fn execute_git_command(
        context: &ExecutionContext,
        operation: String,
        git_args: Vec<String>,
        start: Instant,
    ) -> CommandResult {
        let result = context
            .executor
            .execute(
                "git",
                &git_args.iter().map(|s| s.as_str()).collect::<Vec<_>>(),
                Some(&context.working_dir),
                Some(context.full_env()),
                None,
            )
            .await;

        let duration = start.elapsed().as_millis() as u64;

        match result {
            Ok(output) => {
                let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).to_string();

                if output.status.success() {
                    CommandResult::success(json!({
                        "output": stdout,
                        "operation": operation,
                    }))
                    .with_duration(duration)
                } else {
                    CommandResult::error(format!("Git command failed: {stderr}"))
                        .with_duration(duration)
                }
            }
            Err(e) => CommandResult::error(format!("Failed to execute git command: {e}"))
                .with_duration(duration),
        }
    }

    /// Validates preconditions and prepares git command arguments
    ///
    /// This pure function performs all validation and argument building without side effects.
    /// It returns the validated operation and prepared git arguments, or an error if validation fails.
    fn validate_and_prepare(
        attributes: &HashMap<String, AttributeValue>,
    ) -> Result<(String, Vec<String>), String> {
        let operation = Self::validate_operation(attributes)?;
        let git_args = Self::build_git_args(&operation, attributes)?;
        Ok((operation, git_args))
    }
}

#[async_trait]
impl CommandHandler for GitHandler {
    fn name(&self) -> &str {
        "git"
    }

    fn schema(&self) -> AttributeSchema {
        let mut schema = AttributeSchema::new("git");
        schema.add_required(
            "operation",
            "Git operation to perform (status, diff, commit, etc.)",
        );
        schema.add_optional("args", "Additional arguments for the git command");
        schema.add_optional("message", "Commit message (for commit operation)");
        schema.add_optional("branch", "Branch name (for checkout/create operations)");
        schema.add_optional("remote", "Remote name (for push/pull operations)");
        schema.add_optional("files", "Files to operate on");
        schema.add_optional_with_default(
            "auto_stage",
            "Automatically stage changes before commit",
            AttributeValue::Boolean(false),
        );
        schema
    }

    /// Executes a git command with optimized control flow
    ///
    /// This function uses early returns and pure function extraction to minimize
    /// cognitive complexity and improve readability:
    /// 1. Validates preconditions and builds arguments (pure function)
    /// 2. Returns early for dry-run mode (avoids nested conditionals)
    /// 3. Executes auto-staging if needed (early return pattern)
    /// 4. Executes the git command and returns the result
    async fn execute(
        &self,
        context: &ExecutionContext,
        mut attributes: HashMap<String, AttributeValue>,
    ) -> CommandResult {
        // Apply defaults
        self.schema().apply_defaults(&mut attributes);

        // Validate preconditions and prepare git arguments
        let (operation, git_args) = match Self::validate_and_prepare(&attributes) {
            Ok(result) => result,
            Err(e) => return CommandResult::error(e),
        };

        let start = Instant::now();

        // Early return for dry run mode
        if context.dry_run {
            let duration = start.elapsed().as_millis() as u64;
            return Self::build_dry_run_response(&git_args, duration);
        }

        // Handle auto-staging for commits
        if let Err(e) = Self::execute_auto_staging(context, &operation, &attributes).await {
            return CommandResult::error(e);
        }

        // Execute git command
        Self::execute_git_command(context, operation, git_args, start).await
    }

    fn description(&self) -> &str {
        "Handles Git version control operations"
    }

    fn examples(&self) -> Vec<String> {
        vec![
            r#"{"operation": "status"}"#.to_string(),
            r#"{"operation": "commit", "message": "Fix bug", "auto_stage": true}"#.to_string(),
            r#"{"operation": "checkout", "branch": "feature", "args": "-b"}"#.to_string(),
            r#"{"operation": "push", "remote": "origin", "branch": "main"}"#.to_string(),
        ]
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::subprocess::adapter::MockSubprocessExecutor;
    #[cfg(unix)]
    use std::os::unix::process::ExitStatusExt;
    #[cfg(windows)]
    use std::os::windows::process::ExitStatusExt;
    use std::path::PathBuf;
    use std::process::Output;
    use std::sync::Arc;

    #[tokio::test]
    async fn test_git_handler_schema() {
        let handler = GitHandler::new();
        let schema = handler.schema();

        assert!(schema.required().contains_key("operation"));
        assert!(schema.optional().contains_key("message"));
        assert!(schema.optional().contains_key("branch"));
    }

    #[tokio::test]
    async fn test_git_status() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["status"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"On branch main\nnothing to commit".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("status".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_commit_dry_run() {
        let handler = GitHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test")).with_dry_run(true);

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );
        attributes.insert(
            "message".to_string(),
            AttributeValue::String("Test commit".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());

        let data = result.data.unwrap();
        assert_eq!(data.get("dry_run"), Some(&json!(true)));
    }

    #[tokio::test]
    async fn test_git_missing_operation() {
        let handler = GitHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test"));

        let attributes = HashMap::new();

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert!(result
            .error
            .unwrap()
            .contains("Missing required attribute: operation"));
    }

    #[tokio::test]
    async fn test_git_commit_without_message() {
        let handler = GitHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test"));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert!(result
            .error
            .unwrap()
            .contains("Commit operation requires 'message' attribute"));
    }

    #[tokio::test]
    async fn test_git_commit_with_auto_stage() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["add", "."],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: Vec::new(),
                stderr: Vec::new(),
            },
        );

        mock_executor.expect_execute(
            "git",
            vec!["commit", "-m", "Test commit"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"[main abc123] Test commit".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );
        attributes.insert(
            "message".to_string(),
            AttributeValue::String("Test commit".to_string()),
        );
        attributes.insert("auto_stage".to_string(), AttributeValue::Boolean(true));

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_commit_auto_stage_failure() {
        let handler = GitHandler::new();
        let mock_executor = MockSubprocessExecutor::new();

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );
        attributes.insert(
            "message".to_string(),
            AttributeValue::String("Test commit".to_string()),
        );
        attributes.insert("auto_stage".to_string(), AttributeValue::Boolean(true));

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert!(result.error.unwrap().contains("Failed to stage files"));
    }

    #[tokio::test]
    async fn test_git_commit_success() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["commit", "-m", "Test commit"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"[main abc123] Test commit\n 1 file changed".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );
        attributes.insert(
            "message".to_string(),
            AttributeValue::String("Test commit".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
        let data = result.data.unwrap();
        assert_eq!(data.get("operation"), Some(&json!("commit")));
        assert!(data
            .get("output")
            .unwrap()
            .as_str()
            .unwrap()
            .contains("abc123"));
        assert!(result.duration_ms.is_some());
    }

    #[tokio::test]
    async fn test_git_command_failure() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["commit", "-m", "Test commit"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(1),
                stdout: Vec::new(),
                stderr: b"nothing to commit".to_vec(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );
        attributes.insert(
            "message".to_string(),
            AttributeValue::String("Test commit".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert!(result.error.unwrap().contains("nothing to commit"));
        assert!(result.duration_ms.is_some());
    }

    #[tokio::test]
    async fn test_git_command_execution_error() {
        let handler = GitHandler::new();
        let mock_executor = MockSubprocessExecutor::new();

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );
        attributes.insert(
            "message".to_string(),
            AttributeValue::String("Test commit".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert!(result
            .error
            .unwrap()
            .contains("Failed to execute git command"));
        assert!(result.duration_ms.is_some());
    }

    #[tokio::test]
    async fn test_git_checkout_with_branch() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["checkout", "feature"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Switched to branch 'feature'".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("checkout".to_string()),
        );
        attributes.insert(
            "branch".to_string(),
            AttributeValue::String("feature".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_checkout_create_branch() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["checkout", "-b", "feature", "-b"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Switched to a new branch 'feature'".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("checkout".to_string()),
        );
        attributes.insert(
            "branch".to_string(),
            AttributeValue::String("feature".to_string()),
        );
        attributes.insert("args".to_string(), AttributeValue::String("-b".to_string()));

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_push_with_remote_branch() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["push", "origin", "main"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Everything up-to-date".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("push".to_string()),
        );
        attributes.insert(
            "remote".to_string(),
            AttributeValue::String("origin".to_string()),
        );
        attributes.insert(
            "branch".to_string(),
            AttributeValue::String("main".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_status_with_files() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["status", "src/main.rs", "src/lib.rs"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"On branch main".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("status".to_string()),
        );
        attributes.insert(
            "files".to_string(),
            AttributeValue::Array(vec![
                AttributeValue::String("src/main.rs".to_string()),
                AttributeValue::String("src/lib.rs".to_string()),
            ]),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_add_with_files() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["add", "file1.rs", "file2.rs"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: Vec::new(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("add".to_string()),
        );
        attributes.insert(
            "files".to_string(),
            AttributeValue::Array(vec![
                AttributeValue::String("file1.rs".to_string()),
                AttributeValue::String("file2.rs".to_string()),
            ]),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_switch_to_branch() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["switch", "feature"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Switched to branch 'feature'".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("switch".to_string()),
        );
        attributes.insert(
            "branch".to_string(),
            AttributeValue::String("feature".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_pull_without_remote() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["pull", "main"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Already up to date.".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("pull".to_string()),
        );
        attributes.insert(
            "branch".to_string(),
            AttributeValue::String("main".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_push_without_remote() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["push", "main"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Branch 'main' set up to track remote branch".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("push".to_string()),
        );
        attributes.insert(
            "branch".to_string(),
            AttributeValue::String("main".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_commit_auto_stage_custom_files() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["add", "src/main.rs", "src/lib.rs"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: Vec::new(),
                stderr: Vec::new(),
            },
        );

        mock_executor.expect_execute(
            "git",
            vec!["commit", "-m", "Test commit"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"[main abc123] Test commit".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );
        attributes.insert(
            "message".to_string(),
            AttributeValue::String("Test commit".to_string()),
        );
        attributes.insert("auto_stage".to_string(), AttributeValue::Boolean(true));
        attributes.insert(
            "files".to_string(),
            AttributeValue::Array(vec![
                AttributeValue::String("src/main.rs".to_string()),
                AttributeValue::String("src/lib.rs".to_string()),
            ]),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[test]
    fn test_git_handler_description() {
        let handler = GitHandler::new();
        let description = handler.description();
        assert_eq!(description, "Handles Git version control operations");
    }

    #[test]
    fn test_git_handler_examples() {
        let handler = GitHandler::new();
        let examples = handler.examples();
        assert_eq!(examples.len(), 4);
        assert!(examples[0].contains("status"));
        assert!(examples[1].contains("commit"));
        assert!(examples[2].contains("checkout"));
        assert!(examples[3].contains("push"));
    }

    #[test]
    fn test_git_handler_default() {
        let handler = GitHandler;
        assert_eq!(handler.name(), "git");
    }

    #[tokio::test]
    async fn test_git_checkout_without_branch() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["checkout"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"Already on 'main'".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("checkout".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }

    #[tokio::test]
    async fn test_git_commit_with_additional_args() {
        let handler = GitHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        mock_executor.expect_execute(
            "git",
            vec!["commit", "-m", "Test commit", "--amend", "--no-edit"],
            Some(PathBuf::from("/test")),
            None,
            None,
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"[main abc123] Test commit (amended)".to_vec(),
                stderr: Vec::new(),
            },
        );

        let context =
            ExecutionContext::new(PathBuf::from("/test")).with_executor(Arc::new(mock_executor));

        let mut attributes = HashMap::new();
        attributes.insert(
            "operation".to_string(),
            AttributeValue::String("commit".to_string()),
        );
        attributes.insert(
            "message".to_string(),
            AttributeValue::String("Test commit".to_string()),
        );
        attributes.insert(
            "args".to_string(),
            AttributeValue::String("--amend --no-edit".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
    }
}