destructive_command_guard 0.4.3

A Claude Code hook that blocks destructive commands before they execute
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
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
//! Suggestions system for providing actionable guidance when commands are blocked.
//!
//! When DCG blocks a command, users need actionable guidance:
//! - What safer alternatives exist?
//! - How can they preview the effect first?
//! - How can they allowlist if intentional?
//!
//! This module provides:
//! - [`SuggestionKind`] enum categorizing types of suggestions
//! - [`Suggestion`] struct with actionable guidance
//! - [`SUGGESTION_REGISTRY`] static registry keyed by `rule_id`
//! - [`get_suggestions`] lookup function

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::LazyLock;

/// Type of suggestion to help the user.
///
/// Each kind represents a different strategy for helping users
/// work around blocked commands safely.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SuggestionKind {
    /// "Run this first to preview the effect"
    /// e.g., "Run `git diff` before `git reset --hard`"
    PreviewFirst,

    /// "Use this safer alternative instead"
    /// e.g., "Use `git reset --soft` or `--mixed` instead of `--hard`"
    SaferAlternative,

    /// "Fix your workflow to avoid this situation"
    /// e.g., "Commit your changes before resetting"
    WorkflowFix,

    /// "Read the documentation for more context"
    /// e.g., "See: <https://git-scm.com/docs/git-reset>"
    Documentation,

    /// "How to allowlist this specific rule"
    /// e.g., "To allow: `dcg allow core.git:reset-hard --reason '...'`"
    AllowSafely,
}

impl SuggestionKind {
    /// Returns a human-readable label for this suggestion kind.
    #[must_use]
    pub const fn label(&self) -> &'static str {
        match self {
            Self::PreviewFirst => "Preview first",
            Self::SaferAlternative => "Safer alternative",
            Self::WorkflowFix => "Workflow fix",
            Self::Documentation => "Documentation",
            Self::AllowSafely => "Allow safely",
        }
    }
}

/// A suggestion providing actionable guidance for a blocked command.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Suggestion {
    /// Type of suggestion
    pub kind: SuggestionKind,

    /// Human-readable suggestion text
    pub text: String,

    /// Optional command the user can copy/paste
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,

    /// Optional URL for documentation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

impl Suggestion {
    /// Create a new suggestion.
    #[must_use]
    pub fn new(kind: SuggestionKind, text: impl Into<String>) -> Self {
        Self {
            kind,
            text: text.into(),
            command: None,
            url: None,
        }
    }

    /// Add a command to copy/paste.
    #[must_use]
    pub fn with_command(mut self, command: impl Into<String>) -> Self {
        self.command = Some(command.into());
        self
    }

    /// Add a documentation URL.
    #[must_use]
    pub fn with_url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }
}

/// Registry of suggestions keyed by `rule_id` (e.g., `"core.git:reset-hard"`).
///
/// Rule IDs follow the format `{pack_id}:{pattern_name}`.
///
/// # Performance
///
/// - Lookup is O(1) via `HashMap`
/// - Returns static references (zero allocation on lookup)
/// - Initialized once on first access via `LazyLock`
pub static SUGGESTION_REGISTRY: LazyLock<HashMap<&'static str, Vec<Suggestion>>> =
    LazyLock::new(build_suggestion_registry);

/// Look up suggestions for a rule.
///
/// Returns `None` if no suggestions are registered for the given `rule_id`.
///
/// # Example
///
/// ```
/// use destructive_command_guard::suggestions::get_suggestions;
///
/// if let Some(suggestions) = get_suggestions("core.git:reset-hard") {
///     for s in suggestions {
///         println!("- {}", s.text);
///     }
/// }
/// ```
#[must_use]
pub fn get_suggestions(rule_id: &str) -> Option<&'static [Suggestion]> {
    SUGGESTION_REGISTRY.get(rule_id).map(Vec::as_slice)
}

/// Get the first suggestion of a specific kind for a rule.
#[must_use]
pub fn get_suggestion_by_kind(rule_id: &str, kind: SuggestionKind) -> Option<&'static Suggestion> {
    get_suggestions(rule_id).and_then(|suggestions| suggestions.iter().find(|s| s.kind == kind))
}

// ============================================================================
// Explanation Fallback System
// ============================================================================

/// Generate a fallback explanation when no explicit explanation is available.
///
/// The fallback is neutral, concise, and mentions:
/// - The matched pack and/or pattern name (when available)
/// - That the command matched a destructive pattern
/// - Points to `dcg explain` for details
///
/// # Arguments
///
/// * `pack_id` - The pack ID (e.g., "core.git")
/// * `pattern_name` - The pattern name (e.g., "reset-hard")
///
/// # Examples
///
/// ```
/// use destructive_command_guard::suggestions::fallback_explanation;
///
/// let exp = fallback_explanation(Some("core.git"), Some("reset-hard"));
/// assert!(exp.contains("core.git:reset-hard"));
/// assert!(exp.contains("dcg explain"));
/// ```
#[must_use]
pub fn fallback_explanation(pack_id: Option<&str>, pattern_name: Option<&str>) -> String {
    match (pack_id, pattern_name) {
        (Some(pack), Some(pattern)) => {
            format!(
                "This command matched the destructive pattern `{pack}:{pattern}`. \
                 Run `dcg explain` on this command for details and safer alternatives."
            )
        }
        (Some(pack), None) => {
            format!(
                "This command matched a destructive pattern in the `{pack}` pack. \
                 Run `dcg explain` on this command for details and safer alternatives."
            )
        }
        (None, Some(pattern)) => {
            format!(
                "This command matched the destructive pattern `{pattern}`. \
                 Run `dcg explain` on this command for details and safer alternatives."
            )
        }
        (None, None) => "This command matched a destructive pattern. \
             Run `dcg explain` on this command for details and safer alternatives."
            .to_string(),
    }
}

/// Get an explanation for a pattern, using the explicit explanation if available
/// or falling back to a generated explanation.
///
/// This function ensures no empty explanation sections in output.
///
/// # Arguments
///
/// * `explicit` - The explicit explanation from the pattern, if any
/// * `pack_id` - The pack ID for fallback generation
/// * `pattern_name` - The pattern name for fallback generation
///
/// # Examples
///
/// ```
/// use destructive_command_guard::suggestions::get_explanation;
///
/// // With explicit explanation
/// let exp = get_explanation(Some("Don't do this!"), Some("core.git"), Some("reset-hard"));
/// assert_eq!(exp, "Don't do this!");
///
/// // Without explicit explanation - uses fallback
/// let exp = get_explanation(None, Some("core.git"), Some("reset-hard"));
/// assert!(exp.contains("core.git:reset-hard"));
/// ```
#[must_use]
pub fn get_explanation(
    explicit: Option<&str>,
    pack_id: Option<&str>,
    pattern_name: Option<&str>,
) -> String {
    match explicit {
        Some(exp) if !exp.trim().is_empty() => exp.to_string(),
        _ => fallback_explanation(pack_id, pattern_name),
    }
}

/// Build the suggestion registry.
///
/// This function is called once by `LazyLock` to initialize the registry.
fn build_suggestion_registry() -> HashMap<&'static str, Vec<Suggestion>> {
    let mut m = HashMap::new();
    register_core_git_suggestions(&mut m);
    register_core_filesystem_suggestions(&mut m);
    register_heredoc_suggestions(&mut m);
    register_docker_suggestions(&mut m);
    register_kubernetes_suggestions(&mut m);
    register_database_suggestions(&mut m);
    register_system_permissions_suggestions(&mut m);
    m
}

/// Register suggestions for core.git pack rules.
#[allow(clippy::too_many_lines)]
fn register_core_git_suggestions(m: &mut HashMap<&'static str, Vec<Suggestion>>) {
    m.insert(
        "core.git:reset-hard",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run `git diff` and `git status` to see what would be lost",
            )
            .with_command("git diff && git status"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `git reset --soft` or `--mixed` to preserve changes",
            )
            .with_command("git reset --soft HEAD~1"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Consider using `git stash` to save changes temporarily",
            )
            .with_command("git stash"),
            Suggestion::new(
                SuggestionKind::Documentation,
                "See Git documentation for reset options",
            )
            .with_url("https://git-scm.com/docs/git-reset"),
        ],
    );

    m.insert(
        "core.git:clean-force",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run `git clean -n` to preview what would be deleted",
            )
            .with_command("git clean -n -fd"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `git clean -i` for interactive mode to select files",
            )
            .with_command("git clean -i"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Add patterns to .gitignore instead of cleaning",
            ),
        ],
    );

    // Force push patterns (--force and -f variants)
    let force_push_suggestions = vec![
        Suggestion::new(
            SuggestionKind::SaferAlternative,
            "Use `git push --force-with-lease` to prevent overwriting others' work",
        )
        .with_command("git push --force-with-lease"),
        Suggestion::new(
            SuggestionKind::PreviewFirst,
            "Run `git log origin/branch..HEAD` to see commits being pushed",
        ),
        Suggestion::new(
            SuggestionKind::WorkflowFix,
            "Coordinate with team before force pushing to shared branches",
        ),
    ];
    m.insert("core.git:push-force-long", force_push_suggestions.clone());
    m.insert("core.git:push-force-short", force_push_suggestions);

    // Checkout patterns that discard changes
    let checkout_discard_suggestions = vec![
        Suggestion::new(
            SuggestionKind::PreviewFirst,
            "Run `git status` and `git diff` to see uncommitted changes that would be lost",
        )
        .with_command("git status && git diff"),
        Suggestion::new(
            SuggestionKind::WorkflowFix,
            "Commit or stash changes before discarding",
        )
        .with_command("git stash"),
    ];
    m.insert(
        "core.git:checkout-discard",
        checkout_discard_suggestions.clone(),
    );
    m.insert(
        "core.git:checkout-ref-discard",
        checkout_discard_suggestions,
    );

    m.insert(
        "core.git:branch-force-delete",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check if branch has unmerged commits with `git log branch --not main`",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `git branch -d` (lowercase) to only delete if merged",
            )
            .with_command("git branch -d branch-name"),
        ],
    );

    // restore worktree patterns
    let restore_worktree_suggestions = vec![
        Suggestion::new(
            SuggestionKind::PreviewFirst,
            "Run `git diff` to see uncommitted changes that would be lost",
        )
        .with_command("git diff"),
        Suggestion::new(
            SuggestionKind::SaferAlternative,
            "Use `git stash` to save changes (retrievable later) instead of discarding",
        )
        .with_command("git stash"),
        Suggestion::new(
            SuggestionKind::WorkflowFix,
            "Commit changes before discarding to preserve them in history",
        )
        .with_command("git commit -m 'WIP: saving changes'"),
    ];
    m.insert(
        "core.git:restore-worktree",
        restore_worktree_suggestions.clone(),
    );
    m.insert(
        "core.git:restore-worktree-explicit",
        restore_worktree_suggestions,
    );

    // reset --merge
    m.insert(
        "core.git:reset-merge",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run `git status` to see uncommitted changes that could be lost",
            )
            .with_command("git status"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `git merge --abort` to cleanly abort an in-progress merge",
            )
            .with_command("git merge --abort"),
        ],
    );

    // stash destruction
    m.insert(
        "core.git:stash-drop",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List stashes with `git stash list` and view contents with `git stash show -p`",
            )
            .with_command("git stash list"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Apply the stash first with `git stash apply` before dropping",
            )
            .with_command("git stash apply"),
        ],
    );

    m.insert(
        "core.git:stash-clear",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List all stashes with `git stash list` to review what would be deleted",
            )
            .with_command("git stash list"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Drop stashes individually with `git stash drop` for more control",
            )
            .with_command("git stash drop stash@{0}"),
        ],
    );
}

/// Register suggestions for core.filesystem pack rules.
fn register_core_filesystem_suggestions(m: &mut HashMap<&'static str, Vec<Suggestion>>) {
    // Shared suggestions for all recursive force-delete variants
    let rm_rf_suggestions = vec![
        Suggestion::new(
            SuggestionKind::PreviewFirst,
            "List contents first with `ls -la` to verify target",
        ),
        Suggestion::new(
            SuggestionKind::SaferAlternative,
            "Use `rm -ri` for interactive confirmation of each file",
        )
        .with_command("rm -ri path/"),
        Suggestion::new(
            SuggestionKind::WorkflowFix,
            "Move to trash instead: `mv path ~/.local/share/Trash/`",
        ),
    ];

    // Register for all actual pattern names from filesystem.rs
    m.insert("core.filesystem:rm-rf-root-home", rm_rf_suggestions.clone());
    m.insert("core.filesystem:rm-rf-general", rm_rf_suggestions.clone());
    m.insert("core.filesystem:rm-r-f-separate", rm_rf_suggestions.clone());
    m.insert("core.filesystem:rm-recursive-force-long", rm_rf_suggestions);
}

/// Register suggestions for heredoc pattern rules.
///
/// Note: Rule IDs use the canonical `pack_id:pattern_name` format with colons,
/// matching the format used by `RuleId` in the allowlist module.
fn register_heredoc_suggestions(m: &mut HashMap<&'static str, Vec<Suggestion>>) {
    m.insert(
        "heredoc.python:shutil_rmtree",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List directory contents with `os.listdir()` before removal",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `shutil.move()` to archive instead of delete",
            ),
        ],
    );

    m.insert(
        "heredoc.javascript:fs_rmsync",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Use `fs.readdirSync()` to list contents first",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Move files to a backup directory instead of deleting",
            ),
        ],
    );
}

/// Register suggestions for containers.docker pack rules.
#[allow(clippy::too_many_lines)]
fn register_docker_suggestions(m: &mut HashMap<&'static str, Vec<Suggestion>>) {
    m.insert(
        "containers.docker:system-prune",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run `docker system df` to see what would be affected",
            )
            .with_command("docker system df"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Prune specific resources: `docker container prune`, `docker image prune`",
            ),
        ],
    );

    m.insert(
        "containers.docker:volume-prune",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List volumes with `docker volume ls` to see what would be removed",
            )
            .with_command("docker volume ls"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Remove specific volumes with `docker volume rm <name>`",
            ),
        ],
    );

    m.insert(
        "containers.docker:network-prune",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List networks with `docker network ls` to see what would be removed",
            )
            .with_command("docker network ls"),
        ],
    );

    m.insert(
        "containers.docker:image-prune",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List dangling images with `docker images -f dangling=true`",
            )
            .with_command("docker images -f dangling=true"),
        ],
    );

    m.insert(
        "containers.docker:container-prune",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List stopped containers with `docker ps -a -f status=exited`",
            )
            .with_command("docker ps -a -f status=exited"),
        ],
    );

    m.insert(
        "containers.docker:rm-force",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Stop container first with `docker stop`, then `docker rm`",
            ),
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check container status with `docker ps -a`",
            )
            .with_command("docker ps -a"),
        ],
    );

    m.insert(
        "containers.docker:rmi-force",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check if image is in use with `docker ps -a --filter ancestor=<image>`",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Remove without force to see dependency errors first",
            ),
        ],
    );

    m.insert(
        "containers.docker:volume-rm",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Inspect volume with `docker volume inspect <name>` to verify contents",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up volume data before removing",
            ),
        ],
    );

    m.insert(
        "containers.docker:stop-all",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List running containers with `docker ps` to see what would be stopped",
            )
            .with_command("docker ps"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Stop specific containers by name instead of all",
            ),
        ],
    );
}

/// Register suggestions for kubernetes.kubectl pack rules.
#[allow(clippy::too_many_lines)]
fn register_kubernetes_suggestions(m: &mut HashMap<&'static str, Vec<Suggestion>>) {
    m.insert(
        "kubernetes.kubectl:delete-namespace",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run `kubectl get all -n <namespace>` to see all resources that would be deleted",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `kubectl delete <resource-type> --dry-run=client` to preview",
            )
            .with_command("kubectl delete namespace <name> --dry-run=client"),
        ],
    );

    m.insert(
        "kubernetes.kubectl:delete-all",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run with `--dry-run=client` to preview what would be deleted",
            )
            .with_command("kubectl delete <resource> --all --dry-run=client"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Delete specific resources by name instead of --all",
            ),
        ],
    );

    m.insert(
        "kubernetes.kubectl:delete-all-namespaces",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run `kubectl get <resource> -A` to see what exists across namespaces",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Target a specific namespace with `-n <namespace>` instead of -A",
            ),
        ],
    );

    m.insert(
        "kubernetes.kubectl:drain-node",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List pods on node with `kubectl get pods --field-selector spec.nodeName=<node>`",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `kubectl cordon` first to prevent new pods, then drain",
            )
            .with_command("kubectl cordon <node>"),
        ],
    );

    m.insert(
        "kubernetes.kubectl:cordon-node",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check node status with `kubectl get node <node>`",
            ),
            Suggestion::new(
                SuggestionKind::Documentation,
                "Cordon marks node unschedulable; existing pods continue running",
            ),
        ],
    );

    m.insert(
        "kubernetes.kubectl:taint-noexecute",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List pods on node to see what would be evicted",
            )
            .with_command("kubectl get pods --field-selector spec.nodeName=<node>"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `NoSchedule` taint to prevent new pods without evicting existing ones",
            ),
        ],
    );

    m.insert(
        "kubernetes.kubectl:delete-workload",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Use `--dry-run=client` to preview the deletion",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Scale to 0 replicas first to gracefully stop pods",
            )
            .with_command("kubectl scale deployment <name> --replicas=0"),
        ],
    );

    m.insert(
        "kubernetes.kubectl:delete-pvc",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check PVC's reclaim policy with `kubectl get pv <pv-name> -o jsonpath='{.spec.persistentVolumeReclaimPolicy}'`",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up data before deleting PVC if ReclaimPolicy is Delete",
            ),
        ],
    );

    m.insert(
        "kubernetes.kubectl:delete-pv",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check if PV is bound with `kubectl get pv <name>`",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Ensure data is backed up before deleting persistent volume",
            ),
        ],
    );

    m.insert(
        "kubernetes.kubectl:scale-to-zero",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check current replicas with `kubectl get deployment <name>`",
            ),
            Suggestion::new(
                SuggestionKind::Documentation,
                "Scaling to 0 stops all pods; use for maintenance or decommissioning",
            ),
        ],
    );

    m.insert(
        "kubernetes.kubectl:delete-force",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Remove --force --grace-period=0 to allow graceful termination",
            ),
            Suggestion::new(
                SuggestionKind::Documentation,
                "Force deletion skips graceful shutdown; use only for stuck resources",
            ),
        ],
    );
}

/// Register suggestions for database pack rules (`PostgreSQL`, `MongoDB`, `Redis`, `SQLite`).
#[allow(clippy::too_many_lines)]
fn register_database_suggestions(m: &mut HashMap<&'static str, Vec<Suggestion>>) {
    // PostgreSQL suggestions
    m.insert(
        "database.postgresql:drop-database",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List databases with `\\l` in psql to verify target",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up with `pg_dump -Fc <database> > backup.dump` first",
            )
            .with_command("pg_dump -Fc <database> > backup.dump"),
        ],
    );

    m.insert(
        "database.postgresql:drop-table",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List tables with `\\dt` in psql to verify target",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up table with `pg_dump -t <table> <database>`",
            ),
        ],
    );

    m.insert(
        "database.postgresql:drop-schema",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List schema contents with `\\dn+` in psql",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up schema with `pg_dump -n <schema> <database>`",
            ),
        ],
    );

    m.insert(
        "database.postgresql:truncate-table",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check row count with `SELECT count(*) FROM <table>`",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up data with `COPY <table> TO '/tmp/backup.csv'` first",
            ),
        ],
    );

    m.insert(
        "database.postgresql:delete-without-where",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Add a WHERE clause to limit deletion scope",
            ),
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run `SELECT count(*) FROM <table>` to see row count",
            ),
        ],
    );

    m.insert(
        "database.postgresql:dropdb-cli",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List databases with `psql -l` to verify target",
            )
            .with_command("psql -l"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up with `pg_dump` before dropping",
            ),
        ],
    );

    m.insert(
        "database.postgresql:pg-dump-clean",
        vec![
            Suggestion::new(
                SuggestionKind::Documentation,
                "The --clean flag drops objects before creating; be careful on restore",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Remove --clean flag to create without dropping existing objects",
            ),
        ],
    );

    // MongoDB suggestions
    m.insert(
        "database.mongodb:drop-database",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List databases with `show dbs` to verify target",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up with `mongodump --db <database>` first",
            )
            .with_command("mongodump --db <database>"),
        ],
    );

    m.insert(
        "database.mongodb:drop-collection",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List collections with `show collections` to verify target",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up with `mongoexport --collection <name>` first",
            ),
        ],
    );

    m.insert(
        "database.mongodb:delete-all",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check document count with `db.collection.countDocuments({})`",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Add filter criteria to `deleteMany()` to limit scope",
            ),
        ],
    );

    m.insert(
        "database.mongodb:mongorestore-drop",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Remove --drop flag to merge with existing data",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up existing data with `mongodump` before restoring with --drop",
            ),
        ],
    );

    m.insert(
        "database.mongodb:collection-drop",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check collection stats with `db.collection.stats()`",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Export collection with `mongoexport` before dropping",
            ),
        ],
    );

    // Redis suggestions
    m.insert(
        "database.redis:flushall",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check key counts per database with `INFO keyspace`",
            )
            .with_command("redis-cli INFO keyspace"),
            Suggestion::new(
                SuggestionKind::Documentation,
                "FLUSHALL deletes ALL keys in ALL databases; FLUSHDB affects only current database",
            ),
        ],
    );

    m.insert(
        "database.redis:flushdb",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check key count with `DBSIZE`",
            )
            .with_command("redis-cli DBSIZE"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Export keys with `redis-cli --scan` before flushing",
            ),
        ],
    );

    m.insert(
        "database.redis:debug-crash",
        vec![Suggestion::new(
            SuggestionKind::Documentation,
            "DEBUG SEGFAULT/CRASH will crash the Redis server; only use for testing",
        )],
    );

    m.insert(
        "database.redis:debug-sleep",
        vec![Suggestion::new(
            SuggestionKind::Documentation,
            "DEBUG SLEEP blocks the server; avoid in production",
        )],
    );

    m.insert(
        "database.redis:shutdown",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check connected clients with `CLIENT LIST`",
            )
            .with_command("redis-cli CLIENT LIST"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Use `BGSAVE` to persist data before shutdown",
            )
            .with_command("redis-cli BGSAVE"),
        ],
    );

    m.insert(
        "database.redis:config-dangerous",
        vec![Suggestion::new(
            SuggestionKind::Documentation,
            "CONFIG SET for dir/dbfilename can be exploited for arbitrary file writes",
        )],
    );

    // SQLite suggestions
    m.insert(
        "database.sqlite:drop-table",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List tables with `.tables` to verify target",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up database with `.backup <filename>` first",
            )
            .with_command(".backup backup.db"),
        ],
    );

    m.insert(
        "database.sqlite:delete-without-where",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Add a WHERE clause to limit deletion scope",
            ),
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check row count with `SELECT count(*) FROM <table>`",
            ),
        ],
    );

    m.insert(
        "database.sqlite:vacuum-into",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check if target file exists before VACUUM INTO",
            ),
            Suggestion::new(
                SuggestionKind::Documentation,
                "VACUUM INTO overwrites the target file if it exists",
            ),
        ],
    );

    m.insert(
        "database.sqlite:sqlite3-stdin",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Review the SQL file contents before executing",
            )
            .with_command("cat <file.sql>"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up database with `.backup` before running SQL from file",
            ),
        ],
    );

    // MySQL suggestions
    m.insert(
        "database.mysql:drop-database",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List databases with `SHOW DATABASES` to verify target",
            )
            .with_command("mysql -e 'SHOW DATABASES;'"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up with `mysqldump` before dropping",
            )
            .with_command("mysqldump -h host -u user -p <database> > backup.sql"),
        ],
    );

    m.insert(
        "database.mysql:drop-table",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List tables with `SHOW TABLES` to verify target",
            )
            .with_command("mysql -e 'SHOW TABLES FROM <database>;'"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up table with `mysqldump` before dropping",
            )
            .with_command("mysqldump -h host -u user -p <database> <table> > table_backup.sql"),
        ],
    );

    m.insert(
        "database.mysql:truncate-table",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check row count with `SELECT COUNT(*) FROM <table>`",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use `DELETE FROM` for transactional safety (can be rolled back)",
            )
            .with_command("DELETE FROM <table>;  -- Slower but transactional"),
            Suggestion::new(
                SuggestionKind::Documentation,
                "MySQL's TRUNCATE is NOT transactional and cannot be rolled back",
            ),
        ],
    );

    m.insert(
        "database.mysql:delete-without-where",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Add a WHERE clause to limit deletion scope",
            )
            .with_command("DELETE FROM <table> WHERE <condition>;"),
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Run `SELECT COUNT(*) FROM <table>` to see row count",
            ),
        ],
    );

    m.insert(
        "database.mysql:mysqladmin-drop",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "List databases with `mysql -e 'SHOW DATABASES;'` to verify target",
            )
            .with_command("mysql -e 'SHOW DATABASES;'"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Back up with `mysqldump` before dropping",
            )
            .with_command("mysqldump -h host -u user -p <database> > backup.sql"),
        ],
    );

    m.insert(
        "database.mysql:mysqldump-add-drop-database",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Remove --add-drop-database flag for safer restores",
            )
            .with_command("mysqldump <database> > backup.sql"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Restore to a new database first, verify, then swap",
            ),
        ],
    );

    m.insert(
        "database.mysql:mysqldump-add-drop-table",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use --skip-add-drop-table to disable table drops on restore",
            )
            .with_command("mysqldump --skip-add-drop-table <database> > backup.sql"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Restore to a new database first, then verify before swapping",
            ),
        ],
    );

    m.insert(
        "database.mysql:grant-all",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Grant privileges on a specific database instead of all",
            )
            .with_command("GRANT ALL ON <database>.* TO 'user'@'host';"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Grant specific privileges instead of ALL",
            )
            .with_command("GRANT SELECT, INSERT, UPDATE ON <database>.* TO 'user'@'host';"),
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Review current grants with `SHOW GRANTS FOR 'user'@'host'`",
            ),
        ],
    );

    m.insert(
        "database.mysql:drop-user",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Review user's grants before dropping",
            )
            .with_command("SHOW GRANTS FOR 'user'@'host';"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Lock the account instead of dropping for temporary disablement",
            )
            .with_command("ALTER USER 'user'@'host' ACCOUNT LOCK;"),
        ],
    );

    m.insert(
        "database.mysql:reset-master",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Check replication status and connected replicas first",
            )
            .with_command("SHOW SLAVE HOSTS;"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use PURGE BINARY LOGS for selective cleanup instead",
            )
            .with_command("PURGE BINARY LOGS BEFORE '<date>';"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Ensure all replicas are stopped and reconfigured after RESET MASTER",
            ),
        ],
    );
}

/// Register suggestions for system.permissions pack rules.
fn register_system_permissions_suggestions(m: &mut HashMap<&'static str, Vec<Suggestion>>) {
    // chmod 777 (world writable)
    m.insert(
        "system.permissions:chmod-777",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use 755 for directories (rwxr-xr-x) or 644 for files (rw-r--r--) instead",
            )
            .with_command("chmod 755 <dir>  # or chmod 644 <file>"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Grant group write with 775 if collaboration needed",
            )
            .with_command("chmod 775 <path>"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Use ACLs for fine-grained access control instead of world-writable",
            )
            .with_command("setfacl -m u:username:rwx <path>"),
            Suggestion::new(
                SuggestionKind::Documentation,
                "World-writable files (777) allow any user to read, write, and execute",
            ),
        ],
    );

    // chmod -R on system directories
    m.insert(
        "system.permissions:chmod-recursive-root",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Preview what would change with find before recursive chmod",
            )
            .with_command("find <path> -type f -perm <mode> | head -20"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Apply to specific file types rather than everything recursively",
            )
            .with_command("find <path> -type f -name '*.sh' -exec chmod 755 {} \\;"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Changing permissions on /etc, /usr, /var, etc. can break system services",
            ),
        ],
    );

    // chown -R on system directories
    m.insert(
        "system.permissions:chown-recursive-root",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Preview what would change before recursive chown",
            )
            .with_command("find <path> -type f -user <current> | head -20"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Apply to specific directories rather than system root paths",
            )
            .with_command("chown -R user:group /home/user/specific-dir"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "System directories have specific ownership for security; changing them can break services",
            ),
        ],
    );

    // chmod setuid
    m.insert(
        "system.permissions:chmod-setuid",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use sudo or capabilities instead of setuid for privilege escalation",
            )
            .with_command("sudo setcap cap_net_bind_service=+ep <binary>"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Setuid binaries run as owner regardless of who executes them - security risk",
            ),
            Suggestion::new(
                SuggestionKind::Documentation,
                "Setuid (4xxx or u+s) allows any user to run the file with owner's privileges",
            ),
        ],
    );

    // chmod setgid
    m.insert(
        "system.permissions:chmod-setgid",
        vec![
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Use group ACLs for shared directory access instead of setgid",
            )
            .with_command("setfacl -d -m g:groupname:rwx <directory>"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Setgid on directories makes new files inherit the directory's group",
            ),
            Suggestion::new(
                SuggestionKind::Documentation,
                "Setgid (2xxx or g+s) on executables runs with group privileges",
            ),
        ],
    );

    // chown to root
    m.insert(
        "system.permissions:chown-to-root",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Verify you're changing the correct files before transferring to root",
            )
            .with_command("ls -la <path>"),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Files owned by root often require sudo to modify; ensure this is intended",
            ),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Consider using a service account instead of root for daemons",
            ),
        ],
    );

    // setfacl recursive on system dirs
    m.insert(
        "system.permissions:setfacl-all",
        vec![
            Suggestion::new(
                SuggestionKind::PreviewFirst,
                "Preview current ACLs before modifying recursively",
            )
            .with_command("getfacl -R <path> | head -50"),
            Suggestion::new(
                SuggestionKind::SaferAlternative,
                "Apply ACLs to specific subdirectories rather than system paths",
            ),
            Suggestion::new(
                SuggestionKind::WorkflowFix,
                "Recursive ACL changes on /etc, /var, etc. can break service permissions",
            ),
        ],
    );
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn suggestion_kind_labels() {
        assert_eq!(SuggestionKind::PreviewFirst.label(), "Preview first");
        assert_eq!(
            SuggestionKind::SaferAlternative.label(),
            "Safer alternative"
        );
        assert_eq!(SuggestionKind::WorkflowFix.label(), "Workflow fix");
        assert_eq!(SuggestionKind::Documentation.label(), "Documentation");
        assert_eq!(SuggestionKind::AllowSafely.label(), "Allow safely");
    }

    #[test]
    fn suggestion_builder_pattern() {
        let suggestion = Suggestion::new(SuggestionKind::PreviewFirst, "Test suggestion")
            .with_command("git status")
            .with_url("https://example.com");

        assert_eq!(suggestion.kind, SuggestionKind::PreviewFirst);
        assert_eq!(suggestion.text, "Test suggestion");
        assert_eq!(suggestion.command, Some("git status".to_string()));
        assert_eq!(suggestion.url, Some("https://example.com".to_string()));
    }

    #[test]
    fn registry_lookup_returns_suggestions() {
        let suggestions = get_suggestions("core.git:reset-hard");
        assert!(suggestions.is_some());
        let suggestions = suggestions.unwrap();
        assert!(!suggestions.is_empty());
        assert!(suggestions.len() >= 3); // At least preview, alternative, workflow
    }

    #[test]
    fn registry_lookup_returns_none_for_unknown_rule() {
        let suggestions = get_suggestions("nonexistent:rule");
        assert!(suggestions.is_none());
    }

    #[test]
    fn get_suggestion_by_kind_works() {
        let preview = get_suggestion_by_kind("core.git:reset-hard", SuggestionKind::PreviewFirst);
        assert!(preview.is_some());
        assert!(preview.unwrap().text.contains("git diff"));

        let safer = get_suggestion_by_kind("core.git:reset-hard", SuggestionKind::SaferAlternative);
        assert!(safer.is_some());
        assert!(safer.unwrap().text.contains("soft"));
    }

    #[test]
    fn suggestions_serialize_to_json() {
        let suggestion =
            Suggestion::new(SuggestionKind::PreviewFirst, "Test").with_command("git status");

        let json = serde_json::to_string(&suggestion).unwrap();
        assert!(json.contains("\"kind\":\"preview_first\""));
        assert!(json.contains("\"text\":\"Test\""));
        assert!(json.contains("\"command\":\"git status\""));
        // url should be skipped when None
        assert!(!json.contains("\"url\""));
    }

    #[test]
    fn suggestions_deserialize_from_json() {
        let json = r#"{"kind":"safer_alternative","text":"Use safer option","command":"git reset --soft"}"#;
        let suggestion: Suggestion = serde_json::from_str(json).unwrap();

        assert_eq!(suggestion.kind, SuggestionKind::SaferAlternative);
        assert_eq!(suggestion.text, "Use safer option");
        assert_eq!(suggestion.command, Some("git reset --soft".to_string()));
        assert_eq!(suggestion.url, None);
    }

    #[test]
    fn registry_has_core_git_rules() {
        // Verify expected core.git rules have suggestions
        // These must match actual pattern names from src/packs/core/git.rs
        let expected_rules = [
            "core.git:reset-hard",
            "core.git:reset-merge",
            "core.git:clean-force",
            "core.git:push-force-long",
            "core.git:push-force-short",
            "core.git:checkout-discard",
            "core.git:checkout-ref-discard",
            "core.git:branch-force-delete",
            "core.git:restore-worktree",
            "core.git:restore-worktree-explicit",
            "core.git:stash-drop",
            "core.git:stash-clear",
        ];

        for rule in expected_rules {
            assert!(
                get_suggestions(rule).is_some(),
                "Expected suggestions for {rule}"
            );
        }
    }

    #[test]
    fn registry_has_core_filesystem_rules() {
        // Verify expected core.filesystem rules have suggestions
        // These must match actual pattern names from src/packs/core/filesystem.rs
        let expected_rules = [
            "core.filesystem:rm-rf-root-home",
            "core.filesystem:rm-rf-general",
            "core.filesystem:rm-r-f-separate",
            "core.filesystem:rm-recursive-force-long",
        ];

        for rule in expected_rules {
            assert!(
                get_suggestions(rule).is_some(),
                "Expected suggestions for {rule}"
            );
        }
    }

    #[test]
    fn registry_has_heredoc_rules() {
        // Verify heredoc rules use canonical colon format (pack_id:pattern_name)
        let expected_rules = [
            "heredoc.python:shutil_rmtree",
            "heredoc.javascript:fs_rmsync",
        ];

        for rule in expected_rules {
            assert!(
                get_suggestions(rule).is_some(),
                "Expected suggestions for {rule}"
            );
            // Verify the format uses colon separator (matches RuleId format)
            assert!(
                rule.contains(':'),
                "Rule ID should use colon format: {rule}"
            );
        }
    }

    #[test]
    fn all_suggestion_kinds_are_used() {
        // Verify all SuggestionKind variants are used at least once in the registry
        let mut kinds_found = std::collections::HashSet::new();

        for suggestions in SUGGESTION_REGISTRY.values() {
            for suggestion in suggestions {
                kinds_found.insert(suggestion.kind);
            }
        }

        // Note: AllowSafely may not be used yet - that's intentional for 1gt.5.2
        assert!(kinds_found.contains(&SuggestionKind::PreviewFirst));
        assert!(kinds_found.contains(&SuggestionKind::SaferAlternative));
        assert!(kinds_found.contains(&SuggestionKind::WorkflowFix));
        assert!(kinds_found.contains(&SuggestionKind::Documentation));
        // AllowSafely will be added when allowlist integration is complete
    }

    #[test]
    fn suggestions_have_stable_order() {
        // Verify suggestions for a rule always come in the same order
        let suggestions1 = get_suggestions("core.git:reset-hard").unwrap();
        let suggestions2 = get_suggestions("core.git:reset-hard").unwrap();

        assert_eq!(suggestions1.len(), suggestions2.len());
        for (s1, s2) in suggestions1.iter().zip(suggestions2.iter()) {
            assert_eq!(s1.kind, s2.kind);
            assert_eq!(s1.text, s2.text);
        }
    }

    #[test]
    fn coverage_all_core_pack_patterns_have_suggestions() {
        // This test dynamically checks all destructive patterns in core.* packs
        // against the suggestion registry, ensuring complete coverage.
        //
        // This satisfies the acceptance criteria for git_safety_guard-1gt.5.2:
        // "A coverage test that asserts all core destructive patterns have at least 1 suggestion."

        use crate::packs::REGISTRY;

        let core_packs = ["core.git", "core.filesystem"];
        let mut missing_suggestions = Vec::new();

        for pack_id in core_packs {
            let pack = REGISTRY
                .get(pack_id)
                .unwrap_or_else(|| panic!("Pack {pack_id} should exist"));

            for pattern in &pack.destructive_patterns {
                if let Some(pattern_name) = pattern.name {
                    let rule_id = format!("{pack_id}:{pattern_name}");
                    if get_suggestions(&rule_id).is_none() {
                        missing_suggestions.push(rule_id);
                    }
                }
            }
        }

        assert!(
            missing_suggestions.is_empty(),
            "The following core rules are missing suggestions:\n  {}",
            missing_suggestions.join("\n  ")
        );
    }

    #[test]
    fn coverage_core_patterns_count_matches_registry() {
        // Verify the number of patterns with suggestions matches actual pack definitions.
        // This catches drift between packs and suggestion registry.

        use crate::packs::REGISTRY;

        // Count patterns in core.git
        let git_pack = REGISTRY.get("core.git").unwrap();
        let git_pattern_count = git_pack
            .destructive_patterns
            .iter()
            .filter(|p| p.name.is_some())
            .count();

        // Count suggestions for core.git
        let git_suggestion_count = SUGGESTION_REGISTRY
            .keys()
            .filter(|k| k.starts_with("core.git:"))
            .count();

        assert_eq!(
            git_pattern_count, git_suggestion_count,
            "core.git pattern count ({git_pattern_count}) != suggestion count ({git_suggestion_count})"
        );

        // Count patterns in core.filesystem
        let fs_pack = REGISTRY.get("core.filesystem").unwrap();
        let fs_pattern_count = fs_pack
            .destructive_patterns
            .iter()
            .filter(|p| p.name.is_some())
            .count();

        // Count suggestions for core.filesystem
        let fs_suggestion_count = SUGGESTION_REGISTRY
            .keys()
            .filter(|k| k.starts_with("core.filesystem:"))
            .count();

        assert_eq!(
            fs_pattern_count, fs_suggestion_count,
            "core.filesystem pattern count ({fs_pattern_count}) != suggestion count ({fs_suggestion_count})"
        );
    }

    #[test]
    fn registry_has_docker_rules() {
        let expected = [
            "containers.docker:system-prune",
            "containers.docker:volume-prune",
            "containers.docker:network-prune",
            "containers.docker:image-prune",
            "containers.docker:container-prune",
            "containers.docker:rm-force",
            "containers.docker:rmi-force",
            "containers.docker:volume-rm",
            "containers.docker:stop-all",
        ];
        for rule in expected {
            assert!(get_suggestions(rule).is_some(), "Missing: {rule}");
        }
    }

    #[test]
    fn registry_has_kubernetes_rules() {
        let expected = [
            "kubernetes.kubectl:delete-namespace",
            "kubernetes.kubectl:delete-all",
            "kubernetes.kubectl:delete-all-namespaces",
            "kubernetes.kubectl:drain-node",
            "kubernetes.kubectl:cordon-node",
            "kubernetes.kubectl:taint-noexecute",
            "kubernetes.kubectl:delete-workload",
            "kubernetes.kubectl:delete-pvc",
            "kubernetes.kubectl:delete-pv",
            "kubernetes.kubectl:scale-to-zero",
            "kubernetes.kubectl:delete-force",
        ];
        for rule in expected {
            assert!(get_suggestions(rule).is_some(), "Missing: {rule}");
        }
    }

    #[test]
    fn registry_has_database_rules() {
        let expected = [
            // PostgreSQL
            "database.postgresql:drop-database",
            "database.postgresql:drop-table",
            "database.postgresql:drop-schema",
            "database.postgresql:truncate-table",
            "database.postgresql:delete-without-where",
            "database.postgresql:dropdb-cli",
            "database.postgresql:pg-dump-clean",
            // MongoDB
            "database.mongodb:drop-database",
            "database.mongodb:drop-collection",
            "database.mongodb:delete-all",
            "database.mongodb:mongorestore-drop",
            "database.mongodb:collection-drop",
            // Redis
            "database.redis:flushall",
            "database.redis:flushdb",
            "database.redis:debug-crash",
            "database.redis:debug-sleep",
            "database.redis:shutdown",
            "database.redis:config-dangerous",
            // SQLite
            "database.sqlite:drop-table",
            "database.sqlite:delete-without-where",
            "database.sqlite:vacuum-into",
            "database.sqlite:sqlite3-stdin",
            // MySQL
            "database.mysql:drop-database",
            "database.mysql:drop-table",
            "database.mysql:truncate-table",
            "database.mysql:delete-without-where",
            "database.mysql:mysqladmin-drop",
            "database.mysql:mysqldump-add-drop-database",
            "database.mysql:mysqldump-add-drop-table",
            "database.mysql:grant-all",
            "database.mysql:drop-user",
            "database.mysql:reset-master",
        ];
        for rule in expected {
            assert!(get_suggestions(rule).is_some(), "Missing: {rule}");
        }
    }

    #[test]
    fn registry_has_system_permissions_rules() {
        let expected = [
            "system.permissions:chmod-777",
            "system.permissions:chmod-recursive-root",
            "system.permissions:chown-recursive-root",
            "system.permissions:chmod-setuid",
            "system.permissions:chmod-setgid",
            "system.permissions:chown-to-root",
            "system.permissions:setfacl-all",
        ];
        for rule in expected {
            assert!(get_suggestions(rule).is_some(), "Missing: {rule}");
        }
    }

    // === Correctness & Coverage Tests (git_safety_guard-1gt.5.5) ===

    #[test]
    fn coverage_all_suggestion_rules_are_valid() {
        // Verify every rule_id in SUGGESTION_REGISTRY matches a real pack/pattern.
        use crate::packs::REGISTRY;
        let mut invalid = Vec::new();
        for rule_id in SUGGESTION_REGISTRY.keys() {
            let parts: Vec<&str> = rule_id.split(':').collect();
            if parts.len() != 2 {
                invalid.push(format!("{rule_id} (bad format)"));
                continue;
            }
            let (pack_id, pattern_name) = (parts[0], parts[1]);
            if pack_id.starts_with("heredoc.") {
                continue;
            } // Different namespace
            let Some(pack) = REGISTRY.get(pack_id) else {
                invalid.push(format!("{rule_id} (pack not found)"));
                continue;
            };
            if !pack
                .destructive_patterns
                .iter()
                .any(|p| p.name == Some(pattern_name))
            {
                invalid.push(format!("{rule_id} (pattern not found)"));
            }
        }
        assert!(
            invalid.is_empty(),
            "Invalid suggestion rules:\n  {}",
            invalid.join("\n  ")
        );
    }

    #[test]
    fn suggestions_do_not_suggest_destructive_commands() {
        // Suggestions must not recommend running dangerous commands.
        // Note: --force-with-lease is a SAFE alternative to --force, so we exclude it.
        let forbidden = [
            "rm -rf",
            "rm -fr",
            "git reset --hard",
            "git clean -fd",
            "docker system prune -a",
        ];
        let mut violations = Vec::new();
        for (rule_id, suggestions) in SUGGESTION_REGISTRY.iter() {
            for s in suggestions {
                if let Some(cmd) = &s.command {
                    // Special case: git push --force-with-lease is safe
                    if cmd.contains("--force-with-lease") {
                        continue;
                    }
                    // Check for bare --force or -f (not in a safe context)
                    let has_dangerous_force = (cmd.contains("git push")
                        || cmd.contains("git push"))
                        && (cmd.contains(" --force ")
                            || cmd.contains(" --force\"")
                            || cmd.ends_with(" --force")
                            || cmd.contains(" -f "));
                    if has_dangerous_force {
                        violations.push(format!("{rule_id}: '{cmd}' has dangerous force flag"));
                    }
                    for f in &forbidden {
                        if cmd.to_lowercase().contains(&f.to_lowercase()) {
                            violations.push(format!("{rule_id}: '{cmd}' contains '{f}'"));
                        }
                    }
                }
            }
        }
        assert!(
            violations.is_empty(),
            "Dangerous commands in suggestions:\n  {}",
            violations.join("\n  ")
        );
    }

    #[test]
    fn suggestions_ordering_is_deterministic() {
        // Same rule should return suggestions in same order every time.
        let rules = ["core.git:reset-hard", "containers.docker:system-prune"];
        for rule in rules {
            let s1 = get_suggestions(rule);
            let s2 = get_suggestions(rule);
            let s1_len = s1.map(<[Suggestion]>::len);
            let s2_len = s2.map(<[Suggestion]>::len);
            assert_eq!(s1_len, s2_len, "Count differs for {rule}");
            if let (Some(a), Some(b)) = (s1, s2) {
                for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
                    assert_eq!(x.text, y.text, "Mismatch at {i} for {rule}");
                }
            }
        }
    }

    #[test]
    fn suggestion_registry_keys_iterate_consistently() {
        let k1: Vec<_> = SUGGESTION_REGISTRY.keys().collect();
        let k2: Vec<_> = SUGGESTION_REGISTRY.keys().collect();
        assert_eq!(k1, k2, "Registry iteration order changed");
    }

    // === Fallback Explanation Tests ===

    #[test]
    fn fallback_explanation_with_pack_and_pattern() {
        let exp = fallback_explanation(Some("core.git"), Some("reset-hard"));
        assert!(exp.contains("core.git:reset-hard"));
        assert!(exp.contains("dcg explain"));
        assert!(exp.contains("destructive pattern"));
    }

    #[test]
    fn fallback_explanation_with_pack_only() {
        let exp = fallback_explanation(Some("core.git"), None);
        assert!(exp.contains("core.git"));
        assert!(exp.contains("dcg explain"));
        assert!(!exp.contains(':')); // No pattern separator
    }

    #[test]
    fn fallback_explanation_with_pattern_only() {
        let exp = fallback_explanation(None, Some("reset-hard"));
        assert!(exp.contains("reset-hard"));
        assert!(exp.contains("dcg explain"));
    }

    #[test]
    fn fallback_explanation_with_nothing() {
        let exp = fallback_explanation(None, None);
        assert!(exp.contains("destructive pattern"));
        assert!(exp.contains("dcg explain"));
    }

    #[test]
    fn get_explanation_returns_explicit_when_present() {
        let exp = get_explanation(
            Some("Custom explanation here"),
            Some("core.git"),
            Some("reset-hard"),
        );
        assert_eq!(exp, "Custom explanation here");
    }

    #[test]
    fn get_explanation_uses_fallback_when_none() {
        let exp = get_explanation(None, Some("core.git"), Some("reset-hard"));
        assert!(exp.contains("core.git:reset-hard"));
        assert!(exp.contains("dcg explain"));
    }

    #[test]
    fn get_explanation_uses_fallback_when_empty() {
        let exp = get_explanation(Some(""), Some("core.git"), Some("reset-hard"));
        assert!(exp.contains("core.git:reset-hard"));
        assert!(exp.contains("dcg explain"));
    }

    #[test]
    fn get_explanation_uses_fallback_when_whitespace_only() {
        let exp = get_explanation(Some("   "), Some("core.git"), Some("reset-hard"));
        assert!(exp.contains("core.git:reset-hard"));
        assert!(exp.contains("dcg explain"));
    }

    #[test]
    fn fallback_is_neutral_and_concise() {
        let exp = fallback_explanation(Some("core.git"), Some("reset-hard"));
        // Should not contain scaremongering language
        assert!(!exp.to_lowercase().contains("danger"));
        assert!(!exp.to_lowercase().contains("warning"));
        assert!(!exp.to_lowercase().contains("critical"));
        // Should be reasonably short (2-4 sentences = ~50-200 words)
        let word_count = exp.split_whitespace().count();
        assert!(
            word_count < 50,
            "Fallback should be concise: {word_count} words"
        );
    }
}