destructive_command_guard 0.5.4

An AI coding agent 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
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
//! Hook protocol handling.
//!
//! This module handles JSON input/output for supported hook protocols
//! (Claude Code, Codex CLI, Copilot, Gemini, and Hermes Agent). It parses
//! incoming hook requests and formats denial responses.

use crate::evaluator::MatchSpan;
use crate::highlight::HighlightSpan;
use crate::output::auto_theme;
use crate::output::denial::DenialBox;
use crate::output::theme::Severity as ThemeSeverity;
use crate::packs::PatternSuggestion;
use colored::Colorize;
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>,

    /// Codex CLI active-turn identifier. Documented in
    /// `codex-rs/hooks/src/schema.rs` as "Codex extension: expose the active
    /// turn id to internal turn-scoped hooks" -- i.e. Codex's intentional
    /// divergence from Claude's public hook docs. Claude Code does NOT send
    /// this field (Claude does send `tool_use_id`, so that field can't be
    /// used to disambiguate the two otherwise-similar wire formats). When
    /// `turn_id` is present and non-blank we switch to Codex's strict exit-2 + stderr
    /// deny path because Codex's JSON parser uses `deny_unknown_fields` and
    /// would silently drop dcg's standard hookSpecificOutput payload.
    #[serde(alias = "turnId")]
    pub turn_id: Option<String>,
}

/// 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>,
}

/// Hermes Agent denial output for shell `pre_tool_call` hooks.
///
/// Hermes documents two block-decision wire shapes — `{"decision": "block",
/// "reason": ...}` and `{"action": "block", "message": ...}` — and accepts
/// either. We emit the documented primary form (`decision` + `reason`) and
/// also include the alternate keys (`action` + `message`) for compatibility
/// with both codepaths. Hermes also explicitly notes that "non-zero exit
/// codes... never crash the agent", so blocking MUST come from the JSON
/// payload rather than the exit code.
///
/// Extra fields beyond `decision`/`action`/`reason`/`message` are tolerated
/// by Hermes' parser (no `deny_unknown_fields`), so we include the same
/// `ruleId` / `packId` / `severity` / `remediation` ergonomics as the
/// Claude / Gemini outputs.
///
/// See: <https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/hooks.md>
#[derive(Debug, Serialize)]
pub struct HermesHookOutput<'a> {
    /// Primary block decision keyword (Hermes accepts `"block"` or, for
    /// non-block events, anything truthy/falsy depending on event).
    pub decision: &'static str,

    /// Why the action was denied (paired with `decision`).
    pub reason: Cow<'a, str>,

    /// Alternate block-decision key documented by Hermes. We emit both forms
    /// so future Hermes versions that prefer one over the other still see a
    /// valid block.
    pub action: &'static str,

    /// Alternate human-readable message (paired with `action`).
    pub message: 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>,
}

/// Grok (xAI) denial output for `PreToolUse` hooks.
///
/// Grok documents one block-decision wire shape — `{"decision": "deny",
/// "reason": "..."}` — paired with exit code 0 or 2 (both block; other
/// exit codes are fail-open). dcg emits exit 0 plus the JSON payload so
/// the wire form alone is authoritative, matching the documented preferred
/// path.
///
/// Grok's hook input/output is permissive: extra fields beyond
/// `decision`/`reason` are tolerated, so we include the same `ruleId` /
/// `packId` / `severity` / `remediation` ergonomics fields as the Claude /
/// Gemini outputs for any tooling that wants to surface them.
///
/// See: `~/.grok/docs/user-guide/10-hooks.md`
#[derive(Debug, Serialize)]
pub struct GrokHookOutput<'a> {
    /// Block decision keyword. Grok requires `"deny"` (not `"block"`).
    pub decision: &'static str,

    /// Why the action was denied. Surfaced to the Grok user and the model.
    pub 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>,
}

/// Hook protocol variant for response formatting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HookProtocol {
    /// Claude Code / Augment-compatible `hookSpecificOutput` protocol.
    /// Tolerant JSON parser; accepts dcg's full deny payload with
    /// `allowOnceCode`, `ruleId`, `severity`, `remediation`, etc.
    ClaudeCompatible,
    /// Copilot hook protocol (`continue` / `stopReason` + permission fields).
    Copilot,
    /// Gemini hook protocol (`decision` / `reason`).
    Gemini,
    /// Codex CLI 0.125.0+ protocol. Wire shape mirrors Claude Code's, but
    /// Codex's JSON parser annotates every output struct with
    /// `#[serde(deny_unknown_fields)]` and silently treats any extra field
    /// as an invalid hook (the deny is dropped and the command runs).
    /// To make blocks stick we use Codex's documented "exit code 2 +
    /// stderr reason" alternative path: dcg writes its colored message
    /// to stderr (existing behavior) and the process exits with code 2.
    Codex,
    /// Hermes Agent (NousResearch) protocol. Wire shape: stdin carries
    /// snake_case `hook_event_name: "pre_tool_call"`, `tool_name: "terminal"`,
    /// `tool_input.command`. Block decision MUST be expressed via stdout JSON
    /// `{"decision": "block", "reason": ...}` (or `{"action": "block",
    /// "message": ...}`) — Hermes explicitly documents that non-zero exit
    /// codes "log a warning but never abort the agent loop". Hermes shares
    /// stdin envelope fields (`session_id`, `cwd`) with Claude/Gemini, so we
    /// disambiguate via the lowercase event name `"pre_tool_call"` and the
    /// distinctive `"terminal"` tool name.
    Hermes,
    /// xAI Grok CLI / Grok Build TUI protocol. Wire shape: stdin carries
    /// camelCase `hookEventName: "pre_tool_use"`, `sessionId`, `workspaceRoot`,
    /// `toolName: "run_terminal_cmd"`, `toolInput.command`. Block decision is
    /// expressed via stdout JSON `{"decision": "deny", "reason": "..."}`
    /// (note: `"deny"`, not `"block"` — distinct from Hermes). Grok also
    /// honors exit code 2 as an explicit deny, but per docs the JSON form is
    /// preferred and works with exit code 0. Other exit codes are fail-open
    /// (recorded but do not block). Grok's parser does NOT use
    /// `deny_unknown_fields`, so dcg's ergonomics fields (`ruleId`, `packId`,
    /// `severity`, `remediation`, …) pass through unmolested for any tooling
    /// that wants them. See `~/.grok/docs/user-guide/10-hooks.md`.
    Grok,
}

/// 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** (Claude-compatible shell tool names, 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();

    // --- Hermes Agent indicators (checked first) ---
    // Hermes uses two distinctive markers:
    //   - hook_event_name="pre_tool_call" (snake_case; Claude uses PascalCase
    //     "PreToolUse", Codex uses the same PascalCase form, Gemini uses
    //     "BeforeTool", Copilot uses "pre-tool-use" via the `event` field).
    //   - tool_name="terminal" (none of the other agents use this name).
    // Either signal alone is a strong Hermes indicator. We check Hermes
    // before Copilot because Copilot's `event`/`tool_args` markers can
    // co-occur with arbitrary tool names — but if we see a `terminal` tool
    // or `pre_tool_call` event without those Copilot markers, it's Hermes.
    let is_hermes_event = hook_event_name == "pre_tool_call";
    let is_hermes_tool = tool_name == "terminal";
    if is_hermes_event || is_hermes_tool {
        // Disambiguate: if Copilot's distinctive `event` (which is hyphenated
        // "pre-tool-use", not snake_case "pre_tool_call") or `tool_args` is
        // also present, prefer Copilot. But neither Hermes signal collides
        // with Copilot's signals, so this is just a defensive check.
        if input.event.is_none() && input.tool_args.is_none() {
            return HookProtocol::Hermes;
        }
    }

    // --- Grok (xAI) indicators (checked alongside Hermes) ---
    // Grok uses two distinctive markers in its hook stdin envelope:
    //   - hookEventName="pre_tool_use" (snake_case "use"; Hermes uses "call",
    //     Claude uses PascalCase "PreToolUse", Copilot uses hyphenated
    //     "pre-tool-use" but only via the `event` field — never via
    //     `hookEventName`).
    //   - toolName="run_terminal_cmd" (Grok's internal shell tool name).
    // Either signal alone is a strong Grok indicator. We deliberately do
    // NOT add a GROK_* env-var fallback: real Grok hook invocations always
    // emit both fields, so the wire-level check is sufficient, and an
    // env-var fallback would risk false positives when dcg is invoked from
    // a shell that happens to live inside a Grok session (e.g. running
    // `cargo test` from a Grok-spawned terminal).
    let is_grok_event = hook_event_name == "pre_tool_use";
    let is_grok_tool = tool_name == "run_terminal_cmd";
    if (is_grok_event || is_grok_tool) && input.event.is_none() && input.tool_args.is_none() {
        return HookProtocol::Grok;
    }

    // --- 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;
    }

    // --- Codex CLI indicators (checked before Claude Code) ---
    // Codex 0.125.0+ shares Claude Code's tool name and most envelope
    // fields, so we disambiguate via `turn_id`, which the codex source
    // explicitly documents as "Codex extension: expose the active turn id
    // to internal turn-scoped hooks" (codex-rs/hooks/src/schema.rs). Claude
    // Code does NOT send `turn_id`. (We can't use `tool_use_id` for this
    // because Claude Code's PreToolUse stdin includes it too.) We must
    // classify Codex separately because its JSON parser is strict
    // (`deny_unknown_fields`) and would silently drop dcg's standard deny
    // payload, letting the destructive command through.
    let is_claude_compatible_shell_tool = matches!(
        tool_name.as_str(),
        "bash" | "launch-process" | "powershell" | "pwsh"
    );
    let has_codex_turn_id = input
        .turn_id
        .as_deref()
        .is_some_and(|s| !s.trim().is_empty());
    if is_claude_compatible_shell_tool && has_codex_turn_id {
        return HookProtocol::Codex;
    }

    // --- Claude-compatible indicators ---
    // Claude Code uses tool_name="Bash" or "launch-process"; Codex-style
    // shell payloads can also use PowerShell names. These tool names are not
    // Gemini's shell tool names, so check them before Gemini envelope fields.
    // Claude Code payloads also include session_id/cwd/transcript_path, which
    // would otherwise trigger a false Gemini classification (issue #77).
    if is_claude_compatible_shell_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
}

pub(crate) 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"
            | "powershell"
            | "pwsh"
            | "run_shell_command"
            | "run-shell-command"
            // Hermes Agent shell tool. Distinct from Cursor's "terminal"
            // wrapper script which translates upstream to "Bash" before
            // invoking dcg, so the only path here is genuine Hermes input.
            | "terminal"
            // Grok (xAI) shell tool. Grok aliases Claude-style "Bash" to its
            // internal name `run_terminal_cmd` before invoking hooks, so the
            // toolName field on the wire is always this canonical form.
            | "run_terminal_cmd"
    )
}

pub(crate) fn is_shell_hook_candidate(input: &HookInput) -> bool {
    if is_supported_shell_tool(input.tool_name.as_deref()) {
        return true;
    }

    input.tool_name.is_none()
        && matches!(detect_protocol(input), HookProtocol::Copilot)
        && (input.tool_input.is_some() || input.tool_args.is_some())
}

fn extract_command_from_tool_input(tool_input: &ToolInput) -> Option<String> {
    match tool_input.command.as_ref() {
        Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s.clone()),
        _ => None,
    }
}

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)> {
    let protocol = detect_protocol(input);

    // Only process shell-command invocations for supported clients. Copilot
    // can omit toolName and put the shell command directly in toolArgs, so
    // treat that distinctive envelope as a shell candidate too.
    if !is_shell_hook_candidate(input) {
        return None;
    }

    if let Some(tool_input) = input.tool_input.as_ref() {
        if let Some(command) = extract_command_from_tool_input(tool_input) {
            return Some((command, 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() || crate::output::env_flag_enabled("DCG_NO_COLOR") {
        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;

/// Write a colorful denial warning to an arbitrary writer (test seam).
#[allow(clippy::too_many_lines)]
pub(crate) fn print_colorful_warning_to(
    writer: &mut impl Write,
    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>,
    branch_context: Option<&crate::evaluator::BranchContext>,
    audience: WarningAudience,
) {
    let theme = auto_theme();

    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());

    let span = matched_span
        .map(|s| HighlightSpan::new(s.start, s.end))
        .unwrap_or_else(|| HighlightSpan::new(0, 0));

    let alternatives = pattern_suggestion_alternatives(
        command,
        crate::output::suggestions_enabled(),
        pattern_suggestions,
    );

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

    if let (Some(pack_id), Some(pattern_name)) = (pack, pattern) {
        if let Some(regex) = crate::highlight::find_pattern_regex(pack_id, pattern_name) {
            denial = denial.with_pattern_regex(regex);
        }
    }

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

    if audience == WarningAudience::HumanOperator
        && let Some(code) = allow_once_code
    {
        denial = denial.with_allow_once_code(code);
    }

    if let Some(ctx) = branch_context {
        if let Some(name) = &ctx.branch_name {
            denial = denial.with_branch_context(name, ctx.is_protected);
        }
    }

    let _ = writeln!(writer, "{}", denial.render(&theme));

    let escaped_cmd = command.replace('"', "\\\"");
    let truncated_cmd = truncate_for_display(&escaped_cmd, 45);
    let explain_cmd = format!("dcg explain \"{truncated_cmd}\"");

    let footer_style = if theme.colors_enabled { "\x1b[90m" } else { "" };
    let reset = if theme.colors_enabled { "\x1b[0m" } else { "" };
    let cyan = if theme.colors_enabled { "\x1b[36m" } else { "" };

    match audience {
        WarningAudience::HumanOperator => {
            let _ = writeln!(writer, "{footer_style}Learn more:{reset}");
            let _ = writeln!(writer, "  $ {cyan}{explain_cmd}{reset}");

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

            let _ = writeln!(writer);
            let _ = writeln!(
                writer,
                "{footer_style}False positive? File an issue:{reset}"
            );
            let _ = writeln!(
                writer,
                "{footer_style}https://github.com/Dicklesworthstone/destructive_command_guard/issues/new?template=false_positive.yml{reset}"
            );
            let _ = writeln!(writer);
        }
        WarningAudience::CodexModel => {
            if let Some(ref rule) = rule_id {
                let _ = writeln!(writer, "{footer_style}Rule: {rule}{reset}");
            }
            let _ = writeln!(
                writer,
                "{footer_style}This command is blocked. Do not retry it, create a bypass, or change dcg policy yourself. Ask the user for explicit permission if the operation is truly required.{reset}"
            );
            let _ = writeln!(writer);
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum WarningAudience {
    HumanOperator,
    CodexModel,
}

fn pattern_suggestion_alternatives(
    command: &str,
    suggestions_enabled: bool,
    pattern_suggestions: &[PatternSuggestion],
) -> Vec<String> {
    if !suggestions_enabled {
        return Vec::new();
    }

    let mut alternatives: Vec<String> = pattern_suggestions
        .iter()
        .filter(|suggestion| suggestion.platform.matches_current())
        .take(MAX_SUGGESTIONS)
        .map(|suggestion| format!("{}: {}", suggestion.description, suggestion.command))
        .collect();

    if alternatives.is_empty() {
        if let Some(suggestion) = get_contextual_suggestion(command) {
            alternatives.push(suggestion.to_string());
        }
    }

    alternatives
}

/// 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>,
) {
    let stderr = io::stderr();
    let mut handle = stderr.lock();
    print_colorful_warning_to(
        &mut handle,
        command,
        reason,
        pack,
        pattern,
        explanation,
        allow_once_code,
        matched_span,
        pattern_suggestions,
        severity,
        None,
        WarningAudience::HumanOperator,
    );
}

/// 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
    }
}

/// Write a denial response to arbitrary stdout/stderr writers.
///
/// This is public so integration tests and Criterion benchmarks can exercise
/// protocol formatting without touching process stdout/stderr.
#[cold]
#[inline(never)]
#[allow(clippy::too_many_arguments)]
pub fn write_denial_to(
    stdout: &mut impl Write,
    stderr: &mut impl Write,
    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],
    branch_context: Option<&crate::evaluator::BranchContext>,
) {
    let allow_once_code = allow_once.map(|info| info.code.as_str());
    let warning_audience = match protocol {
        HookProtocol::Codex => WarningAudience::CodexModel,
        HookProtocol::ClaudeCompatible
        | HookProtocol::Copilot
        | HookProtocol::Gemini
        | HookProtocol::Hermes
        | HookProtocol::Grok => WarningAudience::HumanOperator,
    };

    print_colorful_warning_to(
        stderr,
        command,
        reason,
        pack,
        pattern,
        explanation,
        allow_once_code,
        matched_span,
        pattern_suggestions,
        severity,
        branch_context,
        warning_audience,
    );

    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),
        }
    });

    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 *stdout, &output);
            let _ = writeln!(stdout);
        }
        HookProtocol::Codex => {
            // Codex 0.125.0+: exit code 2 + stderr reason. The colored
            // stderr message was already written above; main.rs propagates
            // exit code 2 when this protocol is active. No stdout JSON.
        }
        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 *stdout, &output);
            let _ = writeln!(stdout);
        }
        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 *stdout, &output);
            let _ = writeln!(stdout);
        }
        HookProtocol::Hermes => {
            // Hermes uses the keyword "block" (not "deny") and accepts both
            // {"decision":"block","reason":...} and {"action":"block",
            // "message":...}. We emit both pairs so either Hermes codepath
            // sees a valid block, plus the dcg-specific ergonomics fields
            // (Hermes' parser does NOT use `deny_unknown_fields`, so the
            // extras pass through unmolested for any tooling that wants
            // them).
            let output = HermesHookOutput {
                decision: "block",
                reason: Cow::Owned(message.clone()),
                action: "block",
                message: Cow::Owned(message),
                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 *stdout, &output);
            let _ = writeln!(stdout);
        }
        HookProtocol::Grok => {
            // Grok requires the keyword "deny" (not "block"). Exit code 0 +
            // JSON is the documented preferred path and Grok will block on
            // that alone. Other exit codes are fail-open, so we deliberately
            // avoid relying on the exit code here. The colored deny message
            // has already been written to stderr for human/model visibility.
            let output = GrokHookOutput {
                decision: "deny",
                reason: Cow::Owned(message),
                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 *stdout, &output);
            let _ = writeln!(stdout);
        }
    }
}

/// 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],
    branch_context: Option<&crate::evaluator::BranchContext>,
) {
    let out = io::stdout();
    let mut out_handle = out.lock();
    let err = io::stderr();
    let mut err_handle = err.lock();
    write_denial_to(
        &mut out_handle,
        &mut err_handle,
        protocol,
        command,
        reason,
        pack,
        pattern,
        explanation,
        allow_once,
        matched_span,
        severity,
        confidence,
        pattern_suggestions,
        branch_context,
    );
}

/// 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,
        None,
    );
}

/// Write a warning response to arbitrary stdout/stderr writers (test seam).
#[cold]
#[inline(never)]
pub(crate) fn write_warning_to(
    stdout: &mut impl Write,
    stderr: &mut impl Write,
    protocol: HookProtocol,
    command: &str,
    reason: &str,
    pack: Option<&str>,
    pattern: Option<&str>,
    explanation: Option<&str>,
) {
    // -- stderr: human-visible warning --
    {
        let _ = writeln!(stderr);
        let _ = writeln!(stderr, "{} {}", "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!(stderr, "  {} {}", "Explanation:".bright_black(), first);
            for line in explanation_lines {
                let _ = writeln!(stderr, "               {line}");
            }
        }

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

        let _ = writeln!(stderr, "  {} {}", "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}");

    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 *stdout, &output);
            let _ = writeln!(stdout);
        }
        HookProtocol::Copilot => {
            // Warnings should ask/surface policy context without using the
            // legacy stop signal. Hard denials set `continue=false` above.
            let output = CopilotHookOutput {
                continue_execution: true,
                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 *stdout, &output);
            let _ = writeln!(stdout);
        }
        HookProtocol::Gemini => {
            // Gemini hooks support allow/deny only. Preserve dcg warn as
            // non-blocking while still surfacing the warning text to Gemini.
            let output = GeminiHookOutput {
                decision: "allow",
                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 *stdout, &output);
            let _ = writeln!(stdout);
        }
        HookProtocol::Codex => {
            // Codex: stderr warning already written above; no stdout JSON.
        }
        HookProtocol::Hermes => {
            // Hermes hooks support a "block" decision but no documented
            // "ask" or "warn" decision. Surface dcg warnings to the user via
            // the documented `context` field (which `pre_llm_call` consumes
            // verbatim) AND keep the run going. For pre_tool_call, an empty
            // {} response means "no opinion, proceed normally", so we emit
            // {"context": "<warn message>"} which is structurally valid in
            // both events while preserving the warning text for any tooling
            // that surfaces context fields.
            #[derive(Serialize)]
            struct HermesWarningOutput<'a> {
                context: Cow<'a, str>,
            }
            let output = HermesWarningOutput {
                context: Cow::Owned(warn_reason),
            };
            let _ = serde_json::to_writer(&mut *stdout, &output);
            let _ = writeln!(stdout);
        }
        HookProtocol::Grok => {
            // Grok hooks support `{"decision":"allow"}` and `{"decision":
            // "deny"}` but no documented "ask"/"warn" decision. Preserve dcg
            // warn semantics as non-blocking by emitting an explicit "allow"
            // (Grok's docs note that explicit allow short-circuits later
            // hooks; for dcg this is the safe choice because we never want
            // a warn to escalate to a deny later). The warning text is
            // preserved via the optional `reason` field, which Grok logs in
            // the hooks scrollback even on allow decisions.
            let output = GrokHookOutput {
                decision: "allow",
                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 *stdout, &output);
            let _ = writeln!(stdout);
        }
    }
}

/// Output a warning for a warn-severity match.
#[cold]
#[inline(never)]
pub fn output_warning_for_protocol(
    protocol: HookProtocol,
    command: &str,
    reason: &str,
    pack: Option<&str>,
    pattern: Option<&str>,
    explanation: Option<&str>,
) {
    let out = io::stdout();
    let mut out_handle = out.lock();
    let err = io::stderr();
    let mut err_handle = err.lock();
    write_warning_to(
        &mut out_handle,
        &mut err_handle,
        protocol,
        command,
        reason,
        pack,
        pattern,
        explanation,
    );
}

/// 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_codex_protocol_detected_via_turn_id() {
        // Codex 0.125.0+ stdin: same Bash tool name as Claude Code, but
        // codex-rs/hooks/src/schema.rs annotates `turn_id` as "Codex
        // extension: expose the active turn id to internal turn-scoped
        // hooks". Claude Code does not send turn_id, so its presence on a
        // Bash payload is the disambiguator.
        let json = r#"{
            "session_id":"019dd11d-b795-7261-a9cb-9b85a5dad632",
            "turn_id":"turn-1",
            "transcript_path":null,
            "cwd":"/tmp/x",
            "hook_event_name":"PreToolUse",
            "model":"gpt-5.5",
            "permission_mode":"bypassPermissions",
            "tool_name":"Bash",
            "tool_input":{"command":"git reset --hard"},
            "tool_use_id":"call_abc123"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Codex);
        assert_eq!(
            extract_command(&input),
            Some("git reset --hard".to_string())
        );
    }

    #[test]
    fn test_empty_turn_id_is_not_treated_as_codex() {
        // Defense in depth: only a non-empty turn_id flips us into Codex
        // mode. A literal empty string from a malformed client should fall
        // through to the Claude-compatible default rather than silently
        // dropping our deny payload.
        let json = r#"{
            "tool_name":"Bash",
            "tool_input":{"command":"git status"},
            "turn_id":""
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }

    #[test]
    fn test_claude_code_with_tool_use_id_is_not_codex() {
        // Regression guard: Claude Code's PreToolUse stdin includes
        // `tool_use_id` (per code.claude.com/docs/en/hooks). A naive
        // disambiguator that keyed on tool_use_id would mis-classify Claude
        // Code as Codex and drop our full deny payload from stdout, which
        // would let destructive commands through. Detection must use
        // turn_id (Codex-only), so this Claude-shaped payload that has
        // tool_use_id but NOT turn_id stays Claude-compatible.
        let json = r#"{
            "session_id":"abc123",
            "transcript_path":"/home/user/.claude/projects/x/transcript.jsonl",
            "cwd":"/home/user/my-project",
            "permission_mode":"default",
            "hook_event_name":"PreToolUse",
            "tool_name":"Bash",
            "tool_input":{"command":"git status"},
            "tool_use_id":"toolu_01ABC"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }

    #[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_copilot_powershell_tool_args_object() {
        // GitHub Copilot CLI documents "powershell" as its Windows shell tool
        // name. It must be treated as a shell-command hook, not ignored as a
        // non-shell tool.
        let json = r#"{"event":"pre-tool-use","toolName":"powershell","toolArgs":{"command":"git reset --hard"}}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
        assert_eq!(
            extract_command(&input),
            Some("git reset --hard".to_string())
        );
    }

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

    #[test]
    fn test_parse_copilot_tool_args_without_tool_name() {
        let json = r#"{"event":"pre-tool-use","toolArgs":"{\"command\":\"git reset --hard\"}"}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
        assert_eq!(
            extract_command(&input),
            Some("git reset --hard".to_string())
        );
    }

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

    #[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: true,
            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"], true);
    }

    #[test]
    fn test_gemini_warn_allow_json_shape() {
        let output = GeminiHookOutput {
            decision: "allow",
            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"], "allow");
        assert!(json["reason"].as_str().unwrap().starts_with("DCG warn:"));
    }

    // =========================================================================
    // Hermes Agent (NousResearch) protocol tests — issue #110.
    // =========================================================================

    #[test]
    fn test_parse_hermes_pre_tool_call_input() {
        // Exact wire shape documented at
        // https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/features/hooks.md
        let json = r#"{
            "hook_event_name":"pre_tool_call",
            "tool_name":"terminal",
            "tool_input":{"command":"rm -rf /"},
            "session_id":"sess_abc123",
            "cwd":"/home/user/project",
            "extra":{"task_id":"task-1","tool_call_id":"call-1"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(extract_command(&input), Some("rm -rf /".to_string()));
        assert_eq!(detect_protocol(&input), HookProtocol::Hermes);
    }

    #[test]
    fn test_hermes_detected_via_event_alone() {
        // pre_tool_call is the unique snake_case event name; even with a
        // non-Hermes-shaped tool name we still classify Hermes since no
        // other supported agent uses this event marker.
        let json = r#"{
            "hook_event_name":"pre_tool_call",
            "tool_name":"bash",
            "tool_input":{"command":"git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Hermes);
    }

    #[test]
    fn test_hermes_detected_via_terminal_tool_alone() {
        // tool_name="terminal" without an event field is still Hermes — no
        // other supported agent uses the literal string "terminal".
        let json = r#"{
            "tool_name":"terminal",
            "tool_input":{"command":"echo hi"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Hermes);
    }

    #[test]
    fn test_hermes_loses_to_copilot_when_event_field_present() {
        // If the Copilot-specific `event` field is present, we should
        // NOT misclassify as Hermes — Copilot's payloads can name their
        // own tools, and we must keep dispatching to Copilot's wire format.
        let json = r#"{
            "event":"pre-tool-use",
            "hook_event_name":"pre_tool_call",
            "tool_name":"terminal",
            "tool_input":{"command":"git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
    }

    #[test]
    fn test_hermes_loses_to_copilot_when_tool_args_present() {
        // tool_args is Copilot-distinctive; if it's present, route to
        // Copilot regardless of the Hermes-shaped event/tool name.
        let json = r#"{
            "hook_event_name":"pre_tool_call",
            "tool_name":"terminal",
            "tool_args":"{\"command\":\"git status\"}"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
    }

    #[test]
    fn test_hermes_pre_tool_call_with_session_envelope_not_gemini() {
        // Hermes shares `session_id`/`cwd` with Gemini, but the snake_case
        // event name disambiguates. Regression coverage in the spirit of
        // issue #77 (Claude/Gemini overlap).
        let json = r#"{
            "session_id":"sess",
            "cwd":"/tmp",
            "hook_event_name":"pre_tool_call",
            "tool_name":"terminal",
            "tool_input":{"command":"ls"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Hermes);
    }

    #[test]
    fn test_hermes_hook_output_block_decision_json_shape() {
        // The struct must serialize with "decision":"block" AND
        // "action":"block" so either Hermes codepath registers a block.
        let output = HermesHookOutput {
            decision: "block",
            reason: Cow::Borrowed("blocked for safety"),
            action: "block",
            message: Cow::Borrowed("blocked for safety"),
            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"], "block");
        assert_eq!(json["reason"], "blocked for safety");
        assert_eq!(json["action"], "block");
        assert_eq!(json["message"], "blocked for safety");
        assert_eq!(json["ruleId"], "core.git:reset-hard");
        assert_eq!(json["packId"], "core.git");
        // Hermes rejects "deny"/"continue"/"stopReason" — those are the
        // wire shapes for OTHER agents and would be ignored here.
        assert!(json.get("permissionDecision").is_none());
        assert!(json.get("continue").is_none());
        assert!(json.get("hookSpecificOutput").is_none());
    }

    #[test]
    fn test_write_denial_hermes_produces_block_json() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_denial_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Hermes,
            "rm -rf /",
            "catastrophic filesystem deletion",
            Some("core.filesystem"),
            Some("rm-rf-root"),
            None,
            None,
            None,
            Some(crate::packs::Severity::Critical),
            None,
            &[],
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        assert_eq!(json["decision"], "block");
        assert_eq!(json["action"], "block");
        assert!(
            json["reason"]
                .as_str()
                .unwrap()
                .contains("catastrophic filesystem deletion")
        );
        assert!(
            json["message"]
                .as_str()
                .unwrap()
                .contains("catastrophic filesystem deletion")
        );
        // stderr must contain the colored warning text for human visibility.
        assert!(
            !stderr.is_empty(),
            "Hermes denial must still surface stderr warning text"
        );
    }

    #[test]
    fn test_write_warning_hermes_produces_context_json() {
        // Hermes has no documented "ask" / "warn" decision. We surface the
        // warn text via the documented `context` field which is allowed
        // for any pre_* event and treated as advisory metadata.
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_warning_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Hermes,
            "git stash drop",
            "drops stashed changes",
            Some("core.git"),
            Some("stash-drop"),
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        assert!(json["context"].as_str().unwrap().starts_with("DCG warn:"));
        // Crucially: must NOT carry a "block" decision when warning.
        assert!(json.get("decision").is_none());
        assert!(json.get("action").is_none());
        assert!(!stderr.is_empty(), "stderr must contain warn text");
    }

    // =========================================================================
    // Grok (xAI) protocol detection + denial / warning JSON shape.
    //
    // Grok's wire shape and JSON contract are documented in
    // ~/.grok/docs/user-guide/10-hooks.md. The critical invariants:
    //   - hookEventName="pre_tool_use" (snake_case; distinct from Hermes
    //     "pre_tool_call" and Claude's PascalCase "PreToolUse").
    //   - toolName="run_terminal_cmd" (Grok's internal shell tool).
    //   - Block decision: {"decision":"deny","reason":...} — note "deny",
    //     NOT "block" (Hermes uses "block").
    //   - Allow / passive: {"decision":"allow"} or empty {}; exit 0 expected.
    // =========================================================================

    #[test]
    fn test_grok_detected_via_event_alone() {
        // pre_tool_use is unique to Grok; even with a generic toolName we
        // must still route to the Grok protocol.
        let json = r#"{
            "hookEventName":"pre_tool_use",
            "toolName":"bash",
            "toolInput":{"command":"git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Grok);
    }

    #[test]
    fn test_grok_detected_via_run_terminal_cmd_tool_alone() {
        // run_terminal_cmd is Grok's internal shell tool name; no other
        // supported agent uses it. Even without hookEventName we route to
        // Grok.
        let json = r#"{
            "toolName":"run_terminal_cmd",
            "toolInput":{"command":"echo hi"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Grok);
    }

    #[test]
    fn test_grok_full_envelope_camelcase() {
        // Realistic Grok payload, every documented field present.
        let json = r#"{
            "hookEventName":"pre_tool_use",
            "sessionId":"sess-abc",
            "cwd":"/home/user/proj",
            "workspaceRoot":"/home/user/proj",
            "toolName":"run_terminal_cmd",
            "toolInput":{"command":"rm -rf /"},
            "timestamp":"2026-05-14T12:00:00Z"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Grok);
    }

    #[test]
    fn test_grok_loses_to_copilot_when_event_field_present() {
        // The Copilot-specific `event` field wins over Grok's hookEventName,
        // matching the Hermes guard. Copilot can ship its own tool names.
        let json = r#"{
            "event":"pre-tool-use",
            "hookEventName":"pre_tool_use",
            "toolName":"run_terminal_cmd",
            "toolInput":{"command":"git status"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
    }

    #[test]
    fn test_grok_loses_to_copilot_when_tool_args_present() {
        let json = r#"{
            "hookEventName":"pre_tool_use",
            "toolName":"run_terminal_cmd",
            "toolArgs":"{\"command\":\"git status\"}"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
    }

    #[test]
    fn test_grok_event_does_not_misroute_to_hermes() {
        // Regression guard: "pre_tool_use" must NOT match Hermes's
        // "pre_tool_call". The strings differ by one letter at the end.
        let json = r#"{
            "hook_event_name":"pre_tool_use",
            "tool_name":"run_terminal_cmd",
            "tool_input":{"command":"ls"}
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Grok);
    }

    #[test]
    fn test_grok_hook_output_deny_decision_json_shape() {
        // The wire shape must be EXACTLY {"decision":"deny","reason":...}
        // — Grok's parser will silently drop the block on "block"/"deny" mismatch.
        let output = GrokHookOutput {
            decision: "deny",
            reason: Cow::Borrowed("blocked for safety"),
            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["ruleId"], "core.git:reset-hard");
        assert_eq!(json["packId"], "core.git");
        // Must NOT carry other agents' decision keys.
        assert!(json.get("action").is_none(), "no Hermes 'action'");
        assert!(json.get("message").is_none(), "no Hermes 'message'");
        assert!(
            json.get("permissionDecision").is_none(),
            "no Claude 'permissionDecision'"
        );
        assert!(
            json.get("hookSpecificOutput").is_none(),
            "no Claude 'hookSpecificOutput'"
        );
        assert!(json.get("continue").is_none(), "no Copilot 'continue'");
    }

    #[test]
    fn test_write_denial_grok_produces_deny_json() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_denial_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Grok,
            "rm -rf /",
            "catastrophic filesystem deletion",
            Some("core.filesystem"),
            Some("rm-rf-root"),
            None,
            None,
            None,
            Some(crate::packs::Severity::Critical),
            None,
            &[],
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        assert_eq!(json["decision"], "deny");
        assert!(
            json["reason"]
                .as_str()
                .unwrap()
                .contains("catastrophic filesystem deletion"),
            "reason must surface the human-readable explanation, got: {}",
            json["reason"]
        );
        // Grok must NOT emit Hermes-style or Claude-style fields.
        assert!(json.get("action").is_none());
        assert!(json.get("message").is_none());
        assert!(json.get("hookSpecificOutput").is_none());
        // stderr must still carry the colored warning text for human/model visibility.
        assert!(
            !stderr.is_empty(),
            "Grok denial must still surface stderr warning text"
        );
    }

    #[test]
    fn test_write_warning_grok_produces_allow_with_reason() {
        // Grok has no "ask"/"warn" decision. We emit an explicit allow so the
        // tool call proceeds, with the warning text preserved in `reason`.
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_warning_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Grok,
            "git stash drop",
            "drops stashed changes",
            Some("core.git"),
            Some("stash-drop"),
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        assert_eq!(
            json["decision"], "allow",
            "warn must NOT escalate to deny on Grok"
        );
        assert!(
            json["reason"].as_str().unwrap().starts_with("DCG warn:"),
            "reason should be prefixed so the model knows this is advisory"
        );
        assert!(!stderr.is_empty(), "stderr must contain warn text");
    }

    #[test]
    fn test_grok_run_terminal_cmd_recognized_as_shell_tool() {
        // is_supported_shell_tool() must know about Grok's tool name so the
        // command is actually evaluated rather than skipped.
        assert!(is_supported_shell_tool(Some("run_terminal_cmd")));
        assert!(is_supported_shell_tool(Some("RUN_TERMINAL_CMD")));
    }

    #[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);
    }

    // =========================================================================
    // Writer-injected output tests (P1.1 — Codex coverage)
    // =========================================================================

    fn test_allow_once() -> AllowOnceInfo {
        AllowOnceInfo {
            code: "abc123".to_string(),
            full_hash: "sha256:deadbeef".to_string(),
        }
    }

    #[test]
    fn test_write_denial_claude_produces_valid_json_on_stdout() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let allow = test_allow_once();

        write_denial_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::ClaudeCompatible,
            "git reset --hard HEAD~1",
            "destroys uncommitted changes",
            Some("core.git"),
            Some("reset-hard"),
            Some("Rewrites history and discards uncommitted changes."),
            Some(&allow),
            None,
            Some(crate::packs::Severity::Critical),
            Some(0.95),
            &[],
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout bytes: {stdout_str}"));

        let specific = &json["hookSpecificOutput"];
        assert_eq!(specific["permissionDecision"], "deny");
        assert_eq!(specific["hookEventName"], "PreToolUse");
        assert_eq!(specific["ruleId"], "core.git:reset-hard");
        assert_eq!(specific["packId"], "core.git");
        assert_eq!(specific["allowOnceCode"], "abc123");
        assert!(!stderr.is_empty(), "stderr must contain colorful warning");
    }

    #[test]
    fn test_pattern_suggestion_alternatives_formats_platform_matches() {
        let suggestions = [
            PatternSuggestion::new("git stash", "Save uncommitted changes"),
            PatternSuggestion::new("git clean -n", "Preview untracked file cleanup"),
        ];

        let alternatives = pattern_suggestion_alternatives("git reset --hard", true, &suggestions);

        assert_eq!(
            alternatives,
            vec![
                "Save uncommitted changes: git stash",
                "Preview untracked file cleanup: git clean -n"
            ]
        );
    }

    #[test]
    fn test_pattern_suggestion_alternatives_respects_disable_flag() {
        let suggestions = [PatternSuggestion::new(
            "git stash",
            "Save uncommitted changes",
        )];

        let alternatives = pattern_suggestion_alternatives("git reset --hard", false, &suggestions);

        assert!(alternatives.is_empty());
    }

    #[test]
    fn test_pattern_suggestion_alternatives_falls_back_to_contextual() {
        let alternatives = pattern_suggestion_alternatives("git clean -fd", true, &[]);

        assert_eq!(
            alternatives,
            vec!["Use 'git clean -n' first to preview what would be deleted."]
        );
    }

    #[test]
    fn test_pattern_suggestion_alternatives_limits_display_count() {
        let suggestions = [
            PatternSuggestion::new("cmd1", "one"),
            PatternSuggestion::new("cmd2", "two"),
            PatternSuggestion::new("cmd3", "three"),
            PatternSuggestion::new("cmd4", "four"),
            PatternSuggestion::new("cmd5", "five"),
        ];

        let alternatives = pattern_suggestion_alternatives("rm -rf /tmp/x", true, &suggestions);

        assert_eq!(alternatives.len(), MAX_SUGGESTIONS);
        assert!(alternatives.iter().any(|item| item == "one: cmd1"));
        assert!(!alternatives.iter().any(|item| item == "five: cmd5"));
    }

    #[test]
    fn test_write_denial_codex_produces_empty_stdout() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let allow = test_allow_once();

        write_denial_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Codex,
            "git reset --hard HEAD~1",
            "destroys uncommitted changes",
            Some("core.git"),
            Some("reset-hard"),
            Some("Rewrites history."),
            Some(&allow),
            None,
            Some(crate::packs::Severity::Critical),
            Some(0.95),
            &[],
            None,
        );

        assert!(
            stdout.is_empty(),
            "Codex deny must produce zero bytes on stdout; got {} bytes: {:?}",
            stdout.len(),
            String::from_utf8_lossy(&stdout)
        );
        assert!(
            !stderr.is_empty(),
            "Codex deny must produce non-empty stderr"
        );
        let stderr_str = String::from_utf8_lossy(&stderr);
        assert!(
            stderr_str.contains("git reset --hard HEAD~1"),
            "stderr must contain the blocked command; got: {stderr_str}"
        );
        assert!(
            stderr_str.contains("core.git:reset-hard"),
            "stderr must contain the rule id for agent parsing; got: {stderr_str}"
        );
        assert!(
            stderr_str.contains("Rule: core.git:reset-hard"),
            "Codex stderr must expose the full rule id as a parseable footer; got: {stderr_str}"
        );
        assert!(
            !stderr_str.contains("dcg allowlist add"),
            "Codex stderr must not teach the model to self-allowlist; got: {stderr_str}"
        );
        assert!(
            !stderr_str.contains("dcg allow-once") && !stderr_str.contains("abc123"),
            "Codex stderr must not expose allow-once bypass details; got: {stderr_str}"
        );
        assert!(
            stderr_str.contains("Do not retry it, create a bypass, or change dcg policy yourself"),
            "Codex stderr should give an explicit no-bypass instruction; got: {stderr_str}"
        );
    }

    #[test]
    fn test_write_denial_copilot_produces_valid_json_on_stdout() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_denial_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Copilot,
            "rm -rf /",
            "catastrophic filesystem deletion",
            Some("core.filesystem"),
            Some("rm-rf-root"),
            None,
            None,
            None,
            Some(crate::packs::Severity::Critical),
            None,
            &[],
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        assert_eq!(json["continue"], false);
        assert_eq!(json["permissionDecision"], "deny");
        assert!(
            json["stopReason"]
                .as_str()
                .unwrap()
                .contains("BLOCKED by dcg")
        );
    }

    #[test]
    fn test_write_denial_gemini_produces_valid_json_on_stdout() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_denial_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Gemini,
            "git clean -fd",
            "removes untracked files",
            Some("core.git"),
            Some("clean-force"),
            None,
            None,
            None,
            Some(crate::packs::Severity::High),
            None,
            &[],
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        assert_eq!(json["decision"], "deny");
        assert!(
            json["systemMessage"]
                .as_str()
                .unwrap()
                .contains("BLOCKED by dcg")
        );
    }

    #[test]
    fn test_write_warning_claude_produces_ask_json() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_warning_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::ClaudeCompatible,
            "git checkout -- file.txt",
            "may discard local changes",
            Some("core.git"),
            Some("checkout-dot"),
            Some("Check git diff first."),
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        let specific = &json["hookSpecificOutput"];
        assert_eq!(specific["permissionDecision"], "ask");
        assert!(
            specific["permissionDecisionReason"]
                .as_str()
                .unwrap()
                .starts_with("DCG warn:")
        );
        assert!(!stderr.is_empty(), "stderr must contain warning text");
    }

    #[test]
    fn test_write_warning_codex_produces_empty_stdout() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_warning_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Codex,
            "git checkout -- file.txt",
            "may discard local changes",
            Some("core.git"),
            Some("checkout-dot"),
            None,
        );

        assert!(
            stdout.is_empty(),
            "Codex warn must produce zero bytes on stdout; got {} bytes: {:?}",
            stdout.len(),
            String::from_utf8_lossy(&stdout)
        );
        assert!(
            !stderr.is_empty(),
            "Codex warn must produce non-empty stderr"
        );
        let stderr_str = String::from_utf8_lossy(&stderr);
        assert!(
            stderr_str.contains("WARNING"),
            "stderr must contain WARNING marker; got: {stderr_str}"
        );
        assert!(
            stderr_str.contains("core.git:checkout-dot"),
            "stderr must contain rule id; got: {stderr_str}"
        );
    }

    #[test]
    fn test_write_warning_copilot_produces_ask_json() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_warning_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Copilot,
            "git stash drop",
            "drops stashed changes",
            Some("core.git"),
            Some("stash-drop"),
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        assert_eq!(json["permissionDecision"], "ask");
        assert_eq!(json["continue"], true);
    }

    #[test]
    fn test_write_warning_gemini_produces_allow_json() {
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        write_warning_to(
            &mut stdout,
            &mut stderr,
            HookProtocol::Gemini,
            "git stash drop",
            "drops stashed changes",
            Some("core.git"),
            Some("stash-drop"),
            None,
        );

        let stdout_str = String::from_utf8_lossy(&stdout);
        let json: serde_json::Value = serde_json::from_str(stdout_str.trim())
            .unwrap_or_else(|e| panic!("stdout not valid JSON: {e}\nstdout: {stdout_str}"));

        assert_eq!(json["decision"], "allow");
        assert!(json["reason"].as_str().unwrap().starts_with("DCG warn:"));
    }

    // =========================================================================
    // detect_protocol negative-space coverage (P1.4)
    // =========================================================================

    #[test]
    fn test_detect_protocol_non_shell_tool_with_turn_id_is_not_codex() {
        // Non-shell tool_name must not flip to Codex even with turn_id.
        let json = r#"{"tool_name":"Read","tool_input":{},"turn_id":"turn-1"}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }

    #[test]
    fn test_detect_protocol_launch_process_with_turn_id_is_codex() {
        // launch-process is a valid shell tool for Codex.
        let json =
            r#"{"tool_name":"launch-process","tool_input":{"command":"ls"},"turn_id":"turn-2"}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Codex);
    }

    #[test]
    fn test_detect_protocol_powershell_with_turn_id_is_codex() {
        let json = r#"{"tool_name":"powershell","tool_input":{"command":"git status"},"turn_id":"turn-ps"}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Codex);
    }

    #[test]
    fn test_detect_protocol_whitespace_only_turn_id_is_not_codex() {
        // A whitespace-only turn_id is malformed and should behave like a
        // missing turn_id instead of forcing Codex's stderr-only protocol.
        let json = r#"{"tool_name":"Bash","tool_input":{"command":"ls"},"turn_id":"   "}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }

    #[test]
    fn test_detect_protocol_uppercase_bash_with_turn_id_is_codex() {
        // tool_name is lowercased before comparison; "BASH" should match.
        let json = r#"{"tool_name":"BASH","tool_input":{"command":"ls"},"turn_id":"turn-3"}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Codex);
    }

    #[test]
    fn test_detect_protocol_lowercase_bash_with_turn_id_is_codex() {
        // Lowercase wire form from Codex.
        let json = r#"{"tool_name":"bash","tool_input":{"command":"ls"},"turn_id":"turn-4"}"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Codex);
    }

    #[test]
    fn test_detect_protocol_copilot_event_overrides_turn_id() {
        // Copilot event check fires before Codex turn_id check.
        let json = r#"{
            "event":"pre-tool-use",
            "tool_name":"bash",
            "tool_input":{"command":"ls"},
            "turn_id":"turn-5"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Copilot);
    }

    #[test]
    fn test_detect_protocol_gemini_envelope_overrides_turn_id() {
        // Gemini's (run_shell_command + BeforeTool) signal is stronger than
        // turn_id because the Codex check only fires for bash/launch-process.
        let json = r#"{
            "hook_event_name":"BeforeTool",
            "tool_name":"run_shell_command",
            "tool_input":{"command":"ls"},
            "turn_id":"turn-6"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::Gemini);
    }

    #[test]
    fn test_detect_protocol_bash_tool_use_id_no_turn_id_is_claude() {
        // Regression: tool_use_id alone must not trigger Codex path.
        let json = r#"{
            "tool_name":"Bash",
            "tool_input":{"command":"ls"},
            "tool_use_id":"toolu_01XYZ"
        }"#;
        let input: HookInput = serde_json::from_str(json).unwrap();
        assert_eq!(detect_protocol(&input), HookProtocol::ClaudeCompatible);
    }
}