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
//! Shell command handler for executing system commands

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

/// Handler for executing shell commands
pub struct ShellHandler;

impl ShellHandler {
    /// Creates a new shell handler
    pub fn new() -> Self {
        Self
    }
}

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

    fn schema(&self) -> AttributeSchema {
        let mut schema = AttributeSchema::new("shell");
        schema.add_required("command", "The shell command to execute");
        schema.add_optional_with_default(
            "shell",
            "The shell to use (bash, sh, zsh)",
            AttributeValue::String("bash".to_string()),
        );
        schema.add_optional_with_default(
            "timeout",
            "Command timeout in seconds",
            AttributeValue::Number(30.0),
        );
        schema.add_optional("working_dir", "Working directory for the command");
        schema.add_optional("env", "Environment variables as key=value pairs");
        schema
    }

    async fn execute(
        &self,
        context: &ExecutionContext,
        mut attributes: HashMap<String, AttributeValue>,
    ) -> CommandResult {
        // Apply defaults
        self.schema().apply_defaults(&mut attributes);

        // Extract command
        let command = match attributes.get("command").and_then(|v| v.as_string()) {
            Some(cmd) => cmd.clone(),
            None => return CommandResult::error("Missing required attribute: command".to_string()),
        };

        // Extract shell
        let shell = attributes
            .get("shell")
            .and_then(|v| v.as_string())
            .map(|s| s.as_str())
            .unwrap_or("bash");

        // Extract timeout
        let timeout = attributes
            .get("timeout")
            .and_then(|v| v.as_number())
            .unwrap_or(30.0) as u64;

        // Extract working directory
        let working_dir = attributes
            .get("working_dir")
            .and_then(|v| v.as_string())
            .map(|s| context.resolve_path(s.as_ref()))
            .unwrap_or_else(|| context.working_dir.clone());

        // Extract additional environment variables
        let mut env = context.full_env();

        // Add environment variables from attributes if present
        let env_vars = attributes
            .get("env")
            .and_then(|v| v.as_object())
            .into_iter()
            .flat_map(|env_attr| env_attr.iter())
            .filter_map(|(key, value)| value.as_string().map(|val| (key.clone(), val.clone())));

        env.extend(env_vars);

        // Execute command
        let start = Instant::now();

        if context.dry_run {
            let duration = start.elapsed().as_millis() as u64;
            return CommandResult::success(Value::String(format!(
                "[DRY RUN] Would execute: {shell} -c '{command}'"
            )))
            .with_duration(duration);
        }

        let result = context
            .executor
            .execute(
                shell,
                &["-c", &command],
                Some(&working_dir),
                Some(env),
                Some(std::time::Duration::from_secs(timeout)),
            )
            .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();
                let exit_code = output.status.code().unwrap_or(-1);

                CommandResult::from_output(stdout, stderr, exit_code).with_duration(duration)
            }
            Err(e) => CommandResult::error(format!("Failed to execute command: {e}"))
                .with_duration(duration),
        }
    }

    fn description(&self) -> &str {
        "Executes shell commands with configurable shell, timeout, and environment"
    }

    fn examples(&self) -> Vec<String> {
        vec![
            r#"{"command": "echo 'Hello, World!'"}"#.to_string(),
            r#"{"command": "ls -la", "working_dir": "/tmp"}"#.to_string(),
            r#"{"command": "npm test", "timeout": 60, "env": {"NODE_ENV": "test"}}"#.to_string(),
        ]
    }
}

impl Default for ShellHandler {
    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_shell_handler_schema() {
        let handler = ShellHandler::new();
        let schema = handler.schema();

        assert!(schema.required().contains_key("command"));
        assert!(schema.optional().contains_key("shell"));
        assert!(schema.optional().contains_key("timeout"));
    }

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

        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".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(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
        assert_eq!(result.stdout, Some("test\n".to_string()));
    }

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

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("rm -rf /".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
        let output = result.data.unwrap();
        let output_str = output.as_str().unwrap();
        assert!(output_str.contains("[DRY RUN]"));
        assert!(output_str.contains("bash"));
        // Verify duration is tracked even in dry_run mode
        assert!(result.duration_ms.is_some());
    }

    #[tokio::test]
    async fn test_missing_command_attribute() {
        let handler = ShellHandler::new();
        let context = ExecutionContext::new(PathBuf::from("/test"));
        let attributes = HashMap::new();

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

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

        mock_executor.expect_execute(
            "zsh",
            vec!["-c", "echo custom"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"custom\n".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(
            "command".to_string(),
            AttributeValue::String("echo custom".to_string()),
        );
        attributes.insert(
            "shell".to_string(),
            AttributeValue::String("zsh".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
        assert_eq!(result.stdout, Some("custom\n".to_string()));
    }

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

        mock_executor.expect_execute(
            "bash",
            vec!["-c", "sleep 1"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(60)),
            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(
            "command".to_string(),
            AttributeValue::String("sleep 1".to_string()),
        );
        attributes.insert("timeout".to_string(), AttributeValue::Number(60.0));

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

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

        mock_executor.expect_execute(
            "bash",
            vec!["-c", "pwd"],
            Some(PathBuf::from("/custom/dir")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"/custom/dir\n".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(
            "command".to_string(),
            AttributeValue::String("pwd".to_string()),
        );
        attributes.insert(
            "working_dir".to_string(),
            AttributeValue::String("/custom/dir".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
        assert_eq!(result.stdout, Some("/custom/dir\n".to_string()));
    }

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

        // Note: MockSubprocessExecutor ignores env parameter, but we test the flow
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo $TEST_VAR"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test_value\n".to_vec(),
                stderr: Vec::new(),
            },
        );

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

        let mut env_obj = HashMap::new();
        env_obj.insert(
            "TEST_VAR".to_string(),
            AttributeValue::String("test_value".to_string()),
        );

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("echo $TEST_VAR".to_string()),
        );
        attributes.insert("env".to_string(), AttributeValue::Object(env_obj));

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
        assert_eq!(result.stdout, Some("test_value\n".to_string()));
    }

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

        // Mock a failure by returning non-zero exit code
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "exit 1"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(1 << 8),
                stdout: Vec::new(),
                stderr: b"Command failed\n".to_vec(),
            },
        );

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

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("exit 1".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert_eq!(result.stderr, Some("Command failed\n".to_string()));
    }

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

        mock_executor.expect_execute(
            "bash",
            vec!["-c", "exit 42"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(42 << 8),
                stdout: Vec::new(),
                stderr: b"Error occurred\n".to_vec(),
            },
        );

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

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("exit 42".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        assert_eq!(result.stderr, Some("Error occurred\n".to_string()));
        assert_eq!(result.exit_code, Some(42));
    }

    #[tokio::test]
    async fn test_executor_error() {
        let handler = ShellHandler::new();
        // Mock executor with no expectations will return error
        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(
            "command".to_string(),
            AttributeValue::String("unexpected command".to_string()),
        );

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

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

        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".to_vec(),
                stderr: Vec::new(),
            },
        );

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

        let mut env_obj = HashMap::new();
        // Add a non-string value (Number) which should be skipped
        env_obj.insert("NUM_VAR".to_string(), AttributeValue::Number(42.0));
        env_obj.insert(
            "STR_VAR".to_string(),
            AttributeValue::String("value".to_string()),
        );

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );
        attributes.insert("env".to_string(), AttributeValue::Object(env_obj));

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

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

        // Verify bash is used as default shell
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".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(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );
        // No shell attribute specified

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

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

        // Verify 30 seconds is used as default timeout
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".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(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );
        // No timeout attribute specified

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

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

        // Relative path should be resolved via context.resolve_path
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "pwd"],
            Some(PathBuf::from("/test/subdir")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"/test/subdir\n".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(
            "command".to_string(),
            AttributeValue::String("pwd".to_string()),
        );
        attributes.insert(
            "working_dir".to_string(),
            AttributeValue::String("subdir".to_string()),
        );

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

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

        // No working_dir specified should use context.working_dir
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "pwd"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"/test\n".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(
            "command".to_string(),
            AttributeValue::String("pwd".to_string()),
        );
        // No working_dir attribute specified - should use context default

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

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

        // Absolute path should be used as-is (after resolve_path)
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "pwd"],
            Some(PathBuf::from("/absolute/path")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"/absolute/path\n".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(
            "command".to_string(),
            AttributeValue::String("pwd".to_string()),
        );
        attributes.insert(
            "working_dir".to_string(),
            AttributeValue::String("/absolute/path".to_string()),
        );

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

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

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );
        attributes.insert(
            "shell".to_string(),
            AttributeValue::String("zsh".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
        let output = result.data.unwrap();
        let output_str = output.as_str().unwrap();
        assert!(output_str.contains("[DRY RUN]"));
        assert!(output_str.contains("zsh"));
        assert!(!output_str.contains("bash"));
        // Verify duration is tracked
        assert!(result.duration_ms.is_some());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_exit_code_none_signal() {
        use std::os::unix::process::ExitStatusExt;

        let handler = ShellHandler::new();
        let mut mock_executor = MockSubprocessExecutor::new();

        // Create exit status from signal (code() returns None on Unix)
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "kill -9 $$"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(9), // Signal 9 (SIGKILL)
                stdout: Vec::new(),
                stderr: b"Killed by signal\n".to_vec(),
            },
        );

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

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("kill -9 $$".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        // Should still produce a result with exit_code -1 when code() is None
        assert_eq!(result.exit_code, Some(-1));
        // Verify duration is tracked even for signal termination
        assert!(result.duration_ms.is_some());
    }

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

        // Invalid UTF-8 bytes
        let invalid_utf8 = vec![0xFF, 0xFE, 0xFD];

        mock_executor.expect_execute(
            "bash",
            vec!["-c", "cat binary_file"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: invalid_utf8.clone(),
                stderr: invalid_utf8,
            },
        );

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

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("cat binary_file".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(result.is_success());
        // String::from_utf8_lossy replaces invalid UTF-8 with replacement character
        assert!(result.stdout.is_some());
        assert!(result.stderr.is_some());
        // Verify duration is tracked
        assert!(result.duration_ms.is_some());
    }

    #[tokio::test]
    async fn test_executor_error_includes_duration() {
        let handler = ShellHandler::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(
            "command".to_string(),
            AttributeValue::String("unexpected".to_string()),
        );

        let result = handler.execute(&context, attributes).await;
        assert!(!result.is_success());
        // Verify duration is tracked even for errors
        assert!(result.duration_ms.is_some());
    }

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

        // Shell attribute as None should fallback to "bash"
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".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(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );

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

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

        // Zero timeout should be used as-is (edge case)
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(0)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".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(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );
        attributes.insert("timeout".to_string(), AttributeValue::Number(0.0));

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

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

        // Non-number timeout should fallback to default 30
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".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(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );
        attributes.insert(
            "timeout".to_string(),
            AttributeValue::String("invalid".to_string()),
        );

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

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

        // Empty string should resolve to context.working_dir
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "pwd"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"/test\n".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(
            "command".to_string(),
            AttributeValue::String("pwd".to_string()),
        );
        attributes.insert(
            "working_dir".to_string(),
            AttributeValue::String("".to_string()),
        );

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

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

        // Path with spaces should be handled correctly
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "pwd"],
            Some(PathBuf::from("/test/path with spaces")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"/test/path with spaces\n".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(
            "command".to_string(),
            AttributeValue::String("pwd".to_string()),
        );
        attributes.insert(
            "working_dir".to_string(),
            AttributeValue::String("path with spaces".to_string()),
        );

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

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

        // Empty env object should work without issues
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".to_vec(),
                stderr: Vec::new(),
            },
        );

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

        let env_obj = HashMap::new();

        let mut attributes = HashMap::new();
        attributes.insert(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );
        attributes.insert("env".to_string(), AttributeValue::Object(env_obj));

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

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

        // Non-object env should be ignored
        mock_executor.expect_execute(
            "bash",
            vec!["-c", "echo test"],
            Some(PathBuf::from("/test")),
            None,
            Some(std::time::Duration::from_secs(30)),
            Output {
                status: std::process::ExitStatus::from_raw(0),
                stdout: b"test\n".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(
            "command".to_string(),
            AttributeValue::String("echo test".to_string()),
        );
        attributes.insert(
            "env".to_string(),
            AttributeValue::String("not an object".to_string()),
        );

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