destructive_command_guard 0.5.6

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
#![forbid(unsafe_code)]
//! Destructive Command Guard (dcg) for Claude Code.
//!
//! Blocks destructive commands that can lose uncommitted work or delete files.
//! This hook runs before Bash commands execute and can deny dangerous operations.
//!
//! Exit behavior:
//!   - Exit 0 with JSON {"hookSpecificOutput": {"permissionDecision": "deny", ...}} = block
//!   - Exit 0 with no output = allow
//!
//! # Performance
//!
//! This hook is invoked for every Bash command, so latency is critical:
//! - Quick rejection filter skips regex for 99%+ of commands
//! - Lazy-initialized static patterns compiled once
//! - `Cow<str>` avoids allocation when no path normalization needed
//! - `memchr` SIMD-accelerated substring search for quick rejection
//! - Inlined hot paths for better codegen

use clap::Parser;
use colored::Colorize;
use destructive_command_guard::agent::{Agent, detect_agent};
use destructive_command_guard::allowlist::LayeredAllowlist;
use destructive_command_guard::cli::{self, Cli};
// Exit codes are used by cli.rs for robot mode; main.rs uses them for hook mode errors
use destructive_command_guard::config::Config;
use destructive_command_guard::evaluator::{
    EvaluationDecision, MatchSource, evaluate_command_with_pack_order_deadline_at_path,
};
#[allow(unused_imports)]
use destructive_command_guard::exit_codes::{EXIT_DENIED, EXIT_PARSE_ERROR, EXIT_SUCCESS};
use destructive_command_guard::history::{
    CommandEntry, ENV_HISTORY_DB_PATH, HistoryWriter, Outcome as HistoryOutcome,
};
use destructive_command_guard::hook;
use destructive_command_guard::load_default_allowlists;
use destructive_command_guard::normalize::normalize_command;
use destructive_command_guard::packs::load_external_packs;
#[cfg(test)]
use destructive_command_guard::packs::pack_aware_quick_reject;
use destructive_command_guard::packs::{DecisionMode, REGISTRY};
use destructive_command_guard::pending_exceptions::{PendingExceptionStore, log_maintenance};
use destructive_command_guard::perf::{Deadline, HOOK_EVALUATION_BUDGET};
use destructive_command_guard::sanitize_for_pattern_matching;
// Import HookInput for parsing stdin JSON in hook mode
#[cfg(test)]
use destructive_command_guard::hook::HookInput;
#[cfg(test)]
use std::borrow::Cow;
use std::collections::HashSet;
use std::io::{self, IsTerminal};
use std::path::PathBuf;
use std::time::{Duration, Instant};

// Build metadata from vergen (set by build.rs)
const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
const BUILD_TIMESTAMP: Option<&str> = option_env!("VERGEN_BUILD_TIMESTAMP");
const RUSTC_SEMVER: Option<&str> = option_env!("VERGEN_RUSTC_SEMVER");
const CARGO_TARGET: Option<&str> = option_env!("VERGEN_CARGO_TARGET_TRIPLE");

// NOTE: HookInput, ToolInput, HookOutput, HookSpecificOutput types are now defined
// in the hook module. Use hook::HookInput, hook::read_hook_input(), etc.

/// Configure colored output based on TTY detection.
///
/// Disables colors if stderr is not a terminal (e.g., piped to a file).
fn configure_colors() {
    if std::env::var_os("NO_COLOR").is_some()
        || destructive_command_guard::output::env_flag_enabled("DCG_NO_COLOR")
    {
        colored::control::set_override(false);
        return;
    }

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

fn history_db_path(config: &destructive_command_guard::config::HistoryConfig) -> Option<PathBuf> {
    if let Ok(path) = std::env::var(ENV_HISTORY_DB_PATH) {
        return Some(PathBuf::from(path));
    }
    config.expanded_database_path()
}

fn build_history_entry(
    agent_type: &str,
    command: &str,
    working_dir: &str,
    outcome: HistoryOutcome,
    eval_duration: Duration,
    pack_id: Option<&str>,
    pattern_name: Option<&str>,
    allowlist_layer: Option<&str>,
) -> CommandEntry {
    let eval_duration_us = u64::try_from(eval_duration.as_micros()).unwrap_or(u64::MAX);

    CommandEntry {
        agent_type: agent_type.to_string(),
        working_dir: working_dir.to_string(),
        command: command.to_string(),
        outcome,
        pack_id: pack_id.map(str::to_string),
        pattern_name: pattern_name.map(str::to_string),
        eval_duration_us,
        allowlist_layer: allowlist_layer.map(str::to_string),
        ..Default::default()
    }
}

fn history_agent_type_for_protocol(protocol: hook::HookProtocol, detected_agent: &Agent) -> &str {
    match protocol {
        hook::HookProtocol::Codex => Agent::CodexCli.config_key(),
        hook::HookProtocol::Gemini => Agent::GeminiCli.config_key(),
        hook::HookProtocol::Copilot => Agent::CopilotCli.config_key(),
        hook::HookProtocol::Hermes => Agent::Hermes.config_key(),
        hook::HookProtocol::Grok => Agent::Grok.config_key(),
        hook::HookProtocol::ClaudeCompatible => detected_agent.config_key(),
    }
}

fn effective_agent_for_hook_protocol(
    protocol: hook::HookProtocol,
    detected_agent: &Agent,
) -> Agent {
    match protocol {
        hook::HookProtocol::Codex => Agent::CodexCli,
        hook::HookProtocol::Gemini => Agent::GeminiCli,
        hook::HookProtocol::Copilot => Agent::CopilotCli,
        hook::HookProtocol::Hermes => Agent::Hermes,
        hook::HookProtocol::Grok => Agent::Grok,
        hook::HookProtocol::ClaudeCompatible => detected_agent.clone(),
    }
}

/// Process-wide registry of shutdown actions.
///
/// `std::process::exit` skips Drop, so any subsystem with cross-call buffered
/// state (history writer, future stores) needs an explicit pre-exit flush.
/// Each subsystem registers a closure here at startup; the SIGINT handler
/// invokes them in order before exiting. New stores should add a registration
/// call — do not add ad-hoc flush logic to the SIGINT handler itself.
type ShutdownAction = Box<dyn Fn() + Send + Sync>;

static SHUTDOWN_ACTIONS: std::sync::OnceLock<std::sync::Mutex<Vec<ShutdownAction>>> =
    std::sync::OnceLock::new();

fn shutdown_registry() -> &'static std::sync::Mutex<Vec<ShutdownAction>> {
    SHUTDOWN_ACTIONS.get_or_init(|| std::sync::Mutex::new(Vec::new()))
}

fn register_shutdown_action<F>(action: F)
where
    F: Fn() + Send + Sync + 'static,
{
    let actions = shutdown_registry();
    if let Ok(mut guard) = actions.lock() {
        guard.push(Box::new(action));
    }
}

fn run_shutdown_actions() {
    let actions = shutdown_registry();
    // Recover from a poisoned lock: a previous panic mid-action shouldn't
    // prevent subsequent shutdown calls from flushing remaining stores.
    let guard = match actions.lock() {
        Ok(g) => g,
        Err(p) => p.into_inner(),
    };
    for action in guard.iter() {
        // Catch panics so one buggy flush doesn't skip the rest. We can't
        // do anything useful with the panic payload at shutdown — at best,
        // log it; failing that, swallow it. The other registered stores
        // still need their chance to flush.
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(action));
    }
}

fn install_signal_shutdown_handler() {
    // Idempotent: ctrlc::set_handler returns Err on duplicate install. The
    // handler itself runs every action in the registry deterministically
    // (in registration order), then exits 130. Code 130 is the canonical
    // "interrupted by SIGINT" status (128 + SIGINT(2)).
    let _ = ctrlc::set_handler(|| {
        eprintln!("[dcg] Flushing on signal...");
        run_shutdown_actions();
        std::process::exit(130);
    });
}

fn install_history_shutdown_handler(
    handle: destructive_command_guard::history::HistoryFlushHandle,
) {
    register_shutdown_action(move || {
        handle.flush_sync();
    });
    install_signal_shutdown_handler();
}

fn is_top_level_global_flag(arg: &str) -> bool {
    matches!(
        arg,
        "--verbose"
            | "--quiet"
            | "-q"
            | "--legacy-output"
            | "--no-color"
            | "--no-suggestions"
            | "--robot"
    ) || (arg.starts_with('-') && !arg.starts_with("--") && arg[1..].chars().all(|c| c == 'v'))
}

fn top_level_flag_requested(args: &[String], long: &str, short: &str) -> bool {
    let mut index = 1;
    while index < args.len() {
        let arg = &args[index];
        if arg == long || arg == short {
            return true;
        }
        if is_top_level_global_flag(arg) {
            index += 1;
            continue;
        }
        if arg == "--agent" {
            index += 2;
            continue;
        }
        if arg.starts_with("--agent=") {
            index += 1;
            continue;
        }
        return false;
    }

    false
}

fn remove_disabled_packs_for_agent(
    enabled_packs: &mut HashSet<String>,
    config: &Config,
    agent: &Agent,
) {
    let profile = config.agents.profile_for_agent(agent);
    for disabled in &profile.disabled_packs {
        enabled_packs.remove(disabled);
        enabled_packs.retain(|pack| !pack.starts_with(&format!("{disabled}.")));
    }
}

fn apply_agent_allowlist_profile(
    config: &Config,
    agent: &Agent,
    mut allowlists: LayeredAllowlist,
) -> LayeredAllowlist {
    if config.allowlist_disabled_for_agent(agent) {
        return LayeredAllowlist::default();
    }

    allowlists.prepend_agent_exact_commands(
        agent.config_key(),
        config.additional_allowlist_for_agent(agent),
    );
    allowlists
}

fn load_effective_allowlists_for_agent(config: &Config, agent: &Agent) -> LayeredAllowlist {
    apply_agent_allowlist_profile(config, agent, load_default_allowlists())
}

// NOTE: Denial output functions (format_denial_message, print_colorful_warning, deny)
// are now in the hook module. Use hook::output_denial() for all denial responses.

/// Print version information and exit.
fn print_version() {
    // Machine-readable version on stdout (for scripts, installers, etc.)
    println!("{PKG_VERSION}");

    // ASCII art logo - compact shield design
    eprintln!();
    eprintln!(
        "  {}",
        "╭─────────────────────────────────────────╮".bright_black()
    );
    eprintln!(
        "  {}  🛡  {}               {}",
        "".bright_black(),
        "Destructive Command Guard".white().bold(),
        "".bright_black()
    );
    eprintln!(
        "  {}     {}                           {}",
        "".bright_black(),
        format!("dcg v{PKG_VERSION}").cyan().bold(),
        "".bright_black()
    );
    eprintln!(
        "  {}                                         {}",
        "".bright_black(),
        "".bright_black()
    );

    // Build info
    if let Some(ts) = BUILD_TIMESTAMP {
        // Extract just the date part for cleaner display
        let date = ts.split('T').next().unwrap_or(ts);
        eprintln!(
            "  {}  {} {}                   {}",
            "".bright_black(),
            "Built:".bright_black(),
            date.white(),
            "".bright_black()
        );
    }
    if let Some(rustc) = RUSTC_SEMVER {
        eprintln!(
            "  {}  {} {}                      {}",
            "".bright_black(),
            "Rustc:".bright_black(),
            rustc.white(),
            "".bright_black()
        );
    }
    if let Some(target) = CARGO_TARGET {
        eprintln!(
            "  {}  {} {}         {}",
            "".bright_black(),
            "Target:".bright_black(),
            target.white(),
            "".bright_black()
        );
    }

    eprintln!(
        "  {}                                         {}",
        "".bright_black(),
        "".bright_black()
    );
    eprintln!(
        "  {}  {}  {}",
        "".bright_black(),
        "Protecting your code from destructive ops".green(),
        "".bright_black()
    );
    eprintln!(
        "  {}",
        "╰─────────────────────────────────────────╯".bright_black()
    );
    eprintln!();
}

#[allow(clippy::too_many_lines)]
fn main() {
    // Configure colors based on TTY detection
    configure_colors();

    // Check for --version flag (useful when run directly, not as hook)
    let args: Vec<String> = std::env::args().collect();
    if top_level_flag_requested(&args, "--version", "-V") {
        print_version();
        return;
    }

    // Check for --help flag
    if top_level_flag_requested(&args, "--help", "-h") {
        print_help();
        return;
    }

    // Parse CLI arguments (subcommands). If parsing fails (e.g., unknown flags),
    // print the clap error and exit instead of falling into hook mode and
    // blocking on stdin.
    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(e) => {
            let exit_code = e.exit_code();
            eprintln!("{e}");
            std::process::exit(exit_code);
        }
    };

    // Initialize output system based on CLI flags.
    // --legacy-output, --no-color, or --robot forces plain output mode.
    // Robot mode also suppresses all stderr output.
    let robot_mode = destructive_command_guard::output::robot_mode_enabled(cli.robot);
    let force_plain_output = cli.legacy_output || cli.no_color || robot_mode;
    destructive_command_guard::output::init(force_plain_output);
    destructive_command_guard::output::init_console(force_plain_output);
    destructive_command_guard::output::init_suggestions(!cli.no_suggestions && !robot_mode);

    // In robot mode, also disable colors completely
    if robot_mode {
        colored::control::set_override(false);
    }

    // If there's a subcommand, handle it and exit.
    if cli.command.is_some() {
        if let Err(e) = cli::run_command(cli) {
            eprintln!("Error: {e}");
            std::process::exit(1);
        }
        return;
    }

    // Load configuration
    let config = Config::load();
    let detected_agent = detect_agent();

    // Check if bypass is requested (escape hatch)
    if Config::is_bypassed() {
        return;
    }

    // Self-heal: verify the DCG hook is still registered in settings.json.
    // Claude Code can silently overwrite settings.json mid-session, removing the hook.
    // This re-registers it automatically (fail-open: errors are logged, never fatal).
    if config.general.self_heal_hook {
        cli::ensure_hook_registered();
    }

    // Compile overrides once (precompiled regexes, no per-command compilation)
    let compiled_overrides = config.overrides.compile();

    // Compute effective heredoc settings once (avoid per-command parsing/allocations).
    let heredoc_settings = config.heredoc_settings();

    // Load external packs from custom_paths (glob + tilde expansion).
    // External packs are loaded once and cached for the process lifetime.
    let external_paths = config.packs.expand_custom_paths();
    let external_store = load_external_packs(&external_paths);

    // Log warnings from external pack loading (fail-open: don't block on warnings).
    if config.general.verbose {
        for warning in external_store.warnings() {
            eprintln!("[dcg] Warning: {warning}");
        }
    }

    // Read and parse input
    let max_input_bytes = config.general.max_hook_input_bytes();
    let hook_input = match hook::read_hook_input(max_input_bytes) {
        Ok(input) => input,
        Err(hook::HookReadError::InputTooLarge(len)) => {
            eprintln!(
                "[dcg] Warning: stdin input ({len} bytes) exceeds limit ({max_input_bytes} bytes); allowing command (fail-open)"
            );
            return;
        }
        Err(_) => return, // Fail open on IO or JSON errors
    };

    // Start evaluation deadline after input size checks (includes evaluation).
    // Enforce a minimum timeout to prevent bypass via `hook_timeout_ms = 0`
    // which would cause deadline_exceeded() to immediately allow all commands.
    let deadline = Deadline::new(
        config
            .general
            .hook_timeout_ms
            .map_or(HOOK_EVALUATION_BUDGET, |ms| {
                Duration::from_millis(ms.max(destructive_command_guard::perf::MIN_HOOK_TIMEOUT_MS))
            }),
    );

    let Some((command, hook_protocol)) = hook::extract_command_with_protocol(&hook_input) else {
        return;
    };
    let history_agent_type = history_agent_type_for_protocol(hook_protocol, &detected_agent);
    let effective_agent = effective_agent_for_hook_protocol(hook_protocol, &detected_agent);

    // Check command size limit (fail-open: allow and warn)
    let max_command_bytes = config.general.max_command_bytes();
    if command.len() > max_command_bytes {
        eprintln!(
            "[dcg] Warning: command ({} bytes) exceeds limit ({} bytes); allowing command (fail-open)",
            command.len(),
            max_command_bytes
        );
        return;
    }

    // Load layered allowlists (project/user/system). Missing/invalid files are treated
    // as empty for hook safety; allowlist decisions are only consulted on matches.
    // Use the hook protocol when it identifies the agent more reliably than env/process
    // detection, because Codex/Gemini hooks are often launched without agent-specific
    // environment variables.
    let allowlists = load_effective_allowlists_for_agent(&config, &effective_agent);

    let mut enabled_packs: HashSet<String> = config.enabled_pack_ids_for_agent(&effective_agent);

    // Auto-enable external packs: packs loaded via custom_paths are implicitly enabled.
    // This avoids requiring users to both add a path AND explicitly enable the pack ID.
    for id in external_store.pack_ids() {
        enabled_packs.insert(id.clone());
    }
    remove_disabled_packs_for_agent(&mut enabled_packs, &config, &effective_agent);

    let mut enabled_keywords = REGISTRY.collect_enabled_keywords(&enabled_packs);
    // Merge external pack keywords into enabled keywords for quick rejection.
    // This ensures commands with external pack keywords are not prematurely rejected.
    enabled_keywords.extend(external_store.keywords().iter().copied());

    // Build ordered pack list and keyword index AFTER external packs are loaded,
    // so external pack IDs are included in the evaluation iteration list.
    let mut ordered_packs = REGISTRY.expand_enabled_ordered(&enabled_packs);
    // Append external pack IDs (not in the registry, so expand_enabled_ordered won't include them).
    for id in external_store.pack_ids() {
        if !ordered_packs.contains(id) {
            ordered_packs.push(id.clone());
        }
    }
    // Keyword index only covers built-in packs; disable when external packs are present
    // to ensure the non-indexed path (which handles both built-in and external) is used.
    let keyword_index = if external_store.pack_ids().next().is_some() {
        None
    } else {
        REGISTRY.build_enabled_keyword_index(&ordered_packs)
    };

    let cwd_path = std::env::current_dir().ok();
    let working_dir = cwd_path.as_ref().map_or_else(
        || "<unknown>".to_string(),
        |path| path.to_string_lossy().to_string(),
    );

    let history_writer = if config.history.enabled {
        Some(HistoryWriter::new(
            history_db_path(&config.history),
            &config.history,
        ))
    } else {
        None
    };

    if let Some(writer) = history_writer.as_ref() {
        if let Some(handle) = writer.flush_handle() {
            install_history_shutdown_handler(handle);
        }
    }

    if deadline.is_exceeded() {
        if let Some(log_file) = config.general.log_file.as_deref() {
            let _ = hook::log_budget_skip(
                log_file,
                &command,
                "pre_evaluation",
                deadline.elapsed(),
                HOOK_EVALUATION_BUDGET,
            );
        }
        return;
    }

    // Use the shared evaluator for hook mode parity with `dcg test`.
    let eval_start = Instant::now();
    let result = evaluate_command_with_pack_order_deadline_at_path(
        &command,
        &enabled_keywords,
        &ordered_packs,
        keyword_index.as_ref(),
        &compiled_overrides,
        &allowlists,
        &heredoc_settings,
        None, // allow_once_audit
        None, // project_path
        Some(&deadline),
    );

    // NOTE: External packs from custom_paths are now checked in evaluate_command()
    // alongside built-in packs, so no separate fallback check is needed here.

    let eval_duration = eval_start.elapsed();

    if result.skipped_due_to_budget {
        if let Some(writer) = history_writer.as_ref() {
            let entry = build_history_entry(
                history_agent_type,
                &command,
                &working_dir,
                HistoryOutcome::Allow,
                eval_duration,
                None,
                None,
                None,
            );
            writer.log(entry);
        }
        if let Some(log_file) = config.general.log_file.as_deref() {
            let _ = hook::log_budget_skip(
                log_file,
                &command,
                "evaluation",
                deadline.elapsed(),
                HOOK_EVALUATION_BUDGET,
            );
        }
        return;
    }

    if result.decision != EvaluationDecision::Deny {
        if let Some(writer) = history_writer.as_ref() {
            let mut pack_id = None;
            let mut pattern_name = None;
            let mut allowlist_layer = None;

            if let Some(override_) = result.allowlist_override.as_ref() {
                allowlist_layer = Some(override_.layer.label());
                pack_id = override_.matched.pack_id.as_deref();
                pattern_name = override_.matched.pattern_name.as_deref();
            }

            let entry = build_history_entry(
                history_agent_type,
                &command,
                &working_dir,
                HistoryOutcome::Allow,
                eval_duration,
                pack_id,
                pattern_name,
                allowlist_layer,
            );
            writer.log(entry);
        }
        return;
    }

    let Some(ref info) = result.pattern_info else {
        // Fail open: structurally unexpected, but hook safety wins.
        if let Some(writer) = history_writer.as_ref() {
            let entry = build_history_entry(
                history_agent_type,
                &command,
                &working_dir,
                HistoryOutcome::Allow,
                eval_duration,
                None,
                None,
                None,
            );
            writer.log(entry);
        }
        return;
    };

    let pack = info.pack_id.as_deref();
    let mut mode = match info.source {
        MatchSource::Pack | MatchSource::HeredocAst => {
            config
                .policy()
                .resolve_mode(pack, info.pattern_name.as_deref(), info.severity)
        }
        // Never downgrade explicit blocks.
        MatchSource::ConfigOverride | MatchSource::LegacyPattern => DecisionMode::Deny,
    };

    // Apply confidence scoring (if enabled) to potentially downgrade Deny to Warn.
    // Only applies to pack/heredoc matches, not config overrides.
    if matches!(info.source, MatchSource::Pack | MatchSource::HeredocAst) {
        let sanitized = sanitize_for_pattern_matching(&command);
        let normalized_command = normalize_command(&command);
        let normalized_sanitized = normalize_command(sanitized.as_ref());

        let mut confidence_command = command.as_str();
        let mut confidence_sanitized: Option<&str> = None;

        if normalized_command.len() == normalized_sanitized.len() {
            confidence_command = normalized_command.as_ref();
            if sanitized.as_ref() != command {
                confidence_sanitized = Some(normalized_sanitized.as_ref());
            }
        }

        let confidence_result = destructive_command_guard::apply_confidence_scoring(
            confidence_command,
            confidence_sanitized,
            &result,
            mode,
            &config.confidence,
        );
        mode = confidence_result.mode;
    }

    let pattern = info.pattern_name.as_deref();
    let explanation = info.explanation.as_deref();

    // Rebase-recovery unblock (issue #104).
    //
    // Before emitting a hard deny, check whether this is one of the narrow
    // "recovery" patterns (`checkout-discard`, `restore-worktree`, etc.)
    // AND a recovery signal is active: either a rebase is in progress
    // (`.git/rebase-merge/` or `.git/rebase-apply/`) or a short-lived
    // `dcg rebase-recover` permit was issued. If yes, convert the deny
    // into an allow with a stderr note and (for the permit case) consume
    // the cookie so subsequent unrelated commands stay blocked.
    //
    // Safety: only fires when BOTH (a) the matched pattern is on the
    // small recovery allowlist, AND (b) a recovery signal is active.
    // Outside this narrow window the original deny path is unchanged.
    if matches!(mode, DecisionMode::Deny) {
        if let Some(cwd_ref) = cwd_path.as_deref() {
            if let Some(reason) = destructive_command_guard::rebase_recovery::should_allow_recovery(
                cwd_ref, pack, pattern,
            ) {
                // Consume the permit if that's why we allowed (single-shot).
                if matches!(
                    reason,
                    destructive_command_guard::rebase_recovery::RecoveryReason::ActivePermit(_)
                ) {
                    destructive_command_guard::rebase_recovery::consume_permit(cwd_ref);
                }
                // Inform on stderr (visible to the agent and to humans).
                // Stays silent when stderr isn't a TTY and robot mode is on,
                // but the message itself is always safe to emit.
                eprintln!(
                    "[dcg] Allowing `{}` → rebase-recovery mode ({})",
                    pattern.unwrap_or("<unknown>"),
                    reason.label()
                );
                if let Some(writer) = history_writer.as_ref() {
                    let entry = build_history_entry(
                        history_agent_type,
                        &command,
                        &working_dir,
                        HistoryOutcome::Allow,
                        eval_duration,
                        pack,
                        pattern,
                        Some("rebase-recovery"),
                    );
                    writer.log(entry);
                }
                return;
            }
        }
    }

    if let Some(writer) = history_writer.as_ref() {
        let outcome = match mode {
            DecisionMode::Deny => HistoryOutcome::Deny,
            DecisionMode::Warn => HistoryOutcome::Warn,
            DecisionMode::Log => HistoryOutcome::Allow,
        };
        let entry = build_history_entry(
            history_agent_type,
            &command,
            &working_dir,
            outcome,
            eval_duration,
            pack,
            pattern,
            None,
        );
        writer.log(entry);
    }

    match mode {
        DecisionMode::Deny => {
            let store_path = PendingExceptionStore::default_path(cwd_path.as_deref());
            let store = PendingExceptionStore::new(store_path);
            let reason = match (pack, pattern) {
                (Some(pack_id), Some(pattern_name)) => {
                    format!("{pack_id}:{pattern_name} - {}", info.reason)
                }
                _ => info.reason.clone(),
            };

            let mut allow_once_info: Option<hook::AllowOnceInfo> = None;
            if let Ok((record, maintenance)) = store.record_block(
                &command,
                &working_dir,
                &reason,
                &config.logging.redaction,
                false,
                Some(format!("{:?}", info.source)),
                None,
            ) {
                allow_once_info = Some(hook::AllowOnceInfo {
                    code: record.short_code,
                    full_hash: record.full_hash,
                });
                if let Some(log_file) = config.general.log_file.as_deref() {
                    let _ = log_maintenance(log_file, maintenance, "record_block");
                }
            }

            let branch_ctx = if config.git_awareness.should_show_branch_in_output() {
                result.branch_context.as_ref()
            } else {
                None
            };
            hook::output_denial_for_protocol(
                hook_protocol,
                &command,
                &info.reason,
                pack,
                pattern,
                explanation,
                allow_once_info.as_ref(),
                info.matched_span.as_ref(),
                info.severity,
                None, // confidence not yet available in PatternMatch
                info.suggestions,
                branch_ctx,
            );

            // Log if configured
            if let Some(log_file) = &config.general.log_file {
                let _ = hook::log_blocked_command(log_file, &command, &info.reason, pack);
            }

            // Codex 0.125.0+ ignores stdout JSON whose hookSpecificOutput
            // contains unknown fields; its supported alternative is exit 2 +
            // stderr reason (codex-rs/hooks/src/events/pre_tool_use.rs).
            // The colored deny message has already been written to stderr by
            // output_denial_for_protocol(); exit 2 here makes the block stick.
            //
            // process::exit() skips Rust destructors, so flush the async
            // history writer first -- the Deny entry was just queued via
            // writer.log() above and would otherwise be lost when the worker
            // thread is killed by libc::exit. The other deny paths fall off
            // the end of main and let HistoryWriter::Drop handle this.
            if matches!(hook_protocol, hook::HookProtocol::Codex) {
                if let Some(writer) = history_writer.as_ref() {
                    writer.flush_sync();
                }
                std::process::exit(2);
            }
        }
        DecisionMode::Warn => {
            hook::output_warning_for_protocol(
                hook_protocol,
                &command,
                &info.reason,
                pack,
                pattern,
                explanation,
            );
        }
        DecisionMode::Log => {
            // Silent allow; optionally log to file for history.
            if let Some(log_file) = &config.general.log_file {
                let _ = hook::log_blocked_command(log_file, &command, &info.reason, pack);
            }
        }
    }
}

/// Print help information.
#[allow(clippy::too_many_lines)]
fn print_help() {
    eprintln!();
    eprintln!("  🛡  {} {}", "dcg".green().bold(), PKG_VERSION.cyan());
    eprintln!(
        "     {}",
        "Destructive Command Guard - multi-agent safety hook".bright_black()
    );
    eprintln!();

    // Usage section
    eprintln!("  {}", "USAGE".yellow().bold());
    eprintln!("  {}", "".repeat(50).bright_black());
    eprintln!("    Runs as a pre-execution shell hook for Claude Code, Codex CLI,");
    eprintln!("    Gemini CLI, GitHub Copilot CLI, Cursor IDE, and Hermes Agent.");
    eprintln!("    Compatible agents receive stdout JSON; Codex denials use stderr + exit 2.");
    eprintln!();

    // Configuration section
    eprintln!("  {}", "CONFIGURATION".yellow().bold());
    eprintln!("  {}", "".repeat(50).bright_black());
    eprintln!("    Installers configure supported agent hooks automatically.");
    eprintln!(
        "    Common Claude Code config in {}:",
        "~/.claude/settings.json".cyan()
    );
    eprintln!();
    eprintln!(
        "    {}",
        "╭──────────────────────────────────────────────────────────────╮".bright_black()
    );
    eprintln!(
        "    {} {} {}",
        "".bright_black(),
        r#"{"hooks": {"PreToolUse": [{"matcher": "Bash","#.white(),
        "".bright_black()
    );
    eprintln!(
        "    {}   {} {}",
        "".bright_black(),
        r#""hooks": [{"type": "command", "command": "dcg"}]}]}}"#.white(),
        "".bright_black()
    );
    eprintln!(
        "    {}",
        "╰──────────────────────────────────────────────────────────────╯".bright_black()
    );
    eprintln!();

    // Options section
    eprintln!("  {}", "OPTIONS".yellow().bold());
    eprintln!("  {}", "".repeat(50).bright_black());
    eprintln!(
        "    {}     Print version information",
        "--version, -V".green()
    );
    eprintln!(
        "    {}        Print this help message",
        "--help, -h".green()
    );
    eprintln!();

    // Commands section
    eprintln!("  {}", "COMMANDS".yellow().bold());
    eprintln!("  {}", "".repeat(50).bright_black());
    eprintln!(
        "    {}         Test a command against enabled packs",
        "test".green()
    );
    eprintln!(
        "    {}      Explain why a command would be blocked/allowed",
        "explain".green()
    );
    eprintln!(
        "    {}       Check installation and hook registration",
        "doctor".green()
    );
    eprintln!(
        "    {}        List all available packs and their status",
        "packs".green()
    );
    eprintln!(
        "    {}         Pack management commands (info, validate)",
        "pack".green()
    );
    eprintln!(
        "    {}    Manage allowlist entries (add, list, remove)",
        "allowlist".green()
    );
    eprintln!("    {}        Add a rule to the allowlist", "allow".green());
    eprintln!(
        "    {}      Remove a rule from the allowlist",
        "unallow".green()
    );
    eprintln!(
        "    {}   Allow a blocked command once via short code",
        "allow-once".green()
    );
    eprintln!(
        "    {}         Scan files for destructive commands",
        "scan".green()
    );
    eprintln!(
        "    {}     Simulate policy evaluation on command logs",
        "simulate".green()
    );
    eprintln!("    {}       Show current configuration", "config".green());
    eprintln!(
        "    {}         Generate a sample configuration file",
        "init".green()
    );
    eprintln!(
        "    {}      Install the hook into Claude Code settings",
        "install".green()
    );
    eprintln!(
        "    {}    Remove the hook from Claude Code settings",
        "uninstall".green()
    );
    eprintln!(
        "    {}       Update dcg to the latest release",
        "update".green()
    );
    eprintln!(
        "    {}        Show local statistics from the log file",
        "stats".green()
    );
    eprintln!(
        "    {}      Query command history database",
        "history".green()
    );
    eprintln!(
        "    {}  Suggest allowlist patterns from history",
        "suggest-allowlist".green()
    );
    eprintln!("    {}       Run regression corpus tests", "corpus".green());
    eprintln!(
        "    {}         Run in explicit hook mode (batch support)",
        "hook".green()
    );
    eprintln!(
        "    {}  Generate shell completion scripts",
        "completions".green()
    );
    eprintln!(
        "    {}          Developer tools for pack development",
        "dev".green()
    );
    eprintln!(
        "    {}   Start MCP server for agent integration",
        "mcp-server".green()
    );
    eprintln!();
    eprintln!(
        "    Run {} for detailed help on a command.",
        "dcg <command> --help".cyan()
    );
    eprintln!();

    // Environment section
    eprintln!("  {}", "ENVIRONMENT".yellow().bold());
    eprintln!("  {}", "".repeat(50).bright_black());
    eprintln!(
        "    {}=0-3     Verbosity level (0 = quiet, 3 = trace)",
        "DCG_VERBOSE".green()
    );
    eprintln!(
        "    {}=1       Suppress non-error output",
        "DCG_QUIET".green()
    );
    eprintln!(
        "    {}=1    Disable colored output (same as NO_COLOR)",
        "DCG_NO_COLOR".green()
    );
    eprintln!(
        "    {}=text|json|sarif  Default output format (command-specific)",
        "DCG_FORMAT".green()
    );
    eprintln!(
        "    {}=/path  Use explicit config file",
        "DCG_CONFIG".green()
    );
    eprintln!(
        "    {}=ms  Hook evaluation timeout budget",
        "DCG_HOOK_TIMEOUT_MS".green()
    );
    eprintln!(
        "    {}=1      Robot mode for AI agents (JSON output, no stderr)",
        "DCG_ROBOT".green()
    );
    eprintln!();

    // Blocked commands section
    eprintln!("  {}", "BLOCKED COMMANDS".yellow().bold());
    eprintln!("  {}", "".repeat(50).bright_black());
    eprintln!();
    eprintln!(
        "    {} {}",
        "Git".red().bold(),
        "(core.git pack)".bright_black()
    );
    eprintln!("      {} git reset --hard", "".red());
    eprintln!("      {} git checkout -- <path>", "".red());
    eprintln!("      {} git restore (without --staged)", "".red());
    eprintln!("      {} git clean -f", "".red());
    eprintln!("      {} git push --force", "".red());
    eprintln!("      {} git branch -D", "".red());
    eprintln!("      {} git stash drop/clear", "".red());
    eprintln!();
    eprintln!(
        "    {} {}",
        "Filesystem".red().bold(),
        "(core.filesystem pack)".bright_black()
    );
    eprintln!(
        "      {} rm -rf outside of /tmp, /var/tmp, $TMPDIR",
        "".red()
    );
    eprintln!();

    // Additional packs note
    eprintln!("    📦 Additional packs: containers.docker, kubernetes.kubectl,");
    eprintln!("       databases.sql, cloud.terraform, and more.");
    eprintln!();

    // Links section
    eprintln!("  {}", "".repeat(50).bright_black());
    eprintln!(
        "    📖 {}",
        "https://github.com/Dicklesworthstone/destructive_command_guard"
            .blue()
            .underline()
    );
    eprintln!();
}

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

    mod top_level_dispatch_tests {
        use super::*;

        fn args(items: &[&str]) -> Vec<String> {
            items.iter().map(|item| (*item).to_string()).collect()
        }

        #[test]
        fn top_level_help_is_detected_before_subcommands() {
            assert!(top_level_flag_requested(
                &args(&["dcg", "--help"]),
                "--help",
                "-h"
            ));
            assert!(top_level_flag_requested(
                &args(&["dcg", "--no-color", "-h"]),
                "--help",
                "-h"
            ));
        }

        #[test]
        fn subcommand_help_is_left_for_clap() {
            assert!(!top_level_flag_requested(
                &args(&["dcg", "simulate", "--help"]),
                "--help",
                "-h"
            ));
            assert!(!top_level_flag_requested(
                &args(&["dcg", "--robot", "test", "-h"]),
                "--help",
                "-h"
            ));
        }

        #[test]
        fn update_version_flag_is_not_top_level_version() {
            assert!(!top_level_flag_requested(
                &args(&["dcg", "update", "--version", "v0.2.0"]),
                "--version",
                "-V"
            ));
            assert!(top_level_flag_requested(
                &args(&["dcg", "-vv", "--version"]),
                "--version",
                "-V"
            ));
        }

        #[test]
        fn top_level_agent_override_does_not_hide_global_flags() {
            assert!(top_level_flag_requested(
                &args(&["dcg", "--agent", "custom-agent", "--version"]),
                "--version",
                "-V"
            ));
            assert!(top_level_flag_requested(
                &args(&["dcg", "--agent=custom-agent", "--help"]),
                "--help",
                "-h"
            ));
        }

        #[test]
        fn subcommand_agent_override_is_left_for_clap() {
            assert!(!top_level_flag_requested(
                &args(&["dcg", "test", "--agent", "custom-agent", "--help"]),
                "--help",
                "-h"
            ));
        }
    }

    mod input_parsing_tests {
        use super::*;

        fn parse_and_get_command(json: &str) -> Option<String> {
            let hook_input: HookInput = serde_json::from_str(json).ok()?;
            hook::extract_command(&hook_input)
        }

        #[test]
        fn parses_valid_bash_input() {
            let json = r#"{"tool_name": "Bash", "tool_input": {"command": "git status"}}"#;
            assert_eq!(parse_and_get_command(json), Some("git status".to_string()));
        }

        #[test]
        fn rejects_non_bash_tool() {
            let json = r#"{"tool_name": "Read", "tool_input": {"command": "git status"}}"#;
            assert_eq!(parse_and_get_command(json), None);
        }

        #[test]
        fn parses_valid_copilot_input() {
            let json = r#"{"event":"pre-tool-use","toolName":"run_shell_command","toolInput":{"command":"git status"}}"#;
            assert_eq!(parse_and_get_command(json), Some("git status".to_string()));
        }

        #[test]
        fn rejects_missing_tool_name() {
            let json = r#"{"tool_input": {"command": "git status"}}"#;
            assert_eq!(parse_and_get_command(json), None);
        }

        #[test]
        fn rejects_missing_tool_input() {
            let json = r#"{"tool_name": "Bash"}"#;
            assert_eq!(parse_and_get_command(json), None);
        }

        #[test]
        fn rejects_missing_command() {
            let json = r#"{"tool_name": "Bash", "tool_input": {}}"#;
            assert_eq!(parse_and_get_command(json), None);
        }

        #[test]
        fn rejects_empty_command() {
            let json = r#"{"tool_name": "Bash", "tool_input": {"command": ""}}"#;
            assert_eq!(parse_and_get_command(json), None);
        }

        #[test]
        fn rejects_non_string_command() {
            let json = r#"{"tool_name": "Bash", "tool_input": {"command": 123}}"#;
            assert_eq!(parse_and_get_command(json), None);
        }

        #[test]
        fn rejects_invalid_json() {
            assert_eq!(parse_and_get_command("not json"), None);
            assert_eq!(parse_and_get_command("{invalid}"), None);
        }
    }

    mod history_entry_tests {
        use super::*;

        #[test]
        fn build_history_entry_uses_detected_agent_key() {
            let entry = build_history_entry(
                Agent::CodexCli.config_key(),
                "git status",
                "/tmp/project",
                HistoryOutcome::Allow,
                Duration::from_micros(42),
                None,
                None,
                None,
            );

            assert_eq!(entry.agent_type, "codex-cli");
            assert_eq!(entry.command, "git status");
            assert_eq!(entry.eval_duration_us, 42);
        }

        #[test]
        fn history_agent_type_prefers_definitive_hook_protocols() {
            assert_eq!(
                history_agent_type_for_protocol(hook::HookProtocol::Codex, &Agent::Unknown),
                "codex-cli"
            );
            assert_eq!(
                history_agent_type_for_protocol(hook::HookProtocol::Gemini, &Agent::Unknown),
                "gemini-cli"
            );
            assert_eq!(
                history_agent_type_for_protocol(hook::HookProtocol::Copilot, &Agent::Unknown),
                "copilot-cli"
            );
        }

        #[test]
        fn history_agent_type_preserves_detected_claude_compatible_agent() {
            let custom = Agent::Custom("internal-agent".to_string());

            assert_eq!(
                history_agent_type_for_protocol(hook::HookProtocol::ClaudeCompatible, &custom),
                "internal-agent"
            );
        }
    }

    mod deny_output_tests {
        use super::*;
        use destructive_command_guard::hook::{HookOutput, HookSpecificOutput};

        fn capture_deny_output(command: &str, reason: &str) -> HookOutput<'static> {
            HookOutput {
                hook_specific_output: HookSpecificOutput {
                    hook_event_name: "PreToolUse",
                    permission_decision: "deny",
                    permission_decision_reason: Cow::Owned(format!(
                        "BLOCKED by dcg\n\n\
                         Reason: {reason}\n\n\
                         Command: {command}\n\n\
                         If this operation is truly needed, ask the user for explicit \
                         permission and have them run the command manually."
                    )),
                    allow_once_code: None,
                    allow_once_full_hash: None,
                    rule_id: None,
                    pack_id: None,
                    severity: None,
                    confidence: None,
                    remediation: None,
                },
            }
        }

        #[test]
        fn deny_output_has_correct_structure() {
            let output = capture_deny_output("git reset --hard", "test reason");
            let json = serde_json::to_string(&output).unwrap();
            let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

            assert_eq!(parsed["hookSpecificOutput"]["hookEventName"], "PreToolUse");
            assert_eq!(parsed["hookSpecificOutput"]["permissionDecision"], "deny");
            assert!(
                parsed["hookSpecificOutput"]["permissionDecisionReason"]
                    .as_str()
                    .unwrap()
                    .contains("git reset --hard")
            );
            assert!(
                parsed["hookSpecificOutput"]["permissionDecisionReason"]
                    .as_str()
                    .unwrap()
                    .contains("test reason")
            );
        }

        #[test]
        fn deny_output_is_valid_json() {
            let output = capture_deny_output("rm -rf /", "dangerous");
            let json = serde_json::to_string(&output).unwrap();
            assert!(serde_json::from_str::<serde_json::Value>(&json).is_ok());
        }
    }

    /// Regression tests for git_safety_guard-99e.1 (BUG: Non-core packs unreachable)
    ///
    /// These tests verify that when non-core packs (docker, kubectl, etc.) are enabled,
    /// their commands actually reach the pack checking logic and get blocked appropriately.
    ///
    /// The bug was that `global_quick_reject` only checked for "git" and "rm" keywords,
    /// causing all non-git/rm commands to be allowed before reaching pack checks.
    mod pack_reachability_tests {
        use super::*;
        use std::collections::HashSet;

        /// Test that `pack_aware_quick_reject` does NOT reject docker commands
        /// when docker keywords are in the enabled keywords list.
        #[test]
        fn pack_aware_quick_reject_allows_docker_when_enabled() {
            // Docker pack keywords
            let docker_keywords: Vec<&str> = vec!["docker", "prune", "rmi", "volume"];

            // Commands that should NOT be rejected (contain docker keywords)
            assert!(
                !pack_aware_quick_reject("docker system prune", &docker_keywords),
                "docker system prune should NOT be quick-rejected when docker pack enabled"
            );
            assert!(
                !pack_aware_quick_reject("docker volume prune", &docker_keywords),
                "docker volume prune should NOT be quick-rejected when docker pack enabled"
            );
            assert!(
                !pack_aware_quick_reject("docker ps", &docker_keywords),
                "docker ps should NOT be quick-rejected when docker pack enabled"
            );
            assert!(
                !pack_aware_quick_reject("docker rmi -f myimage", &docker_keywords),
                "docker rmi should NOT be quick-rejected when docker pack enabled"
            );

            // Commands that SHOULD be rejected (no docker keywords)
            assert!(
                pack_aware_quick_reject("ls -la", &docker_keywords),
                "ls should be quick-rejected (no docker keywords)"
            );
            assert!(
                pack_aware_quick_reject("cargo build", &docker_keywords),
                "cargo should be quick-rejected (no docker keywords)"
            );
        }

        /// Test that `pack_aware_quick_reject` does NOT reject kubectl commands
        /// when kubectl keywords are in the enabled keywords list.
        #[test]
        fn pack_aware_quick_reject_allows_kubectl_when_enabled() {
            // kubectl pack keywords (from kubernetes/kubectl.rs)
            let kubectl_keywords: Vec<&str> = vec!["kubectl", "delete", "drain", "cordon", "taint"];

            // Commands that should NOT be rejected
            assert!(
                !pack_aware_quick_reject("kubectl delete namespace foo", &kubectl_keywords),
                "kubectl delete should NOT be quick-rejected when kubectl pack enabled"
            );
            assert!(
                !pack_aware_quick_reject("kubectl get pods", &kubectl_keywords),
                "kubectl get should NOT be quick-rejected when kubectl pack enabled"
            );

            // Commands that SHOULD be rejected
            assert!(
                pack_aware_quick_reject("ls -la", &kubectl_keywords),
                "ls should be quick-rejected (no kubectl keywords)"
            );
        }

        /// Test that the pack registry correctly blocks docker system prune
        /// when the containers.docker pack is enabled.
        #[test]
        fn registry_blocks_docker_prune_when_pack_enabled() {
            let mut enabled = HashSet::new();
            enabled.insert("containers.docker".to_string());

            let result = REGISTRY.check_command("docker system prune", &enabled);
            assert!(
                result.blocked,
                "docker system prune should be blocked when containers.docker pack is enabled"
            );
            assert_eq!(
                result.pack_id.as_deref(),
                Some("containers.docker"),
                "Block should be attributed to containers.docker pack"
            );
        }

        /// Test that docker ps is allowed (safe pattern) even when docker pack enabled.
        #[test]
        fn registry_allows_docker_ps_when_pack_enabled() {
            let mut enabled = HashSet::new();
            enabled.insert("containers.docker".to_string());

            let result = REGISTRY.check_command("docker ps", &enabled);
            assert!(
                !result.blocked,
                "docker ps should be allowed (safe pattern) even when containers.docker pack enabled"
            );
        }

        /// Test that docker system prune is NOT blocked when docker pack is disabled.
        #[test]
        fn registry_allows_docker_prune_when_pack_disabled() {
            // Only core pack enabled (default)
            let mut enabled = HashSet::new();
            enabled.insert("core".to_string());

            let result = REGISTRY.check_command("docker system prune", &enabled);
            assert!(
                !result.blocked,
                "docker system prune should be allowed when containers.docker pack is NOT enabled"
            );
        }

        /// Test that kubectl delete namespace is blocked when kubectl pack enabled.
        #[test]
        fn registry_blocks_kubectl_delete_namespace_when_pack_enabled() {
            let mut enabled = HashSet::new();
            enabled.insert("kubernetes.kubectl".to_string());

            let result = REGISTRY.check_command("kubectl delete namespace production", &enabled);
            assert!(
                result.blocked,
                "kubectl delete namespace should be blocked when kubernetes.kubectl pack is enabled"
            );
            assert_eq!(
                result.pack_id.as_deref(),
                Some("kubernetes.kubectl"),
                "Block should be attributed to kubernetes.kubectl pack"
            );
        }

        /// Test that enabling a category enables all sub-packs.
        #[test]
        fn registry_expands_category_to_subpacks() {
            let mut enabled = HashSet::new();
            enabled.insert("containers".to_string()); // Category, not specific pack

            let result = REGISTRY.check_command("docker system prune", &enabled);
            assert!(
                result.blocked,
                "docker system prune should be blocked when 'containers' category is enabled"
            );
        }

        /// Test that `collect_enabled_keywords` includes docker keywords when docker pack enabled.
        #[test]
        fn collect_enabled_keywords_includes_docker() {
            let mut enabled = HashSet::new();
            enabled.insert("containers.docker".to_string());

            let keywords = REGISTRY.collect_enabled_keywords(&enabled);

            assert!(
                keywords.contains(&"docker"),
                "Enabled keywords should include 'docker' when containers.docker pack is enabled"
            );
            // "prune" is NOT a keyword for containers.docker (it would trigger on git prune)
            // assert!(
            //    keywords.contains(&"prune"),
            //    "Enabled keywords should include 'prune' when containers.docker pack is enabled"
            // );
        }

        /// Integration test: full pipeline blocks docker prune with pack enabled.
        /// This simulates what happens in hook mode when docker pack is enabled.
        #[test]
        fn full_pipeline_blocks_docker_prune_with_pack_enabled() {
            let command = "docker system prune";

            // Simulate config with docker pack enabled
            let mut enabled_packs = HashSet::new();
            enabled_packs.insert("core".to_string());
            enabled_packs.insert("containers.docker".to_string());

            // Collect keywords from enabled packs
            let enabled_keywords = REGISTRY.collect_enabled_keywords(&enabled_packs);

            // Step 1: pack_aware_quick_reject should NOT reject this command
            assert!(
                !pack_aware_quick_reject(command, &enabled_keywords),
                "docker system prune should NOT be quick-rejected with docker pack enabled"
            );

            // Step 2: Normalize command
            let normalized = normalize_command(command);

            // Step 3: Check against pack registry (should block)
            let result = REGISTRY.check_command(&normalized, &enabled_packs);
            assert!(
                result.blocked,
                "docker system prune should be blocked by pack registry"
            );
            assert_eq!(
                result.pack_id.as_deref(),
                Some("containers.docker"),
                "Block should be from containers.docker pack"
            );
        }

        /// Integration test: full pipeline allows docker ps with pack enabled.
        #[test]
        fn full_pipeline_allows_docker_ps_with_pack_enabled() {
            let command = "docker ps";

            let mut enabled_packs = HashSet::new();
            enabled_packs.insert("core".to_string());
            enabled_packs.insert("containers.docker".to_string());

            let enabled_keywords = REGISTRY.collect_enabled_keywords(&enabled_packs);

            // Should NOT be quick-rejected
            assert!(
                !pack_aware_quick_reject(command, &enabled_keywords),
                "docker ps should NOT be quick-rejected"
            );

            let normalized = normalize_command(command);
            let result = REGISTRY.check_command(&normalized, &enabled_packs);

            assert!(
                !result.blocked,
                "docker ps should be allowed (matches safe pattern)"
            );
        }
    }

    mod agent_profile_hook_tests {
        use super::*;
        use destructive_command_guard::allowlist::{
            AllowEntry, AllowSelector, AllowlistFile, AllowlistLayer, LoadedAllowlistLayer, RuleId,
        };
        use destructive_command_guard::config::AgentProfile;
        use destructive_command_guard::evaluator::EvaluationResult;
        use std::collections::HashMap;
        use std::path::PathBuf;

        fn project_allowlist_for_rule(rule: &str) -> LayeredAllowlist {
            LayeredAllowlist {
                layers: vec![LoadedAllowlistLayer {
                    layer: AllowlistLayer::Project,
                    path: PathBuf::from("project-allowlist.toml"),
                    file: AllowlistFile {
                        entries: vec![AllowEntry {
                            selector: AllowSelector::Rule(
                                RuleId::parse(rule).expect("rule id should parse"),
                            ),
                            reason: "project override".to_string(),
                            added_by: None,
                            added_at: None,
                            expires_at: None,
                            ttl: None,
                            session: None,
                            session_id: None,
                            context: None,
                            conditions: HashMap::new(),
                            environments: Vec::new(),
                            paths: None,
                            risk_acknowledged: false,
                        }],
                        errors: Vec::new(),
                    },
                }],
            }
        }

        fn evaluate_with_agent(config: &Config, agent: &Agent, command: &str) -> EvaluationResult {
            let mut enabled_packs = config.enabled_pack_ids_for_agent(agent);
            remove_disabled_packs_for_agent(&mut enabled_packs, config, agent);
            let enabled_keywords = REGISTRY.collect_enabled_keywords(&enabled_packs);
            let ordered_packs = REGISTRY.expand_enabled_ordered(&enabled_packs);
            let keyword_index = REGISTRY.build_enabled_keyword_index(&ordered_packs);
            let compiled_overrides = config.overrides.compile();
            let allowlists =
                apply_agent_allowlist_profile(config, agent, LayeredAllowlist::default());

            evaluate_command_with_pack_order_deadline_at_path(
                command,
                &enabled_keywords,
                &ordered_packs,
                keyword_index.as_ref(),
                &compiled_overrides,
                &allowlists,
                &config.heredoc_settings(),
                None,
                None,
                None,
            )
        }

        #[test]
        fn hook_agent_disabled_allowlist_ignores_base_and_agent_entries() {
            let mut config = Config::default();
            config.agents.profiles.insert(
                "unknown".to_string(),
                AgentProfile {
                    disabled_allowlist: true,
                    additional_allowlist: vec!["git reset --hard".to_string()],
                    ..Default::default()
                },
            );

            let allowlists = apply_agent_allowlist_profile(
                &config,
                &Agent::Unknown,
                project_allowlist_for_rule("core.git:reset-hard"),
            );

            assert!(
                allowlists.layers.is_empty(),
                "disabled_allowlist should suppress project/user/system and agent entries"
            );

            let compiled_overrides = config.overrides.compile();
            let result = destructive_command_guard::evaluate_command(
                "git reset --hard",
                &config,
                &["git"],
                &compiled_overrides,
                &allowlists,
            );

            assert_eq!(result.decision, EvaluationDecision::Deny);
            assert!(result.allowlist_override.is_none());
        }

        #[test]
        fn hook_agent_additional_allowlist_allows_exact_command() {
            let mut config = Config::default();
            config.agents.profiles.insert(
                "claude-code".to_string(),
                AgentProfile {
                    additional_allowlist: vec!["git reset --hard".to_string()],
                    ..Default::default()
                },
            );

            let allowlists = apply_agent_allowlist_profile(
                &config,
                &Agent::ClaudeCode,
                LayeredAllowlist::default(),
            );
            let compiled_overrides = config.overrides.compile();
            let result = destructive_command_guard::evaluate_command(
                "git reset --hard",
                &config,
                &["git"],
                &compiled_overrides,
                &allowlists,
            );

            assert_eq!(result.decision, EvaluationDecision::Allow);
            assert_eq!(allowlists.layers[0].layer, AllowlistLayer::Agent);
        }

        #[test]
        fn hook_agent_extra_packs_participate_in_evaluation() {
            let mut config = Config::default();
            config.agents.profiles.insert(
                "unknown".to_string(),
                AgentProfile {
                    extra_packs: vec!["containers.docker".to_string()],
                    ..Default::default()
                },
            );

            let result = evaluate_with_agent(&config, &Agent::Unknown, "docker system prune");

            assert_eq!(result.decision, EvaluationDecision::Deny);
            assert_eq!(
                result
                    .pattern_info
                    .as_ref()
                    .and_then(|info| info.pack_id.as_deref()),
                Some("containers.docker")
            );
        }

        #[test]
        fn hook_agent_disabled_packs_are_removed_from_evaluation() {
            let mut config = Config::default();
            config.packs.enabled = vec!["containers.docker".to_string()];
            config.agents.profiles.insert(
                "unknown".to_string(),
                AgentProfile {
                    disabled_packs: vec!["containers".to_string()],
                    ..Default::default()
                },
            );

            let result = evaluate_with_agent(&config, &Agent::Unknown, "docker system prune");

            assert_eq!(result.decision, EvaluationDecision::Allow);
            assert!(result.pattern_info.is_none());
        }
    }

    // ========================================================================
    // Input size limit tests (git_safety_guard-99e.10)
    // ========================================================================

    mod input_limit_tests {
        use super::*;

        #[test]
        fn config_default_limits() {
            let config = Config::default();
            // Verify defaults are set correctly
            assert_eq!(config.general.max_hook_input_bytes(), 256 * 1024);
            assert_eq!(config.general.max_command_bytes(), 64 * 1024);
            assert_eq!(config.general.max_findings_per_command(), 100);
        }

        #[test]
        fn config_custom_limits() {
            let mut config = Config::default();
            config.general.max_hook_input_bytes = Some(128 * 1024);
            config.general.max_command_bytes = Some(32 * 1024);
            config.general.max_findings_per_command = Some(50);

            assert_eq!(config.general.max_hook_input_bytes(), 128 * 1024);
            assert_eq!(config.general.max_command_bytes(), 32 * 1024);
            assert_eq!(config.general.max_findings_per_command(), 50);
        }

        #[test]
        #[allow(clippy::assertions_on_constants)]
        fn default_constants_are_reasonable() {
            use destructive_command_guard::config::{
                DEFAULT_MAX_COMMAND_BYTES, DEFAULT_MAX_FINDINGS_PER_COMMAND,
                DEFAULT_MAX_HOOK_INPUT_BYTES,
            };
            // Verify constants are reasonable sizes (compile-time validations)
            assert!(DEFAULT_MAX_HOOK_INPUT_BYTES >= 64 * 1024); // At least 64KB
            assert!(DEFAULT_MAX_HOOK_INPUT_BYTES <= 1024 * 1024); // At most 1MB
            assert!(DEFAULT_MAX_COMMAND_BYTES >= 16 * 1024); // At least 16KB
            assert!(DEFAULT_MAX_COMMAND_BYTES <= 256 * 1024); // At most 256KB
            assert!(DEFAULT_MAX_FINDINGS_PER_COMMAND >= 10); // At least 10
            assert!(DEFAULT_MAX_FINDINGS_PER_COMMAND <= 1000); // At most 1000
        }
    }

    mod shutdown_registry_tests {
        use super::*;
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        #[test]
        fn registered_actions_all_run_on_shutdown_invocation() {
            // Each registered closure increments a shared counter. We verify
            // BOTH ran (after - before >= 2) without depending on ordering
            // between this test and other tests that may have registered
            // actions in the same process — the registry is process-wide.
            let counter = Arc::new(AtomicUsize::new(0));

            let c1 = Arc::clone(&counter);
            register_shutdown_action(move || {
                c1.fetch_add(1, Ordering::SeqCst);
            });
            let c2 = Arc::clone(&counter);
            register_shutdown_action(move || {
                c2.fetch_add(1, Ordering::SeqCst);
            });

            let before = counter.load(Ordering::SeqCst);
            run_shutdown_actions();
            let after = counter.load(Ordering::SeqCst);

            assert!(
                after - before >= 2,
                "both registered actions must run; before={before} after={after}"
            );
        }

        #[test]
        fn run_shutdown_actions_continues_after_panicking_action() {
            // git_safety_guard-i5gd defense: a buggy or panicking flush
            // closure must not skip subsequent registered actions. We
            // register a panicker and a counter-incrementer; after the
            // panic-catching shutdown invocation the counter must have
            // advanced, proving the second action ran.
            let counter = Arc::new(AtomicUsize::new(0));

            register_shutdown_action(|| {
                panic!("simulated flush failure");
            });
            let c = Arc::clone(&counter);
            register_shutdown_action(move || {
                c.fetch_add(1, Ordering::SeqCst);
            });

            let before = counter.load(Ordering::SeqCst);
            run_shutdown_actions();
            let after = counter.load(Ordering::SeqCst);

            assert!(
                after > before,
                "panicking action must not block subsequent ones; before={before} after={after}"
            );
        }
    }
}