destructive_command_guard 0.4.3

A Claude Code hook that blocks destructive commands before they execute
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
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
#![allow(clippy::uninlined_format_args)]
//! E2E tests for `dcg suggest-allowlist` command.
//!
//! These tests validate end-to-end behavior of suggest-allowlist, including
//! non-interactive output paths, with detailed logs on failure.
//!
//! # Test Categories
//!
//! 1. **Non-Interactive Mode** - Verifies no allowlist writes occur
//! 2. **Help Output** - Verifies help documentation works
//! 3. **CLI Parsing** - Verifies flag combinations work
//!
//! # Running
//!
//! ```bash
//! cargo test --test suggest_allowlist_e2e -- --nocapture
//! ```

mod common;

use chrono::Utc;
use common::db::TestCommand;
use destructive_command_guard::history::{HistoryDb, Outcome};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Command, Stdio};

/// Path to the dcg binary (built in debug mode for tests).
fn dcg_binary() -> PathBuf {
    let mut path = std::env::current_exe().unwrap();
    path.pop(); // Remove test binary name
    path.pop(); // Remove deps/
    path.push("dcg");
    path
}

/// Test environment with isolated history and config.
struct TestEnv {
    temp_dir: tempfile::TempDir,
    home_dir: PathBuf,
    xdg_config_dir: PathBuf,
    #[allow(dead_code)]
    dcg_dir: PathBuf,
    config_path: PathBuf,
    history_path: PathBuf,
    allowlist_path: PathBuf,
}

impl TestEnv {
    /// Create a new empty test environment.
    fn new() -> Self {
        let temp_dir = tempfile::tempdir().expect("failed to create temp dir");
        let home_dir = temp_dir.path().join("home");
        let xdg_config_dir = temp_dir.path().join("xdg_config");
        let dcg_dir = xdg_config_dir.join("dcg");

        fs::create_dir_all(&home_dir).expect("failed to create HOME dir");
        fs::create_dir_all(&dcg_dir).expect("failed to create XDG_CONFIG_HOME/dcg dir");

        let config_path = dcg_dir.join("config.toml");
        let history_path = dcg_dir.join("history.db");
        let allowlist_path = dcg_dir.join("allowlist.toml");

        // Create a git repo in the temp dir so project detection works
        fs::create_dir_all(temp_dir.path().join(".git")).expect("failed to create .git dir");

        Self {
            temp_dir,
            home_dir,
            xdg_config_dir,
            dcg_dir,
            config_path,
            history_path,
            allowlist_path,
        }
    }

    /// Create history database and populate with test data.
    fn with_history(self, commands: &[TestCommand]) -> Self {
        // Create history database with seed data
        let db = HistoryDb::open(Some(self.history_path.clone()))
            .expect("Failed to create history database");

        let now = Utc::now();
        for cmd in commands {
            let entry = cmd.to_entry(now);
            db.log_command(&entry).expect("Failed to seed command");
        }

        // Create config that points to our history database
        // The CLI reads database_path from config file via DCG_CONFIG env var
        fs::write(
            &self.config_path,
            format!(
                r#"[history]
enabled = true
database_path = "{}"
"#,
                self.history_path.display()
            ),
        )
        .expect("Failed to write config");

        self
    }

    /// Run dcg suggest-allowlist with given args.
    fn run_suggest_allowlist(&self, args: &[&str]) -> std::process::Output {
        self.run_suggest_allowlist_with_env(args, &[])
    }

    /// Run dcg suggest-allowlist with given args and extra environment variables.
    fn run_suggest_allowlist_with_env(
        &self,
        args: &[&str],
        extra_env: &[(&str, &str)],
    ) -> std::process::Output {
        let mut cmd = Command::new(dcg_binary());
        cmd.env_clear()
            .env("HOME", &self.home_dir)
            .env("XDG_CONFIG_HOME", &self.xdg_config_dir)
            .env("DCG_CONFIG", &self.config_path)
            .env("DCG_PACKS", "core.git,core.filesystem,containers.docker")
            .current_dir(self.temp_dir.path())
            .arg("suggest-allowlist")
            .args(args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        for (key, value) in extra_env {
            cmd.env(key, value);
        }

        cmd.output().expect("failed to execute dcg")
    }

    /// Run dcg suggest-allowlist with stdin input (for interactive mode).
    #[allow(dead_code)]
    fn run_suggest_allowlist_interactive(
        &self,
        args: &[&str],
        stdin_input: &str,
    ) -> std::process::Output {
        let mut cmd = Command::new(dcg_binary());
        cmd.env_clear()
            .env("HOME", &self.home_dir)
            .env("XDG_CONFIG_HOME", &self.xdg_config_dir)
            .env("DCG_CONFIG", &self.config_path)
            .env("DCG_PACKS", "core.git,core.filesystem,containers.docker")
            .current_dir(self.temp_dir.path())
            .arg("suggest-allowlist")
            .args(args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        let mut child = cmd.spawn().expect("failed to spawn dcg");
        {
            let stdin = child.stdin.as_mut().expect("failed to open stdin");
            stdin
                .write_all(stdin_input.as_bytes())
                .expect("failed to write stdin");
        }

        child.wait_with_output().expect("failed to wait for dcg")
    }

    /// Check if allowlist file exists.
    fn allowlist_exists(&self) -> bool {
        self.allowlist_path.exists()
    }

    /// Read allowlist contents.
    #[allow(dead_code)]
    fn read_allowlist(&self) -> String {
        fs::read_to_string(&self.allowlist_path).unwrap_or_default()
    }
}

/// Create standard test fixtures with multiple denied commands.
///
/// Note: suggest-allowlist groups by EXACT command text, so we need
/// multiple occurrences of the same command (not just similar patterns).
#[allow(clippy::too_many_lines)]
fn suggest_test_fixtures() -> Vec<TestCommand> {
    vec![
        // Repeat "git reset --hard HEAD" 4 times (meets min-frequency=3)
        TestCommand {
            command: "git reset --hard HEAD",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -3600,
            pack_id: Some("core.git"),
            pattern_name: Some("reset-hard"),
            rule_id: Some("core.git:reset-hard"),
            eval_duration_us: 100,
        },
        TestCommand {
            command: "git reset --hard HEAD",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -3500,
            pack_id: Some("core.git"),
            pattern_name: Some("reset-hard"),
            rule_id: Some("core.git:reset-hard"),
            eval_duration_us: 100,
        },
        TestCommand {
            command: "git reset --hard HEAD",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -3400,
            pack_id: Some("core.git"),
            pattern_name: Some("reset-hard"),
            rule_id: Some("core.git:reset-hard"),
            eval_duration_us: 100,
        },
        TestCommand {
            command: "git reset --hard HEAD",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -3300,
            pack_id: Some("core.git"),
            pattern_name: Some("reset-hard"),
            rule_id: Some("core.git:reset-hard"),
            eval_duration_us: 100,
        },
        // Repeat "git push --force origin main" 3 times (meets min-frequency=3)
        TestCommand {
            command: "git push --force origin main",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -3200,
            pack_id: Some("core.git"),
            pattern_name: Some("push-force-long"),
            rule_id: Some("core.git:push-force-long"),
            eval_duration_us: 100,
        },
        TestCommand {
            command: "git push --force origin main",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -3100,
            pack_id: Some("core.git"),
            pattern_name: Some("push-force-long"),
            rule_id: Some("core.git:push-force-long"),
            eval_duration_us: 100,
        },
        TestCommand {
            command: "git push --force origin main",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -3000,
            pack_id: Some("core.git"),
            pattern_name: Some("push-force-long"),
            rule_id: Some("core.git:push-force-long"),
            eval_duration_us: 100,
        },
        // Additional variants with lower frequency (for testing min-frequency filter)
        TestCommand {
            command: "git reset --hard origin/main",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -2800,
            pack_id: Some("core.git"),
            pattern_name: Some("reset-hard"),
            rule_id: Some("core.git:reset-hard"),
            eval_duration_us: 100,
        },
        TestCommand {
            command: "git reset --hard origin/main",
            outcome: Outcome::Deny,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -2700,
            pack_id: Some("core.git"),
            pattern_name: Some("reset-hard"),
            rule_id: Some("core.git:reset-hard"),
            eval_duration_us: 100,
        },
        // Some allowed commands (should not be suggested)
        TestCommand {
            command: "git status",
            outcome: Outcome::Allow,
            agent_type: "claude_code",
            working_dir: "/data/projects/test",
            timestamp_offset_secs: -2600,
            pack_id: None,
            pattern_name: None,
            rule_id: None,
            eval_duration_us: 50,
        },
    ]
}

// =============================================================================
// Non-Interactive Mode Tests
// =============================================================================

#[test]
fn test_suggest_allowlist_non_interactive_no_writes() {
    eprintln!("=== Testing that non-interactive mode does not write allowlist ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // Verify no allowlist exists initially
    assert!(
        !env.allowlist_exists(),
        "Allowlist should not exist initially"
    );

    // Run in non-interactive mode
    let output = env.run_suggest_allowlist(&["--non-interactive", "--min-frequency", "3"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

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

    // Verify allowlist was NOT created
    assert!(
        !env.allowlist_exists(),
        "Non-interactive mode should NOT create allowlist"
    );

    eprintln!("=== Non-interactive no-writes test PASSED ===");
}

#[test]
fn test_suggest_allowlist_runs_without_crash() {
    eprintln!("=== Testing that suggest-allowlist runs without crashing ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());
    let output = env.run_suggest_allowlist(&["--non-interactive"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    // Command should succeed (exit 0)
    assert!(output.status.success(), "Command should succeed");

    eprintln!("=== No-crash test PASSED ===");
}

#[test]
fn test_suggest_allowlist_empty_history() {
    eprintln!("=== Testing suggest-allowlist with empty history ===");

    let env = TestEnv::new().with_history(&[]);
    let output = env.run_suggest_allowlist(&["--non-interactive"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    // Should succeed even with no history
    assert!(
        output.status.success(),
        "Command should succeed with empty history"
    );

    // Should mention no denied commands found
    assert!(
        stdout.contains("No denied commands")
            || stdout.contains("No commands found")
            || stdout.contains("No suggestions"),
        "Should indicate no suggestions available"
    );

    eprintln!("=== Empty history test PASSED ===");
}

// =============================================================================
// Filter Tests
// =============================================================================

#[test]
fn test_suggest_allowlist_min_frequency_filter() {
    eprintln!("=== Testing min-frequency filter ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // With min-frequency=10, should get "no commands found" message
    let output = env.run_suggest_allowlist(&["--non-interactive", "--min-frequency", "10"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    eprintln!("Stdout with min-frequency=10: {}", stdout);

    assert!(output.status.success(), "Command should succeed");
    // Should indicate no commands met the threshold
    assert!(
        stdout.contains("No commands found")
            || stdout.contains("No denied")
            || stdout.contains("No suggestions"),
        "Should indicate no commands met threshold"
    );

    eprintln!("=== Min-frequency filter test PASSED ===");
}

#[test]
fn test_suggest_allowlist_limit_filter() {
    eprintln!("=== Testing limit filter ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // With limit=1, should work without crash
    let output = env.run_suggest_allowlist(&["--non-interactive", "--limit", "1"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    eprintln!("Stdout with limit=1: {}", stdout);

    assert!(
        output.status.success(),
        "Command should succeed with limit=1"
    );

    eprintln!("=== Limit filter test PASSED ===");
}

// =============================================================================
// Error Handling Tests
// =============================================================================

#[test]
fn test_suggest_allowlist_invalid_since_format() {
    eprintln!("=== Testing invalid --since format handling ===");

    let env = TestEnv::new();

    // Invalid since format should be handled (error or graceful message)
    let output = env.run_suggest_allowlist(&["--non-interactive", "--since", "invalid"]);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stderr: {}", String::from_utf8_lossy(&output.stderr));
    eprintln!("Stdout: {}", String::from_utf8_lossy(&output.stdout));

    // Should fail with non-zero exit code for invalid format
    assert!(
        !output.status.success(),
        "Command should fail with invalid --since"
    );

    eprintln!("=== Invalid --since format test PASSED ===");
}

// =============================================================================
// Help and CLI Tests
// =============================================================================

#[test]
fn test_suggest_allowlist_help() {
    eprintln!("=== Testing suggest-allowlist --help ===");

    let output = Command::new(dcg_binary())
        .args(["suggest-allowlist", "--help"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .expect("failed to execute dcg");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}{stderr}");

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Combined output:\n{}", combined);

    assert!(output.status.success(), "Help command should succeed");

    // Help output should show tool name and basic usage info
    // The suggest-allowlist subcommand may show the main help or command-specific help
    assert!(
        combined.contains("dcg") || combined.contains("suggest") || combined.contains("allowlist"),
        "Help should display tool information"
    );

    eprintln!("=== Help test PASSED ===");
}

#[test]
fn test_suggest_allowlist_cli_parsing_confidence_filter() {
    eprintln!("=== Testing --confidence filter parsing ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    for tier in &["high", "medium", "low", "all"] {
        let output = env.run_suggest_allowlist(&["--non-interactive", "--confidence", tier]);
        let stderr = String::from_utf8_lossy(&output.stderr);

        eprintln!(
            "Confidence={}: exit_code={}",
            tier,
            output.status.code().unwrap_or(-1)
        );
        if !output.status.success() {
            eprintln!("  stderr: {}", stderr);
        }

        assert!(
            output.status.success(),
            "Command with --confidence {} should succeed",
            tier
        );
    }

    eprintln!("=== Confidence filter parsing test PASSED ===");
}

#[test]
fn test_suggest_allowlist_cli_parsing_risk_filter() {
    eprintln!("=== Testing --risk filter parsing ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    for level in &["low", "medium", "high", "all"] {
        let output = env.run_suggest_allowlist(&["--non-interactive", "--risk", level]);
        let stderr = String::from_utf8_lossy(&output.stderr);

        eprintln!(
            "Risk={}: exit_code={}",
            level,
            output.status.code().unwrap_or(-1)
        );
        if !output.status.success() {
            eprintln!("  stderr: {}", stderr);
        }

        assert!(
            output.status.success(),
            "Command with --risk {} should succeed",
            level
        );
    }

    eprintln!("=== Risk filter parsing test PASSED ===");
}

#[test]
fn test_suggest_allowlist_cli_parsing_format() {
    eprintln!("=== Testing --format parsing ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    for format in &["text", "json"] {
        let output = env.run_suggest_allowlist(&["--non-interactive", "--format", format]);
        let stderr = String::from_utf8_lossy(&output.stderr);

        eprintln!(
            "Format={}: exit_code={}",
            format,
            output.status.code().unwrap_or(-1)
        );
        if !output.status.success() {
            eprintln!("  stderr: {}", stderr);
        }

        assert!(
            output.status.success(),
            "Command with --format {} should succeed",
            format
        );
    }

    eprintln!("=== Format parsing test PASSED ===");
}

// =============================================================================
// JSON Output Validation Tests
// =============================================================================

#[test]
fn test_suggest_allowlist_json_output_structure() {
    eprintln!("=== Testing JSON output structure ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // Run with JSON format and low min-frequency to get suggestions
    let output = env.run_suggest_allowlist(&[
        "--non-interactive",
        "--format",
        "json",
        "--min-frequency",
        "2",
    ]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    assert!(
        output.status.success(),
        "JSON output command should succeed"
    );

    // Skip if no suggestions were generated
    if stdout.contains("No denied commands")
        || stdout.contains("No commands found")
        || stdout.trim().is_empty()
    {
        eprintln!("No suggestions generated - skipping JSON structure validation");
        return;
    }

    // Parse the JSON output
    let parsed: Result<serde_json::Value, _> = serde_json::from_str(&stdout);
    assert!(
        parsed.is_ok(),
        "Output should be valid JSON. Got: {}",
        stdout
    );

    let json = parsed.unwrap();

    // JSON should be an array
    assert!(json.is_array(), "JSON output should be an array");

    let suggestions = json.as_array().unwrap();
    eprintln!("Found {} suggestions in JSON output", suggestions.len());

    // Validate structure of each suggestion
    for (i, suggestion) in suggestions.iter().enumerate() {
        eprintln!("Validating suggestion {}: {:?}", i, suggestion);

        // Required fields
        assert!(
            suggestion.get("pattern").is_some(),
            "Suggestion {} should have 'pattern' field",
            i
        );
        assert!(
            suggestion.get("confidence").is_some(),
            "Suggestion {} should have 'confidence' field",
            i
        );
        assert!(
            suggestion.get("risk").is_some(),
            "Suggestion {} should have 'risk' field",
            i
        );
        assert!(
            suggestion.get("frequency").is_some(),
            "Suggestion {} should have 'frequency' field",
            i
        );

        // Validate types
        assert!(
            suggestion["pattern"].is_string(),
            "Suggestion {} 'pattern' should be string",
            i
        );
        assert!(
            suggestion["confidence"].is_string(),
            "Suggestion {} 'confidence' should be string",
            i
        );
        assert!(
            suggestion["risk"].is_string(),
            "Suggestion {} 'risk' should be string",
            i
        );
        assert!(
            suggestion["frequency"].is_number(),
            "Suggestion {} 'frequency' should be number",
            i
        );

        // Validate confidence is valid tier
        let confidence = suggestion["confidence"].as_str().unwrap();
        assert!(
            ["high", "medium", "low"].contains(&confidence),
            "Suggestion {} confidence should be high/medium/low, got: {}",
            i,
            confidence
        );

        // Validate risk is valid level (can be lowercase or capitalized)
        let risk = suggestion["risk"].as_str().unwrap().to_lowercase();
        assert!(
            ["low", "medium", "high"].contains(&risk.as_str()),
            "Suggestion {} risk should be low/medium/high, got: {}",
            i,
            risk
        );
    }

    eprintln!("=== JSON output structure test PASSED ===");
}

#[test]
fn test_suggest_allowlist_json_output_non_empty() {
    eprintln!("=== Testing that JSON output has suggestions when data exists ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // Use min-frequency=3 since we have 4 git reset --hard commands
    let output = env.run_suggest_allowlist(&[
        "--non-interactive",
        "--format",
        "json",
        "--min-frequency",
        "3",
    ]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

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

    // With 4 git reset --hard and 3 git push --force, we should have suggestions
    if !stdout.contains("No denied commands") && !stdout.contains("No commands found") {
        let parsed: serde_json::Value =
            serde_json::from_str(&stdout).expect("Should produce valid JSON");

        if let Some(arr) = parsed.as_array() {
            eprintln!("Got {} suggestions", arr.len());
            // We should have at least one suggestion for the git reset --hard pattern
            assert!(
                !arr.is_empty(),
                "Should have at least one suggestion with test fixtures"
            );
        }
    }

    eprintln!("=== JSON non-empty test PASSED ===");
}

// =============================================================================
// Interactive Mode Tests
// =============================================================================

#[test]
fn test_suggest_allowlist_interactive_accept_writes_allowlist() {
    eprintln!("=== Testing that interactive accept writes to allowlist ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // Verify no allowlist exists initially
    assert!(
        !env.allowlist_exists(),
        "Allowlist should not exist initially"
    );

    // Run in interactive mode with "a\nq\n" (accept first, then quit)
    let output = env.run_suggest_allowlist_interactive(&["--min-frequency", "3"], "a\nq\n");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    // Command should succeed (exit 0)
    assert!(
        output.status.success(),
        "Interactive command should succeed"
    );

    // After accepting a suggestion, allowlist should exist
    // Note: This depends on the suggestion being generated and accepted
    if stdout.contains("[A]ccept") {
        // If we got to the accept prompt, check if allowlist was created
        if stdout.contains("Added pattern") || stdout.contains("written") {
            assert!(
                env.allowlist_exists(),
                "Allowlist should exist after accepting suggestion"
            );

            let contents = env.read_allowlist();
            eprintln!("Allowlist contents:\n{}", contents);

            // Should contain a pattern entry
            assert!(
                contents.contains("[[allow]]") || contents.contains("pattern"),
                "Allowlist should contain pattern entry"
            );
        }
    }

    eprintln!("=== Interactive accept test PASSED ===");
}

#[test]
fn test_suggest_allowlist_interactive_shows_action_prompts() {
    eprintln!("=== Testing that interactive mode shows action prompts ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());
    let output = env.run_suggest_allowlist_interactive(&["--min-frequency", "3"], "q\n");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}{stderr}");

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    assert!(
        output.status.success(),
        "Interactive command should succeed"
    );
    assert!(
        combined.contains("[A]ccept"),
        "Interactive output should include accept prompt"
    );
    assert!(
        combined.contains("[S]kip"),
        "Interactive output should include skip prompt"
    );
    assert!(
        combined.contains("[Q]uit"),
        "Interactive output should include quit prompt"
    );

    eprintln!("=== Interactive action prompt test PASSED ===");
}

#[test]
fn test_suggest_allowlist_ci_forces_non_interactive_mode() {
    eprintln!("=== Testing CI env forces non-interactive suggest mode ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    let output = env.run_suggest_allowlist_with_env(&["--min-frequency", "3"], &[("CI", "true")]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}{stderr}");

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    assert!(
        output.status.success(),
        "Suggest command should succeed in CI mode"
    );
    assert!(
        !combined.contains("[A]ccept"),
        "CI mode should suppress interactive accept prompt"
    );
    assert!(
        !combined.contains("[S]kip"),
        "CI mode should suppress interactive skip prompt"
    );
    assert!(
        !combined.contains("[Q]uit"),
        "CI mode should suppress interactive quit prompt"
    );
    assert!(
        !env.allowlist_exists(),
        "CI-forced non-interactive mode should not write allowlist"
    );

    eprintln!("=== CI non-interactive test PASSED ===");
}

#[test]
fn test_suggest_allowlist_robot_env_forces_json_non_interactive_mode() {
    eprintln!("=== Testing DCG_ROBOT env forces JSON non-interactive suggest mode ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    let output =
        env.run_suggest_allowlist_with_env(&["--min-frequency", "3"], &[("DCG_ROBOT", "1")]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    let combined = format!("{stdout}{stderr}");

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    assert!(
        output.status.success(),
        "Suggest command should succeed in robot mode"
    );
    assert!(
        !combined.contains("[A]ccept"),
        "Robot mode should suppress interactive accept prompt"
    );
    assert!(
        !combined.contains("[S]kip"),
        "Robot mode should suppress interactive skip prompt"
    );
    assert!(
        !combined.contains("[Q]uit"),
        "Robot mode should suppress interactive quit prompt"
    );
    assert!(
        !env.allowlist_exists(),
        "Robot mode should not write allowlist"
    );

    let parsed: serde_json::Value =
        serde_json::from_str(&stdout).expect("Robot mode output should be valid JSON");
    assert!(
        parsed.is_array(),
        "Robot mode suggest output should be a JSON array"
    );

    eprintln!("=== Robot mode non-interactive test PASSED ===");
}

#[test]
fn test_suggest_allowlist_interactive_skip_no_write() {
    eprintln!("=== Testing that interactive skip does not write allowlist ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // Verify no allowlist exists initially
    assert!(
        !env.allowlist_exists(),
        "Allowlist should not exist initially"
    );

    // Run in interactive mode with "s\ns\nq\n" (skip all, then quit)
    let output =
        env.run_suggest_allowlist_interactive(&["--min-frequency", "3"], "s\ns\ns\ns\nq\n");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    // Command should succeed
    assert!(
        output.status.success(),
        "Interactive skip command should succeed"
    );

    // After skipping all suggestions, allowlist should NOT exist
    assert!(
        !env.allowlist_exists(),
        "Allowlist should NOT exist after skipping all suggestions"
    );

    eprintln!("=== Interactive skip test PASSED ===");
}

#[test]
fn test_suggest_allowlist_interactive_quit_early() {
    eprintln!("=== Testing that interactive quit exits cleanly ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // Verify no allowlist exists initially
    assert!(
        !env.allowlist_exists(),
        "Allowlist should not exist initially"
    );

    // Run in interactive mode with just "q\n" (quit immediately)
    let output = env.run_suggest_allowlist_interactive(&["--min-frequency", "3"], "q\n");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("Exit code: {}", output.status.code().unwrap_or(-1));
    eprintln!("Stdout: {}", stdout);
    eprintln!("Stderr: {}", stderr);

    // Command should succeed (exit 0)
    assert!(
        output.status.success(),
        "Interactive quit command should succeed"
    );

    // After quitting, allowlist should NOT exist
    assert!(
        !env.allowlist_exists(),
        "Allowlist should NOT exist after quitting"
    );

    eprintln!("=== Interactive quit test PASSED ===");
}

// =============================================================================
// Verbose Logging Tests
// =============================================================================

#[test]
fn test_suggest_allowlist_verbose_failure_logging() {
    eprintln!("=== Testing verbose failure logging ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // Test with an invalid filter value to trigger failure
    let output = env.run_suggest_allowlist(&["--non-interactive", "--confidence", "invalid"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    eprintln!("===== VERBOSE FAILURE OUTPUT =====");
    eprintln!("Exit code: {:?}", output.status.code());
    eprintln!("Exit success: {}", output.status.success());
    eprintln!("--- STDOUT ({} bytes) ---", stdout.len());
    eprintln!("{}", stdout);
    eprintln!("--- STDERR ({} bytes) ---", stderr.len());
    eprintln!("{}", stderr);
    eprintln!("===== END VERBOSE OUTPUT =====");

    // Invalid filter should cause failure
    assert!(
        !output.status.success(),
        "Command with invalid --confidence value should fail"
    );

    // Stderr should contain error information
    let combined = format!("{}{}", stdout, stderr);
    assert!(
        !combined.is_empty(),
        "Error output should not be empty for invalid input"
    );

    eprintln!("=== Verbose failure logging test PASSED ===");
}

#[test]
fn test_suggest_allowlist_output_diagnostics() {
    eprintln!("=== Testing output diagnostics for debugging ===");

    let env = TestEnv::new().with_history(&suggest_test_fixtures());

    // Run normal command and capture all output for diagnostics
    let output = env.run_suggest_allowlist(&["--non-interactive", "--min-frequency", "2"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Comprehensive diagnostic output
    eprintln!("╔════════════════════════════════════════════════════════════════════╗");
    eprintln!("║                    DIAGNOSTIC OUTPUT                               ║");
    eprintln!("╠════════════════════════════════════════════════════════════════════╣");
    eprintln!("║ Exit Code: {:?}", output.status.code());
    eprintln!("║ Exit Success: {}", output.status.success());
    eprintln!("║ Stdout Length: {} bytes", stdout.len());
    eprintln!("║ Stderr Length: {} bytes", stderr.len());
    eprintln!("╠════════════════════════════════════════════════════════════════════╣");
    eprintln!("║ STDOUT:");
    for line in stdout.lines() {
        eprintln!("{line}");
    }
    eprintln!("╠════════════════════════════════════════════════════════════════════╣");
    eprintln!("║ STDERR:");
    for line in stderr.lines() {
        eprintln!("{line}");
    }
    eprintln!("╚════════════════════════════════════════════════════════════════════╝");

    // Basic sanity check - command should succeed
    assert!(
        output.status.success(),
        "Diagnostics command should succeed"
    );

    eprintln!("=== Output diagnostics test PASSED ===");
}