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
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
//! Hook protocol handling.
//!
//! This module handles JSON input/output for supported hook protocols
//! (Claude Code, Copilot, and Gemini). It parses incoming hook requests
//! and formats denial responses.

use crate::evaluator::MatchSpan;
use crate::highlight::HighlightSpan;
use crate::output::auto_theme;
#[cfg(feature = "rich-output")]
use crate::output::console::console;
use crate::output::denial::DenialBox;
use crate::output::theme::Severity as ThemeSeverity;
use crate::packs::PatternSuggestion;
use colored::Colorize;
#[cfg(feature = "rich-output")]
#[allow(unused_imports)]
use rich_rust::prelude::*;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
use std::io::{self, IsTerminal, Read, Write};
use std::time::Duration;

/// Input structure from supported hook protocols.
#[derive(Debug, Deserialize)]
pub struct HookInput {
    /// Hook event name (used by some clients, e.g. Copilot CLI: "pre-tool-use").
    pub event: Option<String>,

    /// Gemini hook event name (e.g., "BeforeTool").
    #[serde(alias = "hookEventName")]
    pub hook_event_name: Option<String>,

    /// Gemini session id.
    pub session_id: Option<String>,

    /// Gemini transcript path.
    pub transcript_path: Option<String>,

    /// Gemini working directory.
    pub cwd: Option<String>,

    /// Gemini event timestamp.
    pub timestamp: Option<String>,

    /// The name of the tool being invoked (e.g., "Bash", "Read", "Write").
    #[serde(alias = "toolName")]
    pub tool_name: Option<String>,

    /// Tool-specific input parameters.
    #[serde(alias = "toolInput")]
    pub tool_input: Option<ToolInput>,

    /// Alternate tool arguments format used by some clients.
    /// May be a JSON string (e.g. "{\"command\":\"...\"}") or an object.
    #[serde(alias = "toolArgs")]
    pub tool_args: Option<serde_json::Value>,
}

/// Tool-specific input containing the command to execute.
#[derive(Debug, Deserialize)]
pub struct ToolInput {
    /// The command string (for Bash tools).
    pub command: Option<serde_json::Value>,
}

/// Output structure for denying a command.
#[derive(Debug, Serialize)]
pub struct HookOutput<'a> {
    /// Hook-specific output with the decision.
    #[serde(rename = "hookSpecificOutput")]
    pub hook_specific_output: HookSpecificOutput<'a>,
}

/// Hook-specific output with decision and reason.
#[derive(Debug, Serialize)]
pub struct HookSpecificOutput<'a> {
    /// Always "`PreToolUse`" for this hook.
    #[serde(rename = "hookEventName")]
    pub hook_event_name: &'static str,

    /// The permission decision: "allow" or "deny".
    #[serde(rename = "permissionDecision")]
    pub permission_decision: &'static str,

    /// Human-readable explanation of the decision.
    #[serde(rename = "permissionDecisionReason")]
    pub permission_decision_reason: Cow<'a, str>,

    /// Short allow-once code (if a pending exception was recorded).
    #[serde(rename = "allowOnceCode", skip_serializing_if = "Option::is_none")]
    pub allow_once_code: Option<String>,

    /// Full hash for allow-once disambiguation (if available).
    #[serde(rename = "allowOnceFullHash", skip_serializing_if = "Option::is_none")]
    pub allow_once_full_hash: Option<String>,

    // --- New fields for AI agent ergonomics (git_safety_guard-e4fl.1) ---
    /// Stable rule identifier (e.g., "core.git:reset-hard").
    /// Format: "{packId}:{patternName}"
    #[serde(rename = "ruleId", skip_serializing_if = "Option::is_none")]
    pub rule_id: Option<String>,

    /// Pack identifier that matched (e.g., "core.git").
    #[serde(rename = "packId", skip_serializing_if = "Option::is_none")]
    pub pack_id: Option<String>,

    /// Severity level of the matched pattern.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<crate::packs::Severity>,

    /// Confidence score for this match (0.0-1.0).
    /// Higher values indicate higher confidence that this is a true positive.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,

    /// Remediation suggestions for the blocked command.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remediation: Option<Remediation>,
}

/// Copilot-compatible denial output for pre-tool-use hooks.
///
/// Copilot hooks can consume either:
/// - `continue=false` with `stopReason`
/// - `permissionDecision=deny` with `permissionDecisionReason`
///
/// We emit both for compatibility across documented variants.
#[derive(Debug, Serialize)]
pub struct CopilotHookOutput<'a> {
    /// Whether execution should continue.
    #[serde(rename = "continue")]
    pub continue_execution: bool,

    /// Human-readable stop reason.
    #[serde(rename = "stopReason")]
    pub stop_reason: Cow<'a, str>,

    /// Permission decision (`deny`).
    #[serde(rename = "permissionDecision")]
    pub permission_decision: &'static str,

    /// Human-readable explanation of the decision.
    #[serde(rename = "permissionDecisionReason")]
    pub permission_decision_reason: Cow<'a, str>,

    /// Short allow-once code (if a pending exception was recorded).
    #[serde(rename = "allowOnceCode", skip_serializing_if = "Option::is_none")]
    pub allow_once_code: Option<String>,

    /// Full hash for allow-once disambiguation (if available).
    #[serde(rename = "allowOnceFullHash", skip_serializing_if = "Option::is_none")]
    pub allow_once_full_hash: Option<String>,

    /// Stable rule identifier (e.g., "core.git:reset-hard").
    #[serde(rename = "ruleId", skip_serializing_if = "Option::is_none")]
    pub rule_id: Option<String>,

    /// Pack identifier that matched (e.g., "core.git").
    #[serde(rename = "packId", skip_serializing_if = "Option::is_none")]
    pub pack_id: Option<String>,

    /// Severity level of the matched pattern.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<crate::packs::Severity>,

    /// Confidence score for this match (0.0-1.0).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,

    /// Remediation suggestions for the blocked command.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remediation: Option<Remediation>,
}

/// Gemini-compatible denial output for `BeforeTool` hooks.
#[derive(Debug, Serialize)]
pub struct GeminiHookOutput<'a> {
    /// Decision for this hook event.
    pub decision: &'static str,

    /// Why the action was denied.
    pub reason: Cow<'a, str>,

    /// Human-visible message in Gemini CLI.
    #[serde(rename = "systemMessage", skip_serializing_if = "Option::is_none")]
    pub system_message: Option<Cow<'a, str>>,

    /// Short allow-once code (if a pending exception was recorded).
    #[serde(rename = "allowOnceCode", skip_serializing_if = "Option::is_none")]
    pub allow_once_code: Option<String>,

    /// Full hash for allow-once disambiguation (if available).
    #[serde(rename = "allowOnceFullHash", skip_serializing_if = "Option::is_none")]
    pub allow_once_full_hash: Option<String>,

    /// Stable rule identifier (e.g., "core.git:reset-hard").
    #[serde(rename = "ruleId", skip_serializing_if = "Option::is_none")]
    pub rule_id: Option<String>,

    /// Pack identifier that matched (e.g., "core.git").
    #[serde(rename = "packId", skip_serializing_if = "Option::is_none")]
    pub pack_id: Option<String>,

    /// Severity level of the matched pattern.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<crate::packs::Severity>,

    /// Confidence score for this match (0.0-1.0).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,

    /// Remediation suggestions for the blocked command.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remediation: Option<Remediation>,
}

/// Hook protocol variant for response formatting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookProtocol {
    /// Claude Code / Augment-compatible `hookSpecificOutput` protocol.
    ClaudeCompatible,
    /// Copilot hook protocol (`continue` / `stopReason` + permission fields).
    Copilot,
    /// Gemini hook protocol (`decision` / `reason`).
    Gemini,
}

/// Allow-once metadata for denial output.
#[derive(Debug, Clone)]
pub struct AllowOnceInfo {
    pub code: String,
    pub full_hash: String,
}

/// Remediation suggestions for blocked commands.
///
/// Provides actionable alternatives and context for users to safely
/// accomplish their intended goal.
#[derive(Debug, Clone, Serialize)]
pub struct Remediation {
    /// A safe alternative command that accomplishes a similar goal.
    #[serde(rename = "safeAlternative", skip_serializing_if = "Option::is_none")]
    pub safe_alternative: Option<String>,

    /// Detailed explanation of why the command was blocked and what to do instead.
    pub explanation: String,

    /// The command to run to allow this specific command once (e.g., "dcg allow-once abc12").
    #[serde(rename = "allowOnceCommand")]
    pub allow_once_command: String,
}

/// Result of processing a hook request.
#[derive(Debug)]
pub enum HookResult {
    /// Command is allowed (no output needed).
    Allow,

    /// Command is denied with a reason.
    Deny {
        /// The original command that was blocked.
        command: String,
        /// Why the command was blocked.
        reason: String,
        /// Which pack blocked it (optional).
        pack: Option<String>,
        /// Which pattern matched (optional).
        pattern_name: Option<String>,
    },

    /// Not a Bash command, skip processing.
    Skip,

    /// Error parsing input.
    ParseError,
}

/// Error type for reading and parsing hook input.
#[derive(Debug)]
pub enum HookReadError {
    /// Failed to read from stdin.
    Io(io::Error),
    /// Input exceeded the configured size limit.
    InputTooLarge(usize),
    /// Failed to parse JSON input.
    Json(serde_json::Error),
}

/// Read and parse hook input from stdin.
///
/// # Errors
///
/// Returns [`HookReadError::Io`] if stdin cannot be read, [`HookReadError::Json`]
/// if the input is not valid hook JSON, or [`HookReadError::InputTooLarge`] if
/// the input exceeds `max_bytes`.
pub fn read_hook_input(max_bytes: usize) -> Result<HookInput, HookReadError> {
    let mut input = String::with_capacity(256);
    {
        let stdin = io::stdin();
        // Read up to limit + 1 to detect overflow
        let mut handle = stdin.lock().take(max_bytes as u64 + 1);
        handle
            .read_to_string(&mut input)
            .map_err(HookReadError::Io)?;
    }

    if input.len() > max_bytes {
        return Err(HookReadError::InputTooLarge(input.len()));
    }

    serde_json::from_str(&input).map_err(HookReadError::Json)
}

/// Detect which hook protocol should be used for output formatting.
///
/// # Protocol Disambiguation
///
/// Claude Code and Gemini payloads share several fields (`session_id`,
/// `transcript_path`, `cwd`) which makes naive field-presence checks
/// ambiguous. We disambiguate by checking Claude Code-specific indicators
/// **first** (tool name `"Bash"`, hook event `"PreToolUse"`, and
/// `CLAUDE_CODE` env var), then Gemini-specific markers (tool name
/// `"run_shell_command"` with hook event `"BeforeTool"`).
///
/// See: <https://github.com/Dicklesworthstone/destructive_command_guard/issues/77>
#[must_use]
pub fn detect_protocol(input: &HookInput) -> HookProtocol {
    let tool_name = input
        .tool_name
        .as_deref()
        .map(str::to_ascii_lowercase)
        .unwrap_or_default();
    let hook_event_name = input.hook_event_name.as_deref().unwrap_or_default();

    // --- Copilot indicators (checked first) ---
    // Copilot sends a distinctive `event` field (e.g. "pre-tool-use") that
    // neither Claude Code nor Gemini use. The `tool_args` field is also
    // Copilot-specific. Check these before tool-name-based heuristics
    // because Copilot can use tool_name="bash" (which overlaps with
    // Claude Code's tool names).
    if input.event.is_some() || input.tool_args.is_some() {
        return HookProtocol::Copilot;
    }

    // --- Claude Code indicators ---
    // Claude Code uses tool_name="Bash" or "launch-process". These tool
    // names are never used by Gemini (which uses "run_shell_command").
    // Check this BEFORE Gemini envelope fields, because Claude Code
    // payloads also include session_id/cwd/transcript_path which would
    // otherwise trigger a false Gemini classification (issue #77).
    let is_claude_tool = matches!(tool_name.as_str(), "bash" | "launch-process");
    if is_claude_tool {
        return HookProtocol::ClaudeCompatible;
    }

    // The CLAUDE_CODE env var provides a strong secondary signal when the
    // tool name is ambiguous or absent.
    let is_claude_event =
        hook_event_name.is_empty() || hook_event_name.eq_ignore_ascii_case("pretooluse");
    let has_claude_env = std::env::var_os("CLAUDE_CODE").is_some()
        || std::env::var_os("CLAUDE_SESSION_ID").is_some();
    if has_claude_env && is_claude_event {
        return HookProtocol::ClaudeCompatible;
    }

    // --- Gemini indicators ---
    // Gemini uses tool_name="run_shell_command" and hook_event_name="BeforeTool".
    // It also sends envelope fields (session_id, transcript_path, cwd, timestamp)
    // but those alone are NOT sufficient since Claude Code also sends them.
    let is_gemini_tool = matches!(
        tool_name.as_str(),
        "run_shell_command" | "run-shell-command"
    );
    let is_gemini_event = hook_event_name.eq_ignore_ascii_case("beforetool");
    let has_gemini_envelope = input.session_id.is_some()
        || input.transcript_path.is_some()
        || input.cwd.is_some()
        || input.timestamp.is_some();

    // Strong Gemini signal: BeforeTool event with run_shell_command tool.
    if is_gemini_event && is_gemini_tool {
        return HookProtocol::Gemini;
    }

    // Weaker Gemini signal: envelope fields present AND Gemini-specific
    // event name (but possibly a different tool name).
    if is_gemini_event && has_gemini_envelope {
        return HookProtocol::Gemini;
    }

    // Envelope fields alone with a Gemini tool name (some integrations
    // omit hook_event_name).
    if has_gemini_envelope && is_gemini_tool {
        return HookProtocol::Gemini;
    }

    // Bare run_shell_command without Gemini context -- treat as Copilot
    // (some Copilot integrations use this tool name without `event`).
    if is_gemini_tool {
        return HookProtocol::Copilot;
    }

    // --- Default: Claude Code compatible (safest default) ---
    HookProtocol::ClaudeCompatible
}

fn is_supported_shell_tool(tool_name: Option<&str>) -> bool {
    let Some(tool_name) = tool_name else {
        return false;
    };

    matches!(
        tool_name.to_ascii_lowercase().as_str(),
        "bash" | "launch-process" | "run_shell_command" | "run-shell-command"
    )
}

fn extract_command_from_tool_args(tool_args: &serde_json::Value) -> Option<String> {
    match tool_args {
        serde_json::Value::Object(map) => map.get("command").and_then(|v| match v {
            serde_json::Value::String(s) if !s.is_empty() => Some(s.clone()),
            _ => None,
        }),
        serde_json::Value::String(s) => {
            if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(s) {
                extract_command_from_tool_args(&parsed)
            } else if s.is_empty() {
                None
            } else {
                Some(s.clone())
            }
        }
        _ => None,
    }
}

/// Extract command and protocol from hook input.
#[must_use]
pub fn extract_command_with_protocol(input: &HookInput) -> Option<(String, HookProtocol)> {
    // Only process shell-command invocations for supported clients.
    if !is_supported_shell_tool(input.tool_name.as_deref()) {
        return None;
    }

    let protocol = detect_protocol(input);

    if let Some(tool_input) = input.tool_input.as_ref() {
        if let Some(serde_json::Value::String(s)) = tool_input.command.as_ref() {
            if !s.is_empty() {
                return Some((s.clone(), protocol));
            }
        }
    }

    if let Some(tool_args) = input.tool_args.as_ref() {
        if let Some(command) = extract_command_from_tool_args(tool_args) {
            return Some((command, protocol));
        }
    }

    None
}

/// Extract the command string from hook input.
#[must_use]
pub fn extract_command(input: &HookInput) -> Option<String> {
    extract_command_with_protocol(input).map(|(command, _)| command)
}

/// Configure colored output based on TTY detection.
pub fn configure_colors() {
    if std::env::var_os("NO_COLOR").is_some() || std::env::var_os("DCG_NO_COLOR").is_some() {
        colored::control::set_override(false);
        return;
    }

    if !io::stderr().is_terminal() {
        colored::control::set_override(false);
    }
}

/// Format the explain hint line for copy-paste convenience.
fn format_explain_hint(command: &str) -> String {
    // Escape double quotes in command for safe copy-paste
    let escaped = command.replace('"', "\\\"");
    format!("Tip: dcg explain \"{escaped}\"")
}

fn build_rule_id(pack: Option<&str>, pattern: Option<&str>) -> Option<String> {
    match (pack, pattern) {
        (Some(pack_id), Some(pattern_name)) => Some(format!("{pack_id}:{pattern_name}")),
        _ => None,
    }
}

fn format_explanation_text(
    explanation: Option<&str>,
    rule_id: Option<&str>,
    pack: Option<&str>,
) -> String {
    let trimmed = explanation.map(str::trim).filter(|text| !text.is_empty());

    if let Some(text) = trimmed {
        return text.to_string();
    }

    if let Some(rule) = rule_id {
        return format!(
            "Matched destructive pattern {rule}. No additional explanation is available yet. See pack documentation for details."
        );
    }

    if let Some(pack_name) = pack {
        return format!(
            "Matched destructive pack {pack_name}. No additional explanation is available yet. See pack documentation for details."
        );
    }

    "Matched a destructive pattern. No additional explanation is available yet. See pack documentation for details."
        .to_string()
}

fn format_explanation_block(explanation: &str) -> String {
    let mut lines = explanation.lines();
    let Some(first) = lines.next() else {
        return "Explanation:".to_string();
    };

    let mut output = format!("Explanation: {first}");
    for line in lines {
        output.push('\n');
        output.push_str("             ");
        output.push_str(line);
    }
    output
}

/// Format the denial message for the JSON output (plain text).
#[must_use]
pub fn format_denial_message(
    command: &str,
    reason: &str,
    explanation: Option<&str>,
    pack: Option<&str>,
    pattern: Option<&str>,
) -> String {
    let explain_hint = format_explain_hint(command);
    let rule_id = build_rule_id(pack, pattern);
    let explanation_text = format_explanation_text(explanation, rule_id.as_deref(), pack);
    let explanation_block = format_explanation_block(&explanation_text);

    let rule_line = rule_id.as_deref().map_or_else(
        || {
            pack.map(|pack_name| format!("Pack: {pack_name}\n\n"))
                .unwrap_or_default()
        },
        |rule| format!("Rule: {rule}\n\n"),
    );

    format!(
        "BLOCKED by dcg\n\n\
         {explain_hint}\n\n\
         Reason: {reason}\n\n\
         {explanation_block}\n\n\
         {rule_line}\
         Command: {command}\n\n\
         If this operation is truly needed, ask the user for explicit \
         permission and have them run the command manually."
    )
}

/// Convert packs::Severity to theme::Severity
fn to_output_severity(s: crate::packs::Severity) -> ThemeSeverity {
    match s {
        crate::packs::Severity::Critical => ThemeSeverity::Critical,
        crate::packs::Severity::High => ThemeSeverity::High,
        crate::packs::Severity::Medium => ThemeSeverity::Medium,
        crate::packs::Severity::Low => ThemeSeverity::Low,
    }
}

const MAX_SUGGESTIONS: usize = 4;

/// Print a colorful warning to stderr for human visibility.
#[allow(clippy::too_many_lines)]
pub fn print_colorful_warning(
    command: &str,
    _reason: &str,
    pack: Option<&str>,
    pattern: Option<&str>,
    explanation: Option<&str>,
    allow_once_code: Option<&str>,
    matched_span: Option<&MatchSpan>,
    pattern_suggestions: &[PatternSuggestion],
    severity: Option<crate::packs::Severity>,
) {
    #[cfg(feature = "rich-output")]
    let console_instance = console();
    let theme = auto_theme();

    // Prepare content for DenialBox
    let rule_id = build_rule_id(pack, pattern);
    let pattern_display = rule_id.as_deref().or(pack).unwrap_or("unknown pattern");

    let theme_severity = severity
        .map(to_output_severity)
        .unwrap_or(ThemeSeverity::High);

    let explanation_text = explanation.map(str::trim).filter(|text| !text.is_empty());

    // Create span for highlighting
    let span = matched_span
        .map(|s| HighlightSpan::new(s.start, s.end))
        .unwrap_or_else(|| HighlightSpan::new(0, 0)); // Fallback

    let suggestions_enabled = crate::output::suggestions_enabled();

    // Convert suggestions to alternatives (platform-filtered, capped)
    let filtered_suggestions: Vec<&PatternSuggestion> = if suggestions_enabled {
        pattern_suggestions
            .iter()
            .filter(|s| s.platform.matches_current())
            .collect()
    } else {
        Vec::new()
    };
    let mut alternatives: Vec<String> = filtered_suggestions
        .iter()
        .take(MAX_SUGGESTIONS)
        .map(|s| format!("{}: {}", s.description, s.command))
        .collect();

    // Add contextual suggestion if available and no pattern suggestions
    if suggestions_enabled && alternatives.is_empty() {
        if let Some(sugg) = get_contextual_suggestion(command) {
            alternatives.push(sugg.to_string());
        }
    }

    let mut denial = DenialBox::new(command, span, pattern_display, theme_severity)
        .with_alternatives(alternatives);

    if let Some(text) = explanation_text {
        denial = denial.with_explanation(text);
    }

    if let Some(code) = allow_once_code {
        denial = denial.with_allow_once_code(code);
    }

    // Render the denial box
    // Note: DcgConsole auto-detects stderr usage
    eprintln!("{}", denial.render(&theme));

    // Secondary info (Legacy: printed after box; Rich: could use panels)
    #[cfg(feature = "rich-output")]
    if !console_instance.is_plain() {
        // In rich mode, we might want additional panels or info
        // For now, let's keep it simple as DenialBox handles most things
        // But we might want to print the "Learn more" links
    }

    // "Learn more" section (common to both modes, usually printed after the main warning)
    let escaped_cmd = command.replace('"', "\\\"");
    let truncated_cmd = truncate_for_display(&escaped_cmd, 45);
    let explain_cmd = format!("dcg explain \"{truncated_cmd}\"");

    // Let's print the footer links
    let footer_style = if theme.colors_enabled { "\x1b[90m" } else { "" }; // Bright black
    let reset = if theme.colors_enabled { "\x1b[0m" } else { "" };
    let cyan = if theme.colors_enabled { "\x1b[36m" } else { "" };

    eprintln!("{footer_style}Learn more:{reset}");
    eprintln!("  $ {cyan}{explain_cmd}{reset}");

    if let Some(ref rule) = rule_id {
        eprintln!("  $ {cyan}dcg allowlist add {rule} --project{reset}");
    }

    eprintln!();
    eprintln!("{footer_style}False positive? File an issue:{reset}");
    eprintln!(
        "{footer_style}https://github.com/Dicklesworthstone/destructive_command_guard/issues/new?template=false_positive.yml{reset}"
    );
    eprintln!();
}

#[cfg(feature = "rich-output")]
#[allow(dead_code)] // TODO: Integrate into rich output path
fn render_suggestions_panel(suggestions: &[PatternSuggestion]) -> String {
    use rich_rust::r#box::ROUNDED;
    use rich_rust::prelude::*;

    // Build content as a Vec of lines, then join
    let mut lines = Vec::new();
    if !crate::output::suggestions_enabled() {
        return String::new();
    }

    let filtered: Vec<&PatternSuggestion> = suggestions
        .iter()
        .filter(|s| s.platform.matches_current())
        .take(MAX_SUGGESTIONS)
        .collect();

    for (i, s) in filtered.iter().enumerate() {
        lines.push(format!("[bold cyan]{}.[/] {}", i + 1, s.description));
        lines.push(format!("   [green]$[/] [cyan]{}[/]", s.command));
    }
    let content_str = lines.join("\n");

    let width = crate::output::terminal_width() as usize;
    Panel::from_text(&content_str)
        .title("[yellow bold] 💡 Suggestions [/]")
        .box_style(&ROUNDED)
        .border_style(Style::new().color(Color::parse("yellow").unwrap_or_default()))
        .render_plain(width)
}

/// Truncate a string for display, appending "..." if truncated.
fn truncate_for_display(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        // Find a safe UTF-8 boundary for truncation
        let target = max_len.saturating_sub(3);
        let boundary = s
            .char_indices()
            .take_while(|(i, _)| *i < target)
            .last()
            .map_or(0, |(i, c)| i + c.len_utf8());
        format!("{}...", &s[..boundary])
    }
}

/// Get context-specific suggestion based on the blocked command.
fn get_contextual_suggestion(command: &str) -> Option<&'static str> {
    if command.contains("reset") || command.contains("checkout") {
        Some("Consider using 'git stash' first to save your changes.")
    } else if command.contains("clean") {
        Some("Use 'git clean -n' first to preview what would be deleted.")
    } else if command.contains("push") && command.contains("force") {
        Some("Consider using '--force-with-lease' for safer force pushing.")
    } else if command.contains("rm -rf") || command.contains("rm -r") {
        Some("Verify the path carefully before running rm -rf manually.")
    } else if command.contains("DROP") || command.contains("drop") {
        Some("Consider backing up the database/table before dropping.")
    } else if command.contains("kubectl") && command.contains("delete") {
        Some("Use 'kubectl delete --dry-run=client' to preview changes first.")
    } else if command.contains("docker") && command.contains("prune") {
        Some("Use 'docker system df' to see what would be affected.")
    } else if command.contains("terraform") && command.contains("destroy") {
        Some("Use 'terraform plan -destroy' to preview changes first.")
    } else {
        None
    }
}

/// Output a denial response to stdout (JSON for hook protocol).
#[cold]
#[inline(never)]
#[allow(clippy::too_many_arguments)]
pub fn output_denial_for_protocol(
    protocol: HookProtocol,
    command: &str,
    reason: &str,
    pack: Option<&str>,
    pattern: Option<&str>,
    explanation: Option<&str>,
    allow_once: Option<&AllowOnceInfo>,
    matched_span: Option<&MatchSpan>,
    severity: Option<crate::packs::Severity>,
    confidence: Option<f64>,
    pattern_suggestions: &[PatternSuggestion],
) {
    // Print colorful warning to stderr (visible to user)
    let allow_once_code = allow_once.map(|info| info.code.as_str());
    print_colorful_warning(
        command,
        reason,
        pack,
        pattern,
        explanation,
        allow_once_code,
        matched_span,
        pattern_suggestions,
        severity,
    );

    // Build JSON response for hook protocol (stdout)
    let message = format_denial_message(command, reason, explanation, pack, pattern);
    let rule_id = build_rule_id(pack, pattern);
    let remediation = allow_once.map(|info| {
        let explanation_text = format_explanation_text(explanation, rule_id.as_deref(), pack);
        Remediation {
            safe_alternative: get_contextual_suggestion(command).map(String::from),
            explanation: explanation_text,
            allow_once_command: format!("dcg allow-once {}", info.code),
        }
    });

    let stdout = io::stdout();
    let mut handle = stdout.lock();

    match protocol {
        HookProtocol::ClaudeCompatible => {
            let output = HookOutput {
                hook_specific_output: HookSpecificOutput {
                    hook_event_name: "PreToolUse",
                    permission_decision: "deny",
                    permission_decision_reason: Cow::Owned(message.clone()),
                    allow_once_code: allow_once.map(|info| info.code.clone()),
                    allow_once_full_hash: allow_once.map(|info| info.full_hash.clone()),
                    rule_id,
                    pack_id: pack.map(String::from),
                    severity,
                    confidence,
                    remediation,
                },
            };

            let _ = serde_json::to_writer(&mut handle, &output);
            let _ = writeln!(handle);
        }
        HookProtocol::Copilot => {
            let output = CopilotHookOutput {
                continue_execution: false,
                stop_reason: Cow::Owned(format!("BLOCKED by dcg: {reason}")),
                permission_decision: "deny",
                permission_decision_reason: Cow::Owned(message.clone()),
                allow_once_code: allow_once.map(|info| info.code.clone()),
                allow_once_full_hash: allow_once.map(|info| info.full_hash.clone()),
                rule_id,
                pack_id: pack.map(String::from),
                severity,
                confidence,
                remediation,
            };

            let _ = serde_json::to_writer(&mut handle, &output);
            let _ = writeln!(handle);
        }
        HookProtocol::Gemini => {
            let output = GeminiHookOutput {
                decision: "deny",
                reason: Cow::Owned(message),
                system_message: Some(Cow::Owned(format!("BLOCKED by dcg: {reason}"))),
                allow_once_code: allow_once.map(|info| info.code.clone()),
                allow_once_full_hash: allow_once.map(|info| info.full_hash.clone()),
                rule_id,
                pack_id: pack.map(String::from),
                severity,
                confidence,
                remediation,
            };

            let _ = serde_json::to_writer(&mut handle, &output);
            let _ = writeln!(handle);
        }
    }
}

/// Output a denial response to stdout (JSON for hook protocol).
#[cold]
#[inline(never)]
#[allow(clippy::too_many_arguments)]
pub fn output_denial(
    command: &str,
    reason: &str,
    pack: Option<&str>,
    pattern: Option<&str>,
    explanation: Option<&str>,
    allow_once: Option<&AllowOnceInfo>,
    matched_span: Option<&MatchSpan>,
    severity: Option<crate::packs::Severity>,
    confidence: Option<f64>,
    pattern_suggestions: &[PatternSuggestion],
) {
    output_denial_for_protocol(
        HookProtocol::ClaudeCompatible,
        command,
        reason,
        pack,
        pattern,
        explanation,
        allow_once,
        matched_span,
        severity,
        confidence,
        pattern_suggestions,
    );
}

/// Output a warning for a warn-severity match.
///
/// Prints a human-readable warning to stderr and emits a hook-protocol JSON
/// response to stdout with `permissionDecision: "ask"` (Claude Code / Copilot)
/// or `decision: "ask"` (Gemini).  This makes warn-severity matches visible
/// to AI coding agents that only read stdout JSON, while still allowing the
/// user to approve the command interactively.
#[cold]
#[inline(never)]
pub fn output_warning_for_protocol(
    protocol: HookProtocol,
    command: &str,
    reason: &str,
    pack: Option<&str>,
    pattern: Option<&str>,
    explanation: Option<&str>,
) {
    // -- stderr: human-visible warning (unchanged) --
    {
        let stderr = io::stderr();
        let mut handle = stderr.lock();

        let _ = writeln!(handle);
        let _ = writeln!(handle, "{} {}", "dcg WARNING:".yellow().bold(), reason);

        let rule_id = build_rule_id(pack, pattern);
        let explanation_text = format_explanation_text(explanation, rule_id.as_deref(), pack);
        let mut explanation_lines = explanation_text.lines();

        if let Some(first) = explanation_lines.next() {
            let _ = writeln!(handle, "  {} {}", "Explanation:".bright_black(), first);
            for line in explanation_lines {
                let _ = writeln!(handle, "               {line}");
            }
        }

        if let Some(ref rule) = rule_id {
            let _ = writeln!(handle, "  {} {}", "Rule:".bright_black(), rule);
        } else if let Some(pack_name) = pack {
            let _ = writeln!(handle, "  {} {}", "Pack:".bright_black(), pack_name);
        }

        let _ = writeln!(handle, "  {} {}", "Command:".bright_black(), command);
    }

    // -- stdout: hook-protocol JSON with "ask" decision --
    let rule_id = build_rule_id(pack, pattern);
    let warn_reason = format!("DCG warn: {reason}");

    let stdout = io::stdout();
    let mut handle = stdout.lock();

    match protocol {
        HookProtocol::ClaudeCompatible => {
            let output = HookOutput {
                hook_specific_output: HookSpecificOutput {
                    hook_event_name: "PreToolUse",
                    permission_decision: "ask",
                    permission_decision_reason: Cow::Owned(warn_reason),
                    allow_once_code: None,
                    allow_once_full_hash: None,
                    rule_id,
                    pack_id: pack.map(String::from),
                    severity: None,
                    confidence: None,
                    remediation: None,
                },
            };

            let _ = serde_json::to_writer(&mut handle, &output);
            let _ = writeln!(handle);
        }
        HookProtocol::Copilot => {
            let output = CopilotHookOutput {
                continue_execution: false,
                stop_reason: Cow::Owned(format!("DCG warn: {reason}")),
                permission_decision: "ask",
                permission_decision_reason: Cow::Owned(warn_reason),
                allow_once_code: None,
                allow_once_full_hash: None,
                rule_id,
                pack_id: pack.map(String::from),
                severity: None,
                confidence: None,
                remediation: None,
            };

            let _ = serde_json::to_writer(&mut handle, &output);
            let _ = writeln!(handle);
        }
        HookProtocol::Gemini => {
            let output = GeminiHookOutput {
                decision: "ask",
                reason: Cow::Owned(warn_reason.clone()),
                system_message: Some(Cow::Owned(warn_reason)),
                allow_once_code: None,
                allow_once_full_hash: None,
                rule_id,
                pack_id: pack.map(String::from),
                severity: None,
                confidence: None,
                remediation: None,
            };

            let _ = serde_json::to_writer(&mut handle, &output);
            let _ = writeln!(handle);
        }
    }
}

/// Log a blocked command to a file (if logging is enabled).
///
/// # Errors
///
/// Returns any I/O errors encountered while creating directories or appending
/// to the log file.
pub fn log_blocked_command(
    log_file: &str,
    command: &str,
    reason: &str,
    pack: Option<&str>,
) -> io::Result<()> {
    use std::fs::OpenOptions;

    // Expand ~ in path
    let path = if log_file.starts_with("~/") {
        dirs::home_dir().map_or_else(
            || std::path::PathBuf::from(log_file),
            |h| h.join(&log_file[2..]),
        )
    } else {
        std::path::PathBuf::from(log_file)
    };

    // Ensure parent directory exists
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let mut file = OpenOptions::new().create(true).append(true).open(path)?;

    let timestamp = chrono_lite_timestamp();
    let pack_str = pack.unwrap_or("unknown");

    writeln!(file, "[{timestamp}] [{pack_str}] {reason}")?;
    writeln!(file, "  Command: {command}")?;
    writeln!(file)?;

    Ok(())
}

/// Log a budget skip to a file (if logging is enabled).
///
/// # Errors
///
/// Returns any I/O errors encountered while creating directories or appending
/// to the log file.
pub fn log_budget_skip(
    log_file: &str,
    command: &str,
    stage: &str,
    elapsed: Duration,
    budget: Duration,
) -> io::Result<()> {
    use std::fs::OpenOptions;

    // Expand ~ in path
    let path = if log_file.starts_with("~/") {
        dirs::home_dir().map_or_else(
            || std::path::PathBuf::from(log_file),
            |h| h.join(&log_file[2..]),
        )
    } else {
        std::path::PathBuf::from(log_file)
    };

    // Ensure parent directory exists
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let mut file = OpenOptions::new().create(true).append(true).open(path)?;

    let timestamp = chrono_lite_timestamp();
    writeln!(
        file,
        "[{timestamp}] [budget] evaluation skipped due to budget at {stage}"
    )?;
    writeln!(
        file,
        "  Budget: {}ms, Elapsed: {}ms",
        budget.as_millis(),
        elapsed.as_millis()
    )?;
    writeln!(file, "  Command: {command}")?;
    writeln!(file)?;

    Ok(())
}

/// Simple timestamp without chrono dependency.
/// Returns Unix epoch seconds as a string (e.g., "1704672000").
fn chrono_lite_timestamp() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};

    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();

    let secs = duration.as_secs();
    format!("{secs}")
}

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

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    struct EnvVarGuard {
        key: &'static str,
        previous: Option<String>,
    }

    impl EnvVarGuard {
        fn set(key: &'static str, value: &str) -> Self {
            let previous = std::env::var(key).ok();
            // SAFETY: We hold ENV_LOCK during all tests that use this guard,
            // ensuring no concurrent access to environment variables.
            unsafe { std::env::set_var(key, value) };
            Self { key, previous }
        }

        #[allow(dead_code)]
        fn remove(key: &'static str) -> Self {
            let previous = std::env::var(key).ok();
            // SAFETY: We hold ENV_LOCK during all tests that use this guard,
            // ensuring no concurrent access to environment variables.
            unsafe { std::env::remove_var(key) };
            Self { key, previous }
        }
    }

    impl Drop for EnvVarGuard {
        fn drop(&mut self) {
            if let Some(value) = self.previous.take() {
                // SAFETY: We hold ENV_LOCK during all tests that use this guard,
                // ensuring no concurrent access to environment variables.
                unsafe { std::env::set_var(self.key, value) };
            } else {
                // SAFETY: We hold ENV_LOCK during all tests that use this guard,
                // ensuring no concurrent access to environment variables.
                unsafe { std::env::remove_var(self.key) };
            }
        }
    }

    #[test]
    fn test_parse_valid_bash_input() {
        let json = r#"{"tool_name":"Bash","tool_input":{"command":"git status"}}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), Some("git status".to_string()));
    }

    #[test]
    fn test_parse_non_bash_input() {
        let json = r#"{"tool_name":"Read","tool_input":{"command":"git status"}}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), None);
    }

    #[test]
    fn test_parse_missing_command() {
        let json = r#"{"tool_name":"Bash","tool_input":{}}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), None);
    }

    #[test]
    fn test_parse_copilot_tool_input_command() {
        let json = r#"{"event":"pre-tool-use","toolName":"run_shell_command","toolInput":{"command":"git status"}}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), Some("git status".to_string()));
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
    }

    #[test]
    fn test_parse_copilot_tool_args_json_string() {
        let json = r#"{"event":"pre-tool-use","toolName":"bash","toolArgs":"{\"command\":\"rm -rf /tmp/build\"}"}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(
            extract_command(&input),
            Some("rm -rf /tmp/build".to_string())
        );
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
    }

    #[test]
    fn test_parse_gemini_before_tool_input() {
        let json = r#"{
            "session_id":"session-123",
            "transcript_path":"/tmp/transcript.json",
            "cwd":"/tmp",
            "hook_event_name":"BeforeTool",
            "timestamp":"2026-02-24T00:00:00Z",
            "tool_name":"run_shell_command",
            "tool_input":{"command":"git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), Some("git status".to_string()));
        assert_eq!(detect_protocol(&input), HookProtocol::Gemini);
    }

    #[test]
    fn test_hook_event_name_alone_does_not_force_gemini_protocol() {
        let json = r#"{
            "hook_event_name":"BeforeTool",
            "tool_name":"Bash",
            "tool_input":{"command":"git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), Some("git status".to_string()));
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }

    #[test]
    fn test_gemini_before_tool_marker_detects_gemini_without_session_fields() {
        let json = r#"{
            "hook_event_name":"BeforeTool",
            "tool_name":"run_shell_command",
            "tool_input":{"command":"git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), Some("git status".to_string()));
        assert_eq!(detect_protocol(&input), HookProtocol::Gemini);
    }

    #[test]
    fn test_gemini_hook_output_json_shape() {
        let output = GeminiHookOutput {
            decision: "deny",
            reason: Cow::Borrowed("blocked for safety"),
            system_message: Some(Cow::Borrowed("BLOCKED by dcg: test")),
            allow_once_code: None,
            allow_once_full_hash: None,
            rule_id: Some("core.git:reset-hard".to_string()),
            pack_id: Some("core.git".to_string()),
            severity: None,
            confidence: None,
            remediation: None,
        };
        let json = serde_json::to_value(&output).unwrap();
        assert_eq!(json["decision"], "deny");
        assert_eq!(json["reason"], "blocked for safety");
        assert_eq!(json["systemMessage"], "BLOCKED by dcg: test");
        assert!(json.get("continue").is_none());
        assert!(json.get("stopReason").is_none());
        assert_eq!(json["ruleId"], "core.git:reset-hard");
        assert_eq!(json["packId"], "core.git");
    }

    #[test]
    fn test_parse_non_string_command() {
        let json = r#"{"tool_name":"Bash","tool_input":{"command":123}}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), None);
    }

    #[test]
    fn test_format_denial_message_includes_explanation_and_rule() {
        let message = format_denial_message(
            "git reset --hard",
            "destructive",
            Some("This is irreversible."),
            Some("core.git"),
            Some("reset-hard"),
        );

        assert!(message.contains("Reason: destructive"));
        assert!(message.contains("Explanation: This is irreversible."));
        assert!(message.contains("Rule: core.git:reset-hard"));
        assert!(message.contains("Tip: dcg explain"));
    }

    #[test]
    fn test_claude_compatible_warn_ask_json_shape() {
        let output = HookOutput {
            hook_specific_output: HookSpecificOutput {
                hook_event_name: "PreToolUse",
                permission_decision: "ask",
                permission_decision_reason: Cow::Borrowed("DCG warn: risky pattern"),
                allow_once_code: None,
                allow_once_full_hash: None,
                rule_id: Some("core.git:checkout-dot".to_string()),
                pack_id: Some("core.git".to_string()),
                severity: None,
                confidence: None,
                remediation: None,
            },
        };
        let json = serde_json::to_value(&output).unwrap();
        let specific = &json["hookSpecificOutput"];
        assert_eq!(specific["hookEventName"], "PreToolUse");
        assert_eq!(specific["permissionDecision"], "ask");
        assert!(
            specific["permissionDecisionReason"]
                .as_str()
                .unwrap()
                .starts_with("DCG warn:")
        );
        assert_eq!(specific["ruleId"], "core.git:checkout-dot");
        assert_eq!(specific["packId"], "core.git");
    }

    #[test]
    fn test_copilot_warn_ask_json_shape() {
        let output = CopilotHookOutput {
            continue_execution: false,
            stop_reason: Cow::Borrowed("DCG warn: risky pattern"),
            permission_decision: "ask",
            permission_decision_reason: Cow::Borrowed("DCG warn: risky pattern"),
            allow_once_code: None,
            allow_once_full_hash: None,
            rule_id: None,
            pack_id: None,
            severity: None,
            confidence: None,
            remediation: None,
        };
        let json = serde_json::to_value(&output).unwrap();
        assert_eq!(json["permissionDecision"], "ask");
        assert_eq!(json["continue"], false);
    }

    #[test]
    fn test_gemini_warn_ask_json_shape() {
        let output = GeminiHookOutput {
            decision: "ask",
            reason: Cow::Borrowed("DCG warn: risky pattern"),
            system_message: Some(Cow::Borrowed("DCG warn: risky pattern")),
            allow_once_code: None,
            allow_once_full_hash: None,
            rule_id: None,
            pack_id: None,
            severity: None,
            confidence: None,
            remediation: None,
        };
        let json = serde_json::to_value(&output).unwrap();
        assert_eq!(json["decision"], "ask");
        assert!(json["reason"].as_str().unwrap().starts_with("DCG warn:"));
    }

    #[test]
    fn test_env_var_guard_restores_value() {
        let _lock = ENV_LOCK.lock().unwrap();
        let key = "DCG_TEST_ENV_GUARD";
        // SAFETY: We hold ENV_LOCK to prevent concurrent env modifications
        unsafe { std::env::remove_var(key) };

        {
            let _guard = EnvVarGuard::set(key, "1");
            assert_eq!(std::env::var(key).as_deref(), Ok("1"));
        }

        assert!(std::env::var(key).is_err());
    }

    // =========================================================================
    // Regression tests for issue #77: Claude Code payloads with session_id/cwd
    // being misclassified as Gemini protocol.
    // =========================================================================

    #[test]
    fn test_claude_code_with_session_fields_not_gemini_issue_77() {
        // This is the exact scenario from issue #77: Claude Code sends
        // tool_name="Bash" along with session_id, cwd, and transcript_path.
        // Before the fix, has_gemini_context was true and this was
        // misclassified as Gemini, causing DCG to emit {"decision":"deny",...}
        // instead of {"hookSpecificOutput":{"permissionDecision":"deny",...}}.
        let json = r#"{
            "session_id": "sess-abc123",
            "transcript_path": "/tmp/claude/transcript.json",
            "cwd": "/home/user/project",
            "tool_name": "Bash",
            "tool_input": {"command": "git reset --hard HEAD~1"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(
            detect_protocol(&input),
            HookProtocol::ClaudeCompatible,
            "Claude Code payload with session_id/cwd must NOT be classified as Gemini"
        );
        assert_eq!(
            extract_command(&input),
            Some("git reset --hard HEAD~1".to_string())
        );
    }

    #[test]
    fn test_claude_code_full_payload_with_all_shared_fields() {
        // Claude Code payload with ALL fields that overlap with Gemini.
        let json = r#"{
            "session_id": "sess-xyz",
            "transcript_path": "/tmp/transcript",
            "cwd": "/data/projects",
            "timestamp": "2026-03-20T00:00:00Z",
            "tool_name": "Bash",
            "tool_input": {"command": "rm -rf /tmp/build"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(
            detect_protocol(&input),
            HookProtocol::ClaudeCompatible,
            "tool_name=Bash is a definitive Claude Code indicator regardless of envelope fields"
        );
    }

    #[test]
    fn test_claude_code_with_cwd_only() {
        // Minimal Claude Code payload with just cwd (common case).
        let json = r#"{
            "cwd": "/home/user/project",
            "tool_name": "Bash",
            "tool_input": {"command": "ls"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }

    #[test]
    fn test_claude_code_launch_process_with_session_fields() {
        // launch-process is also a Claude Code tool name.
        let json = r#"{
            "session_id": "sess-abc",
            "cwd": "/tmp",
            "tool_name": "launch-process",
            "tool_input": {"command": "git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }

    #[test]
    fn test_gemini_not_affected_by_fix() {
        // Verify genuine Gemini payloads still work correctly.
        let json = r#"{
            "session_id": "gemini-session",
            "transcript_path": "/tmp/gemini/transcript",
            "cwd": "/home/user",
            "hook_event_name": "BeforeTool",
            "timestamp": "2026-03-20T00:00:00Z",
            "tool_name": "run_shell_command",
            "tool_input": {"command": "git reset --hard"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(
            detect_protocol(&input),
            HookProtocol::Gemini,
            "Genuine Gemini payloads must still be classified as Gemini"
        );
    }

    #[test]
    fn test_copilot_with_event_field_takes_priority() {
        // Copilot sends `event` field which is unique to it.
        // Even with session_id present, event takes priority.
        let json = r#"{
            "event": "pre-tool-use",
            "session_id": "some-session",
            "cwd": "/tmp",
            "tool_name": "bash",
            "tool_args": "{\"command\":\"git status\"}"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(
            detect_protocol(&input),
            HookProtocol::Copilot,
            "Copilot event field must take priority over shared envelope fields"
        );
    }

    #[test]
    fn test_bare_run_shell_command_without_context_is_copilot() {
        // run_shell_command without any Gemini context or event field.
        let json = r#"{
            "tool_name": "run_shell_command",
            "tool_input": {"command": "git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
    }

    #[test]
    fn test_minimal_bash_payload_is_claude_compatible() {
        // Minimal payload with just tool_name=Bash.
        let json = r#"{"tool_name":"Bash","tool_input":{"command":"echo hello"}}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }

    #[test]
    fn test_empty_payload_defaults_to_claude_compatible() {
        // Empty/minimal payload should default to Claude Compatible (safest).
        let json = r"{}";
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }
}