modum 0.6.14

Workspace lint tool for Rust naming and API-shape policy
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
use std::path::PathBuf;

use serde::{Serialize, Serializer, ser::SerializeStruct};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum LintProfile {
    Core,
    Surface,
    #[default]
    Strict,
}

impl LintProfile {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Core => "core",
            Self::Surface => "surface",
            Self::Strict => "strict",
        }
    }
}

impl std::str::FromStr for LintProfile {
    type Err = String;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        match raw {
            "core" => Ok(Self::Core),
            "surface" => Ok(Self::Surface),
            "strict" => Ok(Self::Strict),
            _ => Err(format!(
                "invalid profile `{raw}`; expected core|surface|strict"
            )),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiagnosticCodeInfo {
    pub profile: LintProfile,
    pub summary: &'static str,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub enum DiagnosticLevel {
    Warning,
    Error,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum DiagnosticClass {
    ToolError,
    ToolWarning,
    PolicyError { code: String },
    PolicyWarning { code: String },
    AdvisoryWarning { code: String },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DiagnosticFixKind {
    ReplacePath,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct DiagnosticFix {
    pub kind: DiagnosticFixKind,
    pub replacement: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DiagnosticGuidance {
    pub why: String,
    pub address: String,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Diagnostic {
    pub class: DiagnosticClass,
    pub file: Option<PathBuf>,
    pub line: Option<usize>,
    pub fix: Option<DiagnosticFix>,
    pub message: String,
}

impl Diagnostic {
    pub fn error(file: Option<PathBuf>, line: Option<usize>, message: impl Into<String>) -> Self {
        Self {
            class: DiagnosticClass::ToolError,
            file,
            line,
            fix: None,
            message: message.into(),
        }
    }

    pub fn warning(file: Option<PathBuf>, line: Option<usize>, message: impl Into<String>) -> Self {
        Self {
            class: DiagnosticClass::ToolWarning,
            file,
            line,
            fix: None,
            message: message.into(),
        }
    }

    pub fn policy(
        file: Option<PathBuf>,
        line: Option<usize>,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            class: DiagnosticClass::PolicyWarning { code: code.into() },
            file,
            line,
            fix: None,
            message: message.into(),
        }
    }

    pub fn policy_error(
        file: Option<PathBuf>,
        line: Option<usize>,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            class: DiagnosticClass::PolicyError { code: code.into() },
            file,
            line,
            fix: None,
            message: message.into(),
        }
    }

    pub fn advisory(
        file: Option<PathBuf>,
        line: Option<usize>,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            class: DiagnosticClass::AdvisoryWarning { code: code.into() },
            file,
            line,
            fix: None,
            message: message.into(),
        }
    }

    pub fn with_fix(mut self, fix: DiagnosticFix) -> Self {
        self.fix = Some(fix);
        self
    }

    pub fn guidance(&self) -> Option<DiagnosticGuidance> {
        let code = self.code()?;
        diagnostic_guidance_for_instance(code, &self.message, self.fix.as_ref())
    }

    pub fn level(&self) -> DiagnosticLevel {
        match self.class {
            DiagnosticClass::ToolError | DiagnosticClass::PolicyError { .. } => {
                DiagnosticLevel::Error
            }
            DiagnosticClass::ToolWarning
            | DiagnosticClass::PolicyWarning { .. }
            | DiagnosticClass::AdvisoryWarning { .. } => DiagnosticLevel::Warning,
        }
    }

    pub fn code(&self) -> Option<&str> {
        match &self.class {
            DiagnosticClass::PolicyError { code }
            | DiagnosticClass::PolicyWarning { code }
            | DiagnosticClass::AdvisoryWarning { code } => Some(code),
            DiagnosticClass::ToolError | DiagnosticClass::ToolWarning => None,
        }
    }

    pub fn profile(&self) -> Option<LintProfile> {
        self.code()
            .and_then(|code| diagnostic_code_info(code).map(|info| info.profile))
    }

    pub fn is_error(&self) -> bool {
        matches!(
            self.class,
            DiagnosticClass::ToolError | DiagnosticClass::PolicyError { .. }
        )
    }

    pub fn is_policy_warning(&self) -> bool {
        matches!(self.class, DiagnosticClass::PolicyWarning { .. })
    }

    pub fn is_advisory_warning(&self) -> bool {
        matches!(
            self.class,
            DiagnosticClass::ToolWarning | DiagnosticClass::AdvisoryWarning { .. }
        )
    }

    pub fn is_policy_violation(&self) -> bool {
        matches!(
            self.class,
            DiagnosticClass::PolicyError { .. } | DiagnosticClass::PolicyWarning { .. }
        )
    }

    pub fn included_in_profile(&self, profile: LintProfile) -> bool {
        match &self.class {
            DiagnosticClass::ToolError | DiagnosticClass::ToolWarning => true,
            DiagnosticClass::PolicyError { code }
            | DiagnosticClass::PolicyWarning { code }
            | DiagnosticClass::AdvisoryWarning { code } => {
                profile >= minimum_profile_for_code(code)
            }
        }
    }
}

impl Serialize for Diagnostic {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("Diagnostic", 9)?;
        state.serialize_field("level", &self.level())?;
        state.serialize_field("file", &self.file)?;
        state.serialize_field("line", &self.line)?;
        state.serialize_field("code", &self.code())?;
        state.serialize_field("profile", &self.profile())?;
        state.serialize_field("policy", &self.is_policy_violation())?;
        state.serialize_field("fix", &self.fix)?;
        state.serialize_field("guidance", &self.guidance())?;
        state.serialize_field("message", &self.message)?;
        state.end()
    }
}

fn diagnostic_guidance_parts_for_code(code: &str) -> Option<(&'static str, &'static str)> {
    let (why, address) = match code {
        "namespace_flat_use" | "namespace_flat_pub_use" | "namespace_flat_type_alias" => (
            "The imported leaf still depends on the parent path to read clearly, so flattening it makes call sites harder to scan.",
            "Keep the meaningful qualifier visible at the use site or public surface named in the lint. If you want a shorter path, promote a real parent surface first. Don't flatten it and then smuggle the missing meaning back with an alias or a longer leaf.",
        ),
        "namespace_flat_use_error_surface_follow_through"
        | "namespace_flat_pub_use_error_surface_follow_through"
        | "namespace_flat_type_alias_error_surface_follow_through"
        | "namespace_qualified_error_surface_follow_through" => (
            "The path is still pointing at a flatter `*Error` surface even though the owning facet or owned `Error` boundary now carries the real failure shape.",
            "Move callers to the owned `Error` surface named in the lint and keep that path visible instead of preserving the old flat `*Error` path. If the deeper facet does not exist yet, create it for real, move the leaf value and failure surface together, and then migrate callers. Don't keep the flat `*Error` as a parallel public answer, and don't hide the mismatch with aliases, type aliases, or `#[path = ...]` shims.",
        ),
        "namespace_flat_use_child_facet_follow_through"
        | "namespace_flat_pub_use_child_facet_follow_through"
        | "namespace_flat_type_alias_child_facet_follow_through"
        | "namespace_qualified_child_facet_follow_through" => (
            "The path is still going through the broader owner even though the leaf family now points toward a deeper child facet.",
            "Once the child facet is real, keep that facet visible in the value or type path instead of preserving the broader owner path. Move the leaf value and failure surface together, and don't keep the old broader path alive as a parallel canonical answer. Don't hide the mismatch with aliases, type aliases, or `#[path = ...]` shims.",
        ),
        "namespace_flat_use_preserve_module"
        | "namespace_flat_pub_use_preserve_module"
        | "namespace_flat_type_alias_preserve_module"
        | "namespace_glob_preserve_module" => (
            "The child module is a real facet like `http`, `query`, or `components`, so hiding it erases role information that the path should keep visible.",
            "Import or re-export through the preserved module named in the lint so the facet stays visible. Don't keep the path flat and patch over the loss with a local alias, a glob, or a longer leaf name.",
        ),
        "namespace_flat_use_redundant_leaf_context"
        | "namespace_flat_pub_use_redundant_leaf_context"
        | "namespace_flat_type_alias_redundant_leaf_context"
        | "internal_redundant_leaf_context"
        | "internal_adapter_redundant_leaf_context"
        | "api_redundant_leaf_context" => (
            "The leaf is repeating context that the parent path already supplies, so the name is doing work the module path should already be doing.",
            "Move the repeated context into the path and keep the shorter leaf only if the resulting path is still a complete, standalone name. Don't fake this with a local alias or by mechanically chopping tokens; if the short leaf becomes vague, strengthen the parent path or keep the longer leaf.",
        ),
        "namespace_redundant_qualified_generic" => (
            "The qualifier repeats a generic category the leaf already names, so the written path is longer without adding meaning.",
            "Use the nearer parent surface if it already exists. For owned code, create that parent-surface re-export first, migrate callers to it, and then shorten the written path. Don't silence the lint with a local alias, a compensating leaf rename, or a duplicate shadow surface.",
        ),
        "namespace_overqualified_callsite_path" => (
            "The call site is spelling more of the module scaffolding than it needs, which makes the code heavier without adding comparable meaning.",
            "Import the smallest semantic parent module and call through that instead of keeping the full absolute or deep path inline. Don't flatten all the way to the bare leaf, and don't keep the whole path just because it is technically correct. If the shortest meaningful module still reads badly, the canonical surface likely wants work, and if the owner itself is too broad for the leaf, grow the child facet first instead of freezing the shorter path.",
        ),
        "namespace_aliased_qualified_path" => (
            "The local alias hides the real semantic module path and makes the call site read flatter and more technical than the source surface.",
            "Use the semantic module path directly, or for owned code promote the binding to the nearer parent surface the lint names and use that consistently. Don't keep the technical alias around as the de facto path.",
        ),
        "namespace_family_unsupported_construct" => (
            "This namespace family depends on constructs like macros, cfg gates, or includes that the current source-level pass can't interpret authoritatively.",
            "Treat this as an analysis boundary. Verify the owning family or facet from the expanded or real surface before flattening the path or enshrining the current one. Don't rewrite macros, includes, or cfg-driven code only to satisfy this lint.",
        ),
        "namespace_parent_surface" => (
            "The parent module already exposes the readable caller-facing surface, so reaching through a child module bypasses the intended entrypoint.",
            "Import or re-export the binding from the parent surface named in the lint and make that the canonical caller-facing path. Keep the child path for implementation organization only; don't add the parent alias and then keep callers split across both surfaces.",
        ),
        "namespace_prelude_glob_import" => (
            "A prelude glob hides where names come from, which makes it harder to tell which module is carrying the meaning.",
            "Import the concrete items you need or keep the meaningful module visible at the call site instead of relying on the glob. Don't replace one hidden source with another flatter alias or umbrella prelude.",
        ),
        "internal_catch_all_module" | "api_catch_all_module" => (
            "A bucket module like `util` or `service` forces item names to carry all the meaning because the module itself says almost nothing.",
            "Split the bucket by a real domain or facet, or rename the module to the semantic boundary it actually owns. Don't just move the same mixed contents under another weak bucket like `common`, `shared`, `helpers`, or `types`.",
        ),
        "internal_flat_namespace_preserving_module" => (
            "The flat compound module name is hiding a facet that should stay visible as part of the path.",
            "Reshape the module into the semantic parent and preserved child facet named in the lint, and move the family consistently. Do the filesystem refactor for real: create the actual module files or directories and move the code there instead of mounting the old files through `#[path = ...]`. Don't leave the flat compound module in place and patch over it with longer item names or one-off re-exports.",
        ),
        "internal_organizational_submodule_flatten" => (
            "A pure category module like `errors`, `request`, or `response` is making naming carry the burden instead of the path.",
            "Flatten the family back to the stronger parent surface or rename the module to the actual semantic boundary it owns. If that means changing module layout, create the real files or directories and move the code there; don't keep the old layout behind `#[path = ...]` shims. Don't keep the category module and only rename items inside it, and don't swap it for another organizational bucket.",
        ),
        "internal_path_shim_module" | "api_path_shim_module" => (
            "A `#[path = ...]` module shim makes the namespace say one thing while the filesystem still says another, so the structure only looks fixed.",
            "Create the real module file or directory for the semantic path the code now wants, move or rename the source into it, and remove the `#[path]` attribute. Don't satisfy namespace or semantic-module lints by keeping the old files in place behind a prettier shim.",
        ),
        "internal_redundant_category_suffix" => (
            "The item suffix is repeating the parent category, so the name is noisier without adding meaning.",
            "Drop the repeated category suffix if the parent path already carries it clearly. Don't strip the token mechanically: if the shorter leaf becomes vague or collides, strengthen the parent path or keep the longer leaf.",
        ),
        "api_missing_parent_surface_export" => (
            "The child module has the main binding, but callers still have to reach into that child path instead of using the readable parent surface.",
            "Add the parent-surface re-export the lint is asking for and treat that parent path as the readable caller-facing entrypoint. Don't dodge this by renaming the child module or type, and don't add a second surface while leaving callers on the child path.",
        ),
        "api_anyhow_error_surface" => (
            "A public boundary that leaks `anyhow` hides the crate's real error vocabulary and makes the surface harder to understand and match on.",
            "Expose a crate-owned typed error at the boundary and convert internal `anyhow` failures into it. Keep `anyhow` inside the implementation boundary where it belongs, and don't wrap `anyhow::Error` in a thin alias or pass-through newtype and call that a typed boundary.",
        ),
        "api_string_error_surface" => (
            "A raw string error loses structure, variants, and machine-readable meaning at the API boundary.",
            "Replace the string boundary with a typed error value that names the real failure cases. Don't hide the same free-form text inside a wrapper with one `message` field or defer the modeling work deeper in the workflow.",
        ),
        "api_manual_error_surface" => (
            "The public error shape looks like an ad hoc wrapper instead of a focused typed boundary with named failure cases.",
            "Give the boundary an explicit typed error design that matches what callers need to understand. If the wrapper is only carrying text, replace it with real variants or focused fields instead of polishing the wrapper shell.",
        ),
        "api_semantic_string_scalar" => (
            "The boundary name suggests domain meaning like `url`, `email`, or `path`, but the type is still a raw string.",
            "Parse or validate at the boundary into the focused type the repo wants to use there. If a reusable newtype or domain wrapper already exists, use that instead of renaming the string field or parameter. Don't stop at a plain `type ... = String` alias, a pass-through wrapper, or a later parse step.",
        ),
        "api_semantic_numeric_scalar" => (
            "The boundary name suggests a unit or domain meaning like duration, timestamp, or port, but the type is still a bare number.",
            "Use a typed duration, timestamp, port, or small domain wrapper at the boundary. Don't just rename the field, switch integer widths, or hide the same raw number inside another config object.",
        ),
        "api_raw_id_surface" => (
            "An id at the boundary usually carries validation, formatting, or cross-system meaning that a bare string or integer can't express.",
            "Introduce or reuse a focused id type at the boundary and validate or parse into it there. Avoid silencing the lint by only renaming the raw field, using a plain `type ... = String` alias, or wrapping the same raw value without stronger semantics.",
        ),
        "api_boolean_flag_cluster" => (
            "Several booleans together usually mean the boundary is really describing a smaller mode or policy model.",
            "Replace the cluster with a typed options object or enum that names the actual combinations callers are supposed to choose between. Don't just move the same booleans into another bag or builder and call the boundary modeled.",
        ),
        "api_manual_flag_set" => (
            "Parallel constants and raw bitmask handling usually mean the API is hand-rolling a flags boundary.",
            "Replace the raw integer mask with a typed flags surface or wrapper so the boundary names the allowed combinations directly. Don't keep the same bitmask contract behind helper functions or renamed constants.",
        ),
        "callsite_maybe_some" => (
            "Wrapping a concrete value in `Some(...)` when calling a `maybe_*` API throws away the distinction that method is designed to preserve.",
            "If you already have a concrete value, call the non-`maybe_` setter. Use the `maybe_` form when the caller really is forwarding an `Option<_>`. Don't wrap a value in `Some(...)` just to satisfy the method name.",
        ),
        "api_candidate_semantic_module" | "internal_candidate_semantic_module" => (
            "The sibling family looks like it wants one shared semantic module surface instead of repeating the family marker in every leaf or module name.",
            "Treat this as a design prompt, not an automatic rewrite. Extract the semantic module only if it becomes the real canonical surface for the family and the inner leaves get clearer. If you do it, make it a real refactor: create the module files or directories and move the code instead of keeping the old layout behind `#[path = ...]` shims. Don't create a shadow module while keeping the old flat family equally canonical.",
        ),
        "api_candidate_facet_module" => (
            "The root module is carrying both leaf-specific value-plus-error families and the broader boundary error, so facet ownership is being flattened together.",
            "Move each leaf value-plus-error family under its owning facet and let the root keep the cross-facet boundary. Re-export the good leaf value back out only if it improves ergonomics, but don't flatten the leaf error back next to the root `Error`.",
        ),
        "api_candidate_child_facet_module" => (
            "The module is mixing broader aggregate surface with one validated leaf that likely wants its own owned facet and failure surface.",
            "Create the child facet the lint names only if it becomes the canonical owner for that leaf, move the leaf value and failure surface into it, and let the broader parent keep the aggregate items that depend on it. Do the filesystem refactor for real instead of using `#[path = ...]` shims, and don't keep both the flat module and the new child facet as equal canonical homes for the same leaf family.",
        ),
        "api_boundary_wraps_child_facet_error" => (
            "The broader boundary is still wrapping a flat child companion error even though the child module now looks like it wants a deeper owning facet.",
            "Once the child facet is the real owner, let the broader boundary wrap that child-facet `Error` instead of the flat companion error. Create the child facet for real, move the leaf value and failure surface into it together, and don't keep the flat child error as a parallel public answer from the broader owner. Do the filesystem refactor for real instead of using `#[path = ...]` shims.",
        ),
        "api_owned_facet_companion_error" => (
            "This owner already has its own `Error`, so a parallel leaf-specific companion like `TextError` creates two failure surfaces for the same facet.",
            "Keep the owner's `Error` as the caller-visible failure surface. Leave the companion error as construction detail or generated internals, or split the leaf into a deeper facet only if callers truly need a separate error boundary. Don't export both `TextError`-style companions and `Error` as parallel public answers from the same owner.",
        ),
        "api_candidate_semantic_module_unsupported_construct" => (
            "This scope contains constructs like macros, cfg gates, or includes that the current source-level pass can't interpret authoritatively.",
            "Treat this as an analysis boundary. Inspect the expanded or real surface manually, or upgrade the observation point, before making structural changes here. Don't rewrite macros, includes, or cfg-driven code just to satisfy the current pass.",
        ),
        "api_organizational_submodule_flatten" => (
            "A pure category module like `error`, `request`, or `response` is leaking category structure into the caller-facing path instead of letting the stronger parent surface carry it.",
            "Flatten the public surface back to the stronger parent path or rename the module to the actual semantic boundary it owns. If that means changing module layout, create the real files or directories and move the code there; don't keep the old layout behind `#[path = ...]` shims.",
        ),
        _ if code.starts_with("namespace_") => (
            "The current path shape is hiding meaning in the wrong place, so readers have to recover structure from longer leaves or flatter aliases.",
            "Move the meaning back into the path the lint points at. Fix the owning surface instead of only renaming the local use site or alias.",
        ),
        _ if code.starts_with("internal_") => (
            "The internal module or item shape is making names carry meaning that the structure should carry instead.",
            "Change the structure the lint points at: split the module, strengthen the parent path, or shorten the repeated leaf only when the resulting path stays clear. Avoid bucket renames and token-chop fixes whose only job is to silence the lint.",
        ),
        _ if code.starts_with("api_") => (
            "The caller-facing surface is exposing a shape that hides the real domain or protocol meaning from readers.",
            "Change the caller-facing boundary itself instead of only renaming the current item. Prefer one canonical surface or stronger boundary type over aliases, wrappers, or duplicate paths that preserve the same shape.",
        ),
        _ => return None,
    };

    Some((why, address))
}

pub fn diagnostic_guidance_for_code(
    code: &str,
    fix: Option<&DiagnosticFix>,
) -> Option<DiagnosticGuidance> {
    let (why, address) = diagnostic_guidance_parts_for_code(code)?;

    Some(DiagnosticGuidance {
        why: why.to_string(),
        address: append_direct_rewrite(address, fix),
    })
}

fn diagnostic_guidance_for_instance(
    code: &str,
    message: &str,
    fix: Option<&DiagnosticFix>,
) -> Option<DiagnosticGuidance> {
    let (base_why, base_address) = diagnostic_guidance_parts_for_code(code)?;
    let mut why = base_why.to_string();
    let mut address = base_address.to_string();

    match code {
        "namespace_flat_use" | "namespace_flat_pub_use" | "namespace_flat_type_alias" => {
            if let Some((instance_why, instance_address)) =
                namespace_flat_context_guidance(code, message, fix)
            {
                why = instance_why;
                address = instance_address;
            }
        }
        "namespace_flat_use_error_surface_follow_through"
        | "namespace_flat_pub_use_error_surface_follow_through"
        | "namespace_flat_type_alias_error_surface_follow_through"
        | "namespace_qualified_error_surface_follow_through" => {
            if let Some((instance_why, instance_address)) =
                error_surface_follow_through_guidance(code, message)
            {
                why = instance_why;
                address = instance_address;
            }
        }
        "namespace_flat_use_child_facet_follow_through"
        | "namespace_flat_pub_use_child_facet_follow_through"
        | "namespace_flat_type_alias_child_facet_follow_through"
        | "namespace_qualified_child_facet_follow_through" => {
            if let Some((instance_why, instance_address)) =
                child_facet_value_follow_through_guidance(code, message)
            {
                why = instance_why;
                address = instance_address;
            }
        }
        "namespace_overqualified_callsite_path" => {
            if let Some((instance_why, instance_address)) = overqualified_callsite_guidance(message)
            {
                why = instance_why;
                address = instance_address;
            }
        }
        "namespace_flat_use_redundant_leaf_context"
        | "namespace_flat_pub_use_redundant_leaf_context"
        | "namespace_flat_type_alias_redundant_leaf_context"
        | "internal_redundant_leaf_context"
        | "internal_adapter_redundant_leaf_context"
        | "api_redundant_leaf_context" => {
            append_instance_address(
                &mut address,
                "If this item is also re-exported or caller-visible elsewhere, reconcile that outer surface too so the family ends up with one intentional path shape instead of an internal-only rename.",
            );
        }
        "api_semantic_string_scalar" => {
            append_instance_address(&mut address, &semantic_string_scalar_address_hint(message));
        }
        "api_semantic_numeric_scalar" => {
            append_instance_address(&mut address, &semantic_numeric_scalar_address_hint(message));
        }
        "api_raw_id_surface" => {
            append_instance_address(&mut address, &raw_id_surface_address_hint(message));
        }
        "api_candidate_child_facet_module" => {
            if let Some((instance_why, instance_address)) =
                candidate_child_facet_module_guidance(message)
            {
                why = instance_why;
                address = instance_address;
            }
        }
        "api_boundary_wraps_child_facet_error" => {
            if let Some((instance_why, instance_address)) =
                boundary_wraps_child_facet_error_guidance(message)
            {
                why = instance_why;
                address = instance_address;
            }
        }
        "namespace_family_unsupported_construct" => {
            append_instance_address(
                &mut address,
                &namespace_family_unsupported_address_hint(message),
            );
        }
        _ => {}
    }

    Some(DiagnosticGuidance {
        why,
        address: append_direct_rewrite(&address, fix),
    })
}

fn append_direct_rewrite(address: &str, fix: Option<&DiagnosticFix>) -> String {
    let Some(fix) = fix else {
        return address.to_string();
    };
    format!(
        "{address} Once the owning surface is right, the site-level rewrite here is `{}`.",
        fix.replacement
    )
}

fn append_instance_address(address: &mut String, extra: &str) {
    if extra.is_empty() {
        return;
    }
    address.push(' ');
    address.push_str(extra);
}

fn semantic_string_scalar_address_hint(message: &str) -> String {
    let (subject, fields) = message_subject_and_fields(message);
    let mut hints = Vec::new();

    for field in fields {
        let lower = field.to_ascii_lowercase();
        if lower.contains("url") {
            let scoped = scoped_boundary_type_hint(subject.as_deref(), &field);
            hints.push(match scoped {
                Some(scoped) => format!(
                    "For `{field}`, use a real URL boundary type. If the repo already has a matching wrapper, something like `{scoped}` is the right shape; otherwise use `url::Url` or a focused wrapper."
                ),
                None => format!(
                    "For `{field}`, use a real URL boundary type like the repo's existing wrapper or `url::Url`."
                ),
            });
        } else if lower.contains("email") {
            hints.push(format!(
                "For `{field}`, use the repo's email type if it exists, or a focused `Email` wrapper, instead of raw text."
            ));
        } else if lower.contains("path") {
            hints.push(format!(
                "For `{field}`, prefer `std::path::PathBuf` or the repo's path wrapper instead of raw text."
            ));
        }
    }

    hints.join(" ")
}

fn semantic_numeric_scalar_address_hint(message: &str) -> String {
    let (_, fields) = message_subject_and_fields(message);
    let mut hints = Vec::new();

    for field in fields {
        let lower = field.to_ascii_lowercase();
        if looks_like_duration_field(&lower) {
            hints.push(format!(
                "For `{field}`, `std::time::Duration` is the natural boundary type."
            ));
        } else if lower.contains("port") {
            hints.push(format!(
                "For `{field}`, use a focused port newtype, `core::num::NonZeroU16` when zero is invalid, or move it into a typed socket, endpoint, or address config surface instead of leaving it as a bare integer."
            ));
        }
    }

    hints.join(" ")
}

fn namespace_family_unsupported_address_hint(message: &str) -> String {
    let Some(first_chunk) = backticked_chunks(message).first().cloned() else {
        return String::new();
    };
    if first_chunk == "Error" || !first_chunk.ends_with("Error") {
        return String::new();
    }

    "If this is a flat leaf failure under a broader root boundary, verify whether the family really wants an owning facet like `email::Error` rather than a root-level `EmailError`-style surface.".to_string()
}

fn namespace_flat_context_guidance(
    code: &str,
    message: &str,
    fix: Option<&DiagnosticFix>,
) -> Option<(String, String)> {
    let chunks = backticked_chunks(message);
    let leaf = chunks.first()?.as_str();
    let preferred = fix
        .map(|fix| fix.replacement.as_str())
        .or_else(|| chunks.get(1).map(|chunk| chunk.as_str()))?;
    let (parent, _) = preferred.rsplit_once("::")?;

    let why = match (code, leaf_looks_context_dependent(leaf)) {
        ("namespace_flat_pub_use", true) => format!(
            "The leaf still needs `{parent}::` to read clearly here, so flattening it makes the caller-facing surface harder to scan."
        ),
        ("namespace_flat_pub_use", false) => format!(
            "`{parent}` is a meaningful facet or family home for this item, so flattening it hides structure the caller-facing surface should keep visible."
        ),
        ("namespace_flat_type_alias", true) => format!(
            "The leaf still needs `{parent}::` to read clearly here, so flattening it makes the aliased type path harder to scan."
        ),
        ("namespace_flat_type_alias", false) => format!(
            "`{parent}` is a meaningful facet or family home for this item, so flattening it hides structure the aliased type path should keep visible."
        ),
        (_, true) => format!(
            "The leaf still needs `{parent}::` to read clearly here, so flattening it makes the path harder to scan at the use site."
        ),
        _ => format!(
            "`{parent}` is a meaningful facet or family home for this item, so flattening it hides structure the path should keep visible."
        ),
    };

    let address = match code {
        "namespace_flat_pub_use" => format!(
            "Re-export through `{preferred}` and make `{parent}` the visible public facet here. Don't keep the flat re-export and try to compensate with an alias, a longer leaf, or a second competing surface."
        ),
        "namespace_flat_type_alias" => format!(
            "Keep `{preferred}` visible in the alias so the type path still shows its owning facet. Don't hide the module inside the alias name or flatten it away and compensate elsewhere."
        ),
        _ => format!(
            "Import `{preferred}` directly and keep `{parent}` visible at call sites. Don't flatten it and try to smuggle the missing structure back with an alias or a longer leaf."
        ),
    };

    Some((why, address))
}

fn error_surface_follow_through_guidance(code: &str, message: &str) -> Option<(String, String)> {
    let chunks = backticked_chunks(message);
    if chunks.len() < 2 {
        return None;
    }

    let current = chunks.first()?;
    let preferred = chunks.get(1)?;
    let owner = preferred
        .rsplit_once("::")
        .map(|(owner, _)| owner)
        .unwrap_or(preferred);
    let pending_facet = message.contains("once that facet exists");

    let why = if pending_facet {
        format!(
            "`{current}` is still using the old flat companion error shape even though `{owner}` is the deeper owner this family is trying to grow toward."
        )
    } else {
        format!(
            "`{current}` is bypassing the owned error surface `{preferred}`, so callers are still seeing a flatter `*Error` path than the owner intends."
        )
    };

    let address = match code {
        "namespace_flat_pub_use_error_surface_follow_through" => {
            if pending_facet {
                format!(
                    "Re-export through `{preferred}` once `{owner}` exists for real, and then treat that path as the public error surface. Don't keep re-exporting the flat `*Error` from the broader owner, and don't add the deeper facet as a second optional surface."
                )
            } else {
                format!(
                    "Re-export through `{preferred}` and treat `{owner}` as the public home for this failure surface. Don't keep the flat `*Error` re-export alive as a parallel public path."
                )
            }
        }
        "namespace_flat_type_alias_error_surface_follow_through" => {
            if pending_facet {
                format!(
                    "Once `{owner}` exists for real, point the alias at `{preferred}` or remove the alias entirely if it only preserves the old flat `*Error` path. Don't hide the ownership move behind a compensating alias name."
                )
            } else {
                format!(
                    "Point the alias at `{preferred}` or remove it if the alias is only preserving the flatter `*Error` path. Don't keep the old surface alive behind a local alias."
                )
            }
        }
        "namespace_qualified_error_surface_follow_through" => {
            if pending_facet {
                format!(
                    "Grow `{owner}` as the real child facet, move the leaf value and failure surface there together, and then switch call sites to `{preferred}`. Don't freeze the intermediate flat path just because it is shorter today."
                )
            } else {
                format!(
                    "Call through `{preferred}` so the code uses the owner's `Error` surface directly. Don't keep spelling the flatter `*Error` path at call sites, and don't patch over it with aliases."
                )
            }
        }
        _ => {
            if pending_facet {
                format!(
                    "Import or use `{preferred}` once `{owner}` exists for real, and move the leaf value and failure surface there together. Don't keep importing the old flat `*Error` path and call that good enough."
                )
            } else {
                format!(
                    "Import or use `{preferred}` so callers see the owner's `Error` surface directly. Don't keep the flatter `*Error` path around as a parallel answer from the same family."
                )
            }
        }
    };

    Some((why, address))
}

fn child_facet_value_follow_through_guidance(
    code: &str,
    message: &str,
) -> Option<(String, String)> {
    let chunks = backticked_chunks(message);
    if chunks.len() < 2 {
        return None;
    }

    let current = chunks.first()?;
    let preferred = chunks.get(1)?;
    let pending_facet = message.contains("once that facet exists");

    let why = if pending_facet {
        format!(
            "`{current}` is still using the broader owner path even though `{preferred}` is the child facet this leaf family is trying to grow toward."
        )
    } else {
        format!(
            "`{current}` is bypassing the child facet `{preferred}`, so callers are still reading the leaf through the broader owner path."
        )
    };

    let address = match code {
        "namespace_flat_pub_use_child_facet_follow_through" => {
            if pending_facet {
                format!(
                    "Re-export through a path under `{preferred}` once that facet exists for real, and then treat that child facet as the public home for the leaf family. Don't keep re-exporting the broader owner path as a parallel public answer."
                )
            } else {
                format!(
                    "Re-export through `{preferred}` and treat that child facet as the public home for the leaf family. Don't keep the broader owner path alive as a parallel public surface."
                )
            }
        }
        "namespace_flat_type_alias_child_facet_follow_through" => {
            if pending_facet {
                format!(
                    "Once `{preferred}` exists for real, point the alias at a path under that child facet or remove the alias if it only preserves the broader owner path. Don't hide the ownership move behind a compensating alias name."
                )
            } else {
                format!(
                    "Point the alias at `{preferred}` or remove it if the alias is only preserving the broader owner path. Don't keep the old surface alive behind a local alias."
                )
            }
        }
        "namespace_qualified_child_facet_follow_through" => {
            if pending_facet {
                format!(
                    "Grow `{preferred}` as the real child facet, move the leaf value and failure surface there together, and then switch call sites into that facet instead of freezing the broader owner path just because it is shorter today."
                )
            } else {
                format!(
                    "Call through `{preferred}` so the code uses the child facet directly. Don't keep spelling the broader owner path at call sites, and don't patch over it with aliases."
                )
            }
        }
        _ => {
            if pending_facet {
                format!(
                    "Import or use a path under `{preferred}` once that child facet exists for real, and move the leaf value and failure surface there together. Don't keep importing the broader owner path and call that good enough."
                )
            } else {
                format!(
                    "Import or use `{preferred}` so callers see the child facet directly. Don't keep the broader owner path around as a parallel answer from the same family."
                )
            }
        }
    };

    Some((why, address))
}

fn overqualified_callsite_guidance(message: &str) -> Option<(String, String)> {
    let chunks = backticked_chunks(message);
    let full_path = chunks.first()?;
    let qualifier = chunks.get(1)?;
    let preferred = chunks.get(2)?;
    let (parent, _) = preferred.rsplit_once("::")?;

    let why = format!(
        "The call site is carrying the full path `{full_path}` even though `{parent}` is enough visible context once that module is imported."
    );
    let address = if message.contains("call through existing") {
        format!(
            "Call through the existing `{qualifier}` namespace and prefer `{preferred}` so the call site keeps the semantic facet without paying the whole absolute path cost. Don't flatten all the way to the bare leaf, and don't keep the full path inline just because it compiles. If `{parent}` is still too broad for the leaf family, grow the child facet first instead of freezing this shorter path."
        )
    } else {
        format!(
            "Import `{qualifier}` and call through `{preferred}` so the call site keeps the semantic facet without paying the whole absolute path cost. Don't flatten all the way to the bare leaf, and don't keep the full path inline just because it compiles. If `{parent}` is still too broad for the leaf family, grow the child facet first instead of freezing this shorter path."
        )
    };

    Some((why, address))
}

fn candidate_child_facet_module_guidance(message: &str) -> Option<(String, String)> {
    let chunks = backticked_chunks(message);
    if chunks.len() < 4 {
        return None;
    }

    let owner = chunks.first()?;
    let child = chunks.last()?;
    let leaf = chunks.get(chunks.len().checked_sub(2)?)?;
    let broader_items = chunks[1..chunks.len() - 2].join(", ");
    let leaf_name = leaf.rsplit("::").next()?;

    let why = format!(
        "`{owner}` is carrying broader surface like `{broader_items}` and a validated leaf `{leaf_name}` at the same level, which is a sign the leaf may want its own owned facet and failure surface."
    );
    let address = format!(
        "If `{child}` becomes the real owner for this leaf family, move `{leaf_name}` and its failure surface there and let `{owner}` keep the broader aggregate surface like `{broader_items}`. Do the filesystem refactor for real instead of using `#[path = ...]` shims, and don't keep both `{leaf}` and `{child}::{leaf_name}` as equal canonical homes."
    );

    Some((why, address))
}

fn boundary_wraps_child_facet_error_guidance(message: &str) -> Option<(String, String)> {
    let chunks = backticked_chunks(message);
    if chunks.len() < 5 {
        return None;
    }

    let boundary = chunks.first()?;
    let variant = chunks.get(1)?;
    let flat_error = chunks.get(2)?;
    let child_owner = chunks.get(3)?;
    let child_error = chunks.get(4)?;

    let why = format!(
        "`{boundary}` is still keeping variant `{variant}` on the flat child error surface `{flat_error}` even though `{child_owner}` looks like the real owner for that leaf family."
    );
    let address = format!(
        "If `{child_owner}` becomes the canonical child owner, move the leaf value and failure surface there together and let `{boundary}` wrap `{child_error}` instead. Don't keep `{flat_error}` as the parallel public child error once the deeper facet exists, and don't fake the move with `#[path = ...]` shims."
    );

    Some((why, address))
}

fn raw_id_surface_address_hint(message: &str) -> String {
    let (subject, fields) = message_subject_and_fields(message);
    let mut hints = Vec::new();

    for field in fields {
        if !field.to_ascii_lowercase().contains("id") {
            continue;
        }

        let scoped = scoped_boundary_type_hint(subject.as_deref(), &field)
            .unwrap_or_else(|| pascalize_identifier(&field));
        hints.push(format!(
            "For `{field}`, use the repo's matching id type if it exists; a type like `{scoped}` is the intended boundary shape."
        ));
    }

    hints.join(" ")
}

fn message_subject_and_fields(message: &str) -> (Option<String>, Vec<String>) {
    let chunks = backticked_chunks(message);
    if chunks.is_empty() {
        return (None, Vec::new());
    }

    let subject = chunks.first().cloned();
    let fields = chunks
        .into_iter()
        .skip(1)
        .filter(|chunk| {
            !chunk.contains("::")
                && chunk
                    .chars()
                    .any(|ch| ch.is_ascii_alphanumeric() || ch == '_')
        })
        .collect::<Vec<_>>();
    (subject, fields)
}

fn backticked_chunks(message: &str) -> Vec<String> {
    let mut chunks = Vec::new();
    let mut rest = message;

    while let Some(start) = rest.find('`') {
        let after_start = &rest[start + 1..];
        let Some(end) = after_start.find('`') else {
            break;
        };
        chunks.push(after_start[..end].to_string());
        rest = &after_start[end + 1..];
    }

    chunks
}

fn scoped_boundary_type_hint(subject: Option<&str>, field: &str) -> Option<String> {
    let prefix = subject.and_then(boundary_subject_scope)?;
    let field_type = pascalize_identifier(field);
    if field_type.starts_with(&prefix) {
        return None;
    }
    Some(format!("{prefix}{field_type}"))
}

fn boundary_subject_scope(subject: &str) -> Option<String> {
    let segments = subject.split("::").collect::<Vec<_>>();
    let owner = match segments.as_slice() {
        [] => return None,
        [single] => *single,
        [.., prev, last]
            if last
                .chars()
                .next()
                .is_some_and(|ch| ch.is_ascii_lowercase()) =>
        {
            *prev
        }
        [.., last] => *last,
    };
    let scope = ident_words(owner).last().cloned()?;
    (!scope_word_is_generic(&scope)).then_some(scope)
}

fn pascalize_identifier(raw: &str) -> String {
    ident_words(raw)
        .into_iter()
        .map(|word| {
            let mut chars = word.chars();
            let Some(first) = chars.next() else {
                return String::new();
            };
            let mut rendered = String::new();
            rendered.push(first.to_ascii_uppercase());
            rendered.push_str(chars.as_str());
            rendered
        })
        .collect::<String>()
}

fn ident_words(raw: &str) -> Vec<String> {
    let mut words = Vec::new();
    let mut current = String::new();
    let mut prev_was_lower_or_digit = false;

    for ch in raw.chars() {
        if matches!(ch, '_' | ':' | '-' | ' ') {
            if !current.is_empty() {
                words.push(current.clone());
                current.clear();
            }
            prev_was_lower_or_digit = false;
            continue;
        }

        if ch.is_ascii_uppercase() && prev_was_lower_or_digit && !current.is_empty() {
            words.push(current.clone());
            current.clear();
        }

        current.push(ch);
        prev_was_lower_or_digit = ch.is_ascii_lowercase() || ch.is_ascii_digit();
    }

    if !current.is_empty() {
        words.push(current);
    }

    words
}

fn looks_like_duration_field(field: &str) -> bool {
    field.contains("timeout")
        || field.contains("interval")
        || field.contains("backoff")
        || field.ends_with("_secs")
        || field.ends_with("_ms")
        || field.ends_with("_millis")
        || field.ends_with("_nanos")
}

fn leaf_looks_context_dependent(leaf: &str) -> bool {
    if leaf
        .chars()
        .all(|ch| ch.is_ascii_uppercase() || ch == '_' || ch.is_ascii_digit())
    {
        return true;
    }

    let words = ident_words(leaf);
    if words.len() <= 1 {
        return true;
    }

    let generic_count = words
        .iter()
        .filter(|word| namespace_context_word_is_generic(word))
        .count();

    generic_count.saturating_mul(2) >= words.len().saturating_add(1)
}

fn namespace_context_word_is_generic(word: &str) -> bool {
    let generic_words = [
        "body",
        "config",
        "content",
        "context",
        "cookie",
        "copy",
        "entry",
        "error",
        "field",
        "flow",
        "id",
        "key",
        "kind",
        "layer",
        "level",
        "log",
        "message",
        "name",
        "pipeline",
        "record",
        "repository",
        "request",
        "response",
        "result",
        "service",
        "session",
        "state",
        "store",
        "target",
        "text",
        "type",
        "value",
    ];
    generic_words.contains(&word.to_ascii_lowercase().as_str())
}

fn scope_word_is_generic(scope: &str) -> bool {
    let generic_scope_words = [
        "adapter", "auth", "client", "config", "entry", "event", "hit", "id", "mock", "param",
        "params", "payload", "profile", "record", "request", "response", "result", "state",
        "vault",
    ];
    let normalized = scope.to_ascii_lowercase();
    generic_scope_words.contains(&normalized.as_str())
}

#[cfg(test)]
mod tests {
    use super::{
        Diagnostic, DiagnosticClass, DiagnosticFix, DiagnosticFixKind, diagnostic_guidance_for_code,
    };

    #[test]
    fn instance_guidance_for_semantic_string_scalar_mentions_repo_shaped_url_type() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_semantic_string_scalar".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "public struct `SensitiveSandbox` carries semantic scalar field(s) `base_url` as raw strings; prefer typed boundary values or focused newtypes".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.address.contains("SandboxBaseUrl"));
        assert!(guidance.address.contains("url::Url"));
    }

    #[test]
    fn instance_guidance_for_raw_id_surface_mentions_repo_shaped_id_type() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_raw_id_surface".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "public struct `SensitiveSandbox` keeps raw id field(s) `client_id` as strings or primitive integers; prefer id newtypes at the boundary".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.address.contains("SandboxClientId"));
    }

    #[test]
    fn instance_guidance_for_flat_use_generic_leaf_mentions_needed_parent_context() {
        let diag = Diagnostic {
            class: DiagnosticClass::PolicyWarning {
                code: "namespace_flat_use".to_string(),
            },
            file: None,
            line: None,
            fix: Some(DiagnosticFix {
                kind: DiagnosticFixKind::ReplacePath,
                replacement: "types::LogFieldKey".to_string(),
            }),
            message: "flattened import hides namespace context for `LogFieldKey`; prefer `types::LogFieldKey`".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.why.contains("still needs `types::`"));
        assert!(
            guidance
                .address
                .contains("Import `types::LogFieldKey` directly")
        );
    }

    #[test]
    fn instance_guidance_for_flat_use_family_leaf_mentions_facet_visibility() {
        let diag = Diagnostic {
            class: DiagnosticClass::PolicyWarning {
                code: "namespace_flat_use".to_string(),
            },
            file: None,
            line: None,
            fix: Some(DiagnosticFix {
                kind: DiagnosticFixKind::ReplacePath,
                replacement: "viewer::ViewerResolutionFlow".to_string(),
            }),
            message: "flattened import hides namespace context for `ViewerResolutionFlow`; prefer `viewer::ViewerResolutionFlow`".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.why.contains("meaningful facet or family home"));
        assert!(
            guidance
                .address
                .contains("Import `viewer::ViewerResolutionFlow` directly")
        );
    }

    #[test]
    fn instance_guidance_for_flat_pub_use_names_reexport_move_directly() {
        let diag = Diagnostic {
            class: DiagnosticClass::PolicyWarning {
                code: "namespace_flat_pub_use".to_string(),
            },
            file: None,
            line: None,
            fix: Some(DiagnosticFix {
                kind: DiagnosticFixKind::ReplacePath,
                replacement: "layers::RequestLayerFlow".to_string(),
            }),
            message: "flattened re-export hides namespace context for `RequestLayerFlow`; prefer `layers::RequestLayerFlow`".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.why.contains("caller-facing surface"));
        assert!(
            guidance
                .address
                .contains("Re-export through `layers::RequestLayerFlow`")
        );
        assert!(guidance.address.contains("visible public facet"));
    }

    #[test]
    fn instance_guidance_for_overqualified_callsite_names_import_and_preferred_path() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "namespace_overqualified_callsite_path".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "`crate::trace_log::demo::chat::short_hyphenated_text` keeps too much module scaffolding at the call site; import `crate::trace_log::demo::chat` and prefer `chat::short_hyphenated_text`".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.why.contains("`chat` is enough visible context"));
        assert!(guidance.address.contains(
            "Import `crate::trace_log::demo::chat` and call through `chat::short_hyphenated_text`"
        ));
    }

    #[test]
    fn instance_guidance_for_overqualified_callsite_reuses_existing_namespace_binding() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "namespace_overqualified_callsite_path".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "`domain::chat::room::name::Error` keeps too much module scaffolding at the call site; call through existing `chat` namespace and prefer `chat::room::name::Error`".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(
            guidance
                .why
                .contains("`chat::room::name` is enough visible context")
        );
        assert!(guidance.address.contains(
            "Call through the existing `chat` namespace and prefer `chat::room::name::Error`"
        ));
        assert!(guidance.address.contains("grow the child facet first"));
    }

    #[test]
    fn instance_guidance_skips_generic_scope_prefixes_for_string_scalars() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_semantic_string_scalar".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "public struct `EpicConfig` carries semantic scalar field(s) `base_url` as raw strings; prefer typed boundary values or focused newtypes".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.address.contains("url::Url"));
        assert!(!guidance.address.contains("ConfigBaseUrl"));
    }

    #[test]
    fn instance_guidance_skips_duplicate_scope_prefixes_for_id_types() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_raw_id_surface".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "public struct `AuditRecord` keeps raw id field(s) `record_id` as strings or primitive integers; prefer id newtypes at the boundary".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.address.contains("RecordId"));
        assert!(!guidance.address.contains("RecordRecordId"));
    }

    #[test]
    fn generic_guidance_for_unsupported_construct_reports_analysis_boundary() {
        let guidance = diagnostic_guidance_for_code(
            "api_candidate_semantic_module_unsupported_construct",
            None,
        )
        .expect("guidance");
        assert!(guidance.why.contains("can't interpret authoritatively"));
        assert!(guidance.address.contains("analysis boundary"));
        assert!(!guidance.address.contains("Change the public boundary"));
        assert!(guidance.address.contains("Don't rewrite macros"));
    }

    #[test]
    fn generic_guidance_for_namespace_family_unsupported_construct_reports_analysis_boundary() {
        let guidance = diagnostic_guidance_for_code("namespace_family_unsupported_construct", None)
            .expect("guidance");
        assert!(guidance.why.contains("can't interpret authoritatively"));
        assert!(guidance.address.contains("analysis boundary"));
        assert!(
            guidance
                .address
                .contains("Verify the owning family or facet")
        );
        assert!(
            !guidance
                .address
                .contains("Keep the real module path visible")
        );
    }

    #[test]
    fn instance_guidance_for_namespace_family_unsupported_construct_mentions_owned_facet_for_leaf_error()
     {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "namespace_family_unsupported_construct".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "skipped namespace-family inference for `EmailError` in this import because source-level analysis saw `item macro`; verify manually whether this flat leaf failure belongs under an owning facet before changing the path".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.address.contains("email::Error"));
    }

    #[test]
    fn generic_guidance_for_parent_surface_warns_against_split_canonical_paths() {
        let guidance =
            diagnostic_guidance_for_code("namespace_parent_surface", None).expect("guidance");
        assert!(guidance.address.contains("canonical caller-facing path"));
        assert!(
            guidance
                .address
                .contains("callers split across both surfaces")
        );
    }

    #[test]
    fn generic_guidance_for_redundant_leaf_context_warns_against_alias_and_token_chop() {
        let guidance = diagnostic_guidance_for_code("internal_redundant_leaf_context", None)
            .expect("guidance");
        assert!(guidance.address.contains("local alias"));
        assert!(guidance.address.contains("mechanically chopping tokens"));
    }

    #[test]
    fn instance_guidance_for_redundant_leaf_context_mentions_outer_surface_reconciliation() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "internal_redundant_leaf_context".to_string(),
            },
            file: None,
            line: None,
            fix: Some(DiagnosticFix {
                kind: DiagnosticFixKind::ReplacePath,
                replacement: "sensitive_boundary::config::SandboxHttp".to_string(),
            }),
            message: "internal item `sensitive_boundary::config::SandboxHttpConfig` repeats the `config` context; prefer `sensitive_boundary::config::SandboxHttp`".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.address.contains("caller-visible elsewhere"));
    }

    #[test]
    fn generic_guidance_for_candidate_facet_module_keeps_root_boundary_and_leaf_errors_separate() {
        let guidance =
            diagnostic_guidance_for_code("api_candidate_facet_module", None).expect("guidance");
        assert!(guidance.why.contains("value-plus-error families"));
        assert!(guidance.address.contains("cross-facet boundary"));
        assert!(guidance.address.contains("don't flatten the leaf error"));
    }

    #[test]
    fn generic_guidance_for_candidate_child_facet_module_demands_real_child_owner() {
        let guidance = diagnostic_guidance_for_code("api_candidate_child_facet_module", None)
            .expect("guidance");
        assert!(guidance.why.contains("validated leaf"));
        assert!(guidance.address.contains("canonical owner"));
        assert!(guidance.address.contains("#[path = ...]"));
        assert!(guidance.address.contains("equal canonical homes"));
    }

    #[test]
    fn instance_guidance_for_candidate_child_facet_module_names_owner_and_child() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_candidate_child_facet_module".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "public module `chat::message` mixes broader surface `Message` with validated leaf `chat::message::Body`; consider an owned child facet like `chat::message::body` so the leaf value and failure surface can live together".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(
            guidance
                .why
                .contains("`chat::message` is carrying broader surface")
        );
        assert!(guidance.address.contains("`chat::message::body`"));
        assert!(guidance.address.contains("`chat::message::Body`"));
    }

    #[test]
    fn generic_guidance_for_boundary_wraps_child_facet_error_keeps_child_owner_single() {
        let guidance = diagnostic_guidance_for_code("api_boundary_wraps_child_facet_error", None)
            .expect("guidance");
        assert!(guidance.why.contains("flat child companion error"));
        assert!(guidance.address.contains("child-facet `Error`"));
        assert!(guidance.address.contains("parallel public answer"));
        assert!(guidance.address.contains("#[path = ...]"));
    }

    #[test]
    fn instance_guidance_for_boundary_wraps_child_facet_error_names_boundary_and_child_owner() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_boundary_wraps_child_facet_error".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "public boundary `chat::Error` variant `MessageBody` wraps flat child error `chat::message::BodyError` even though `chat::message::body` looks like the owning child facet; prefer `chat::message::body::Error` once that facet exists".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.why.contains("`chat::Error`"));
        assert!(guidance.why.contains("`MessageBody`"));
        assert!(guidance.address.contains("`chat::message::body::Error`"));
        assert!(guidance.address.contains("`chat::message::BodyError`"));
    }

    #[test]
    fn generic_guidance_for_error_surface_follow_through_keeps_owned_error_canonical() {
        let guidance =
            diagnostic_guidance_for_code("namespace_flat_use_error_surface_follow_through", None)
                .expect("guidance");
        assert!(guidance.why.contains("owning facet"));
        assert!(guidance.address.contains("owned `Error` surface"));
        assert!(guidance.address.contains("#[path = ...]"));
    }

    #[test]
    fn instance_guidance_for_error_surface_follow_through_names_deeper_owner() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "namespace_qualified_error_surface_follow_through".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "`domain::chat::message::BodyError` keeps a flat leaf error surface; prefer `message::body::Error` once that facet exists".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.why.contains("`domain::chat::message::BodyError`"));
        assert!(guidance.why.contains("`message::body`"));
        assert!(guidance.address.contains("`message::body::Error`"));
        assert!(guidance.address.contains("child facet"));
    }

    #[test]
    fn generic_guidance_for_child_facet_value_follow_through_keeps_child_visible() {
        let guidance =
            diagnostic_guidance_for_code("namespace_flat_use_child_facet_follow_through", None)
                .expect("guidance");
        assert!(guidance.why.contains("deeper child facet"));
        assert!(
            guidance
                .address
                .contains("Move the leaf value and failure surface together")
        );
        assert!(guidance.address.contains("#[path = ...]"));
    }

    #[test]
    fn instance_guidance_for_child_facet_value_follow_through_names_child_owner() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "namespace_qualified_child_facet_follow_through".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "`domain::chat::message::Body` keeps a broader leaf path; prefer a child-facet path under `message::body` once that facet exists".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.why.contains("`domain::chat::message::Body`"));
        assert!(guidance.why.contains("`message::body`"));
        assert!(guidance.address.contains("child facet"));
    }

    #[test]
    fn generic_guidance_for_owned_facet_companion_error_keeps_one_canonical_error_surface() {
        let guidance = diagnostic_guidance_for_code("api_owned_facet_companion_error", None)
            .expect("guidance");
        assert!(guidance.why.contains("same facet"));
        assert!(guidance.address.contains("caller-visible failure surface"));
        assert!(guidance.address.contains("parallel public answers"));
    }

    #[test]
    fn owned_facet_companion_error_has_strict_profile_metadata() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_owned_facet_companion_error".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: String::new(),
        };

        assert_eq!(diag.profile(), Some(super::LintProfile::Strict));
    }

    #[test]
    fn boundary_wraps_child_facet_error_has_strict_profile_metadata() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_boundary_wraps_child_facet_error".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: String::new(),
        };

        assert_eq!(diag.profile(), Some(super::LintProfile::Strict));
    }

    #[test]
    fn error_surface_follow_through_has_strict_profile_metadata() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "namespace_flat_use_error_surface_follow_through".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: String::new(),
        };

        assert_eq!(diag.profile(), Some(super::LintProfile::Strict));
    }

    #[test]
    fn child_facet_value_follow_through_has_strict_profile_metadata() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "namespace_flat_use_child_facet_follow_through".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: String::new(),
        };

        assert_eq!(diag.profile(), Some(super::LintProfile::Strict));
    }

    #[test]
    fn generic_guidance_for_semantic_string_scalar_warns_against_type_alias_string() {
        let guidance =
            diagnostic_guidance_for_code("api_semantic_string_scalar", None).expect("guidance");
        assert!(guidance.address.contains("type ... = String"));
    }

    #[test]
    fn instance_guidance_for_numeric_port_scalar_mentions_concrete_port_shapes() {
        let diag = Diagnostic {
            class: DiagnosticClass::AdvisoryWarning {
                code: "api_semantic_numeric_scalar".to_string(),
            },
            file: None,
            line: None,
            fix: None,
            message: "public struct `Sensitive` carries semantic scalar field(s) `provider_stub_port` as raw integers; prefer typed duration, timestamp, port, or domain-specific scalar types".to_string(),
        };

        let guidance = diag.guidance().expect("guidance");
        assert!(guidance.address.contains("NonZeroU16"));
        assert!(guidance.address.contains("typed socket"));
    }

    #[test]
    fn generic_guidance_for_candidate_semantic_module_warns_against_shadow_surface() {
        let guidance =
            diagnostic_guidance_for_code("api_candidate_semantic_module", None).expect("guidance");
        assert!(guidance.address.contains("design prompt"));
        assert!(guidance.address.contains("shadow module"));
        assert!(guidance.address.contains("#[path = ...]"));
    }

    #[test]
    fn generic_guidance_for_flat_namespace_module_warns_against_path_shims() {
        let guidance =
            diagnostic_guidance_for_code("internal_flat_namespace_preserving_module", None)
                .expect("guidance");
        assert!(guidance.address.contains("#[path = ...]"));
        assert!(guidance.address.contains("filesystem refactor"));
    }

    #[test]
    fn generic_guidance_for_path_shim_module_demands_real_module_layout() {
        let guidance =
            diagnostic_guidance_for_code("internal_path_shim_module", None).expect("guidance");
        assert!(guidance.why.contains("filesystem"));
        assert!(guidance.address.contains("real module file or directory"));
        assert!(guidance.address.contains("remove the `#[path]` attribute"));
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSelection {
    All,
    Policy,
    Advisory,
}

impl DiagnosticSelection {
    pub fn includes(self, diagnostic: &Diagnostic) -> bool {
        match self {
            Self::All => true,
            Self::Policy => diagnostic.is_error() || diagnostic.is_policy_violation(),
            Self::Advisory => diagnostic.is_error() || diagnostic.is_advisory_warning(),
        }
    }

    pub fn report_label(self) -> Option<&'static str> {
        match self {
            Self::All => None,
            Self::Policy => Some("policy diagnostics and errors only"),
            Self::Advisory => Some("advisory diagnostics and errors only"),
        }
    }
}

pub fn diagnostic_code_info(code: &str) -> Option<DiagnosticCodeInfo> {
    let (profile, summary) = match code {
        "namespace_flat_use" => (
            LintProfile::Core,
            "Flattened imports hide useful namespace context for leaves that still need the parent path.",
        ),
        "namespace_flat_use_error_surface_follow_through" => (
            LintProfile::Strict,
            "A flattened import keeps an older flat `*Error` path even though ownership now points at a deeper or owned `Error` surface.",
        ),
        "namespace_flat_use_child_facet_follow_through" => (
            LintProfile::Strict,
            "A flattened import keeps the broader owner path even though the leaf family points at a deeper child facet.",
        ),
        "namespace_flat_use_preserve_module" => (
            LintProfile::Core,
            "Flattened imports hide a module that should stay visible at call sites.",
        ),
        "namespace_flat_use_redundant_leaf_context" => (
            LintProfile::Core,
            "Flattened imports keep parent context in the leaf instead of the path.",
        ),
        "namespace_redundant_qualified_generic" => (
            LintProfile::Core,
            "Qualified paths repeat a generic category that the leaf already names.",
        ),
        "namespace_qualified_error_surface_follow_through" => (
            LintProfile::Strict,
            "A qualified path is still spelling the flatter `*Error` surface instead of the owned or faceted `Error` path.",
        ),
        "namespace_qualified_child_facet_follow_through" => (
            LintProfile::Strict,
            "A qualified path is still spelling the broader owner path instead of the deeper child facet the leaf family points toward.",
        ),
        "namespace_overqualified_callsite_path" => (
            LintProfile::Strict,
            "A long qualified call-site path keeps more module scaffolding visible than the caller needs.",
        ),
        "namespace_aliased_qualified_path" => (
            LintProfile::Core,
            "A namespace alias flattens a semantic path instead of keeping the real module visible.",
        ),
        "namespace_family_unsupported_construct" => (
            LintProfile::Strict,
            "Namespace-family call-site guidance was skipped because source-level analysis hit macros, cfg gates, or includes.",
        ),
        "namespace_parent_surface" => (
            LintProfile::Core,
            "Imports bypass a canonical parent surface that already re-exports the binding.",
        ),
        "namespace_flat_type_alias" => (
            LintProfile::Core,
            "A type alias hides useful namespace context for an aliased leaf that still needs the parent path.",
        ),
        "namespace_flat_type_alias_error_surface_follow_through" => (
            LintProfile::Strict,
            "A type alias preserves an older flat `*Error` path instead of the owned or faceted `Error` surface.",
        ),
        "namespace_flat_type_alias_child_facet_follow_through" => (
            LintProfile::Strict,
            "A type alias preserves the broader owner path instead of the deeper child facet the leaf family points toward.",
        ),
        "namespace_flat_type_alias_preserve_module" => (
            LintProfile::Core,
            "A type alias hides a module that should stay visible in the aliased type path.",
        ),
        "namespace_flat_type_alias_redundant_leaf_context" => (
            LintProfile::Core,
            "A type alias keeps redundant parent context in the alias name instead of the path.",
        ),
        "namespace_prelude_glob_import" => (
            LintProfile::Core,
            "A prelude glob import hides the real source modules instead of keeping useful namespace context visible.",
        ),
        "namespace_glob_preserve_module" => (
            LintProfile::Core,
            "A glob import flattens a configured namespace-preserving module instead of keeping that module visible.",
        ),
        "internal_catch_all_module" => (
            LintProfile::Core,
            "An internal module name is a catch-all bucket instead of a stable domain or facet.",
        ),
        "internal_repeated_module_segment" => (
            LintProfile::Core,
            "An internal nested module repeats the same segment instead of adding meaning.",
        ),
        "internal_organizational_submodule_flatten" => (
            LintProfile::Core,
            "An internal organizational module leaks category structure that should usually be flattened.",
        ),
        "internal_weak_module_generic_leaf" => (
            LintProfile::Core,
            "An internal item leaf is too generic for a weak or technical parent module.",
        ),
        "internal_redundant_leaf_context" => (
            LintProfile::Core,
            "An internal item leaf repeats context the parent module already provides.",
        ),
        "internal_adapter_redundant_leaf_context" => (
            LintProfile::Core,
            "An internal adapter leaf repeats implementation context the parent module already provides.",
        ),
        "internal_redundant_category_suffix" => (
            LintProfile::Core,
            "An internal item leaf repeats the parent category in a redundant suffix.",
        ),
        "internal_flat_namespace_preserving_module" => (
            LintProfile::Core,
            "An internal flat module name hides a namespace-preserving facet that should stay visible in the path.",
        ),
        "internal_path_shim_module" => (
            LintProfile::Core,
            "An internal module is being mounted through `#[path = ...]` instead of living at a real module path.",
        ),
        "internal_candidate_semantic_module" => (
            LintProfile::Strict,
            "A family of sibling internal items or modules suggests a stronger semantic module surface.",
        ),
        "api_catch_all_module" => (
            LintProfile::Core,
            "A surface-visible module is a catch-all bucket instead of a stable domain or facet.",
        ),
        "api_repeated_module_segment" => (
            LintProfile::Core,
            "A surface-visible nested module repeats the same segment instead of adding meaning.",
        ),
        "namespace_flat_pub_use" => (
            LintProfile::Surface,
            "A re-export flattens useful namespace context out of the caller-facing path.",
        ),
        "namespace_flat_pub_use_error_surface_follow_through" => (
            LintProfile::Strict,
            "A re-export preserves a flatter `*Error` path instead of the owned or faceted `Error` surface.",
        ),
        "namespace_flat_pub_use_child_facet_follow_through" => (
            LintProfile::Strict,
            "A re-export preserves the broader owner path instead of the deeper child facet the leaf family points toward.",
        ),
        "namespace_flat_pub_use_preserve_module" => (
            LintProfile::Surface,
            "A re-export hides a module that should stay visible in the caller-facing path.",
        ),
        "namespace_flat_pub_use_redundant_leaf_context" => (
            LintProfile::Surface,
            "A re-export keeps parent context in the leaf instead of the path.",
        ),
        "api_missing_parent_surface_export" => (
            LintProfile::Surface,
            "A child module surface should usually also expose a readable parent binding.",
        ),
        "api_anyhow_error_surface" => (
            LintProfile::Surface,
            "A caller-facing surface leaks `anyhow` instead of exposing a crate-owned typed error boundary.",
        ),
        "api_semantic_string_scalar" => (
            LintProfile::Surface,
            "A caller-facing semantic scalar is kept as a raw string instead of a typed boundary value.",
        ),
        "api_semantic_numeric_scalar" => (
            LintProfile::Surface,
            "A caller-facing semantic scalar is kept as a raw integer instead of a typed boundary value.",
        ),
        "api_weak_module_generic_leaf" => (
            LintProfile::Surface,
            "A surface-visible item leaf is too generic for a weak or technical parent module.",
        ),
        "api_redundant_leaf_context" => (
            LintProfile::Surface,
            "A surface-visible item leaf repeats context the parent module already provides.",
        ),
        "api_redundant_category_suffix" => (
            LintProfile::Surface,
            "A surface-visible item leaf repeats the parent category in a redundant suffix.",
        ),
        "api_organizational_submodule_flatten" => (
            LintProfile::Surface,
            "A surface-visible organizational module should usually be flattened out of the path.",
        ),
        "api_path_shim_module" => (
            LintProfile::Core,
            "A surface-visible module is being mounted through `#[path = ...]` instead of living at a real module path.",
        ),
        "api_candidate_semantic_module" => (
            LintProfile::Strict,
            "A family of sibling items suggests a stronger semantic module surface.",
        ),
        "api_candidate_facet_module" => (
            LintProfile::Strict,
            "A root boundary is sitting beside flat leaf value-plus-error families that likely want owned facets.",
        ),
        "api_candidate_child_facet_module" => (
            LintProfile::Strict,
            "A broader public module likely wants a child facet for one validated leaf and its failure surface.",
        ),
        "api_boundary_wraps_child_facet_error" => (
            LintProfile::Strict,
            "A broader public `Error` boundary still wraps a flat child companion error even though a deeper child facet now looks like the owner.",
        ),
        "api_owned_facet_companion_error" => (
            LintProfile::Strict,
            "An owned facet is exposing both a local companion error and a facet-level `Error` as parallel failure surfaces.",
        ),
        "api_candidate_semantic_module_unsupported_construct" => (
            LintProfile::Strict,
            "Semantic-module family inference was skipped because the parsed source contains unsupported constructs.",
        ),
        "api_manual_enum_string_helper" => (
            LintProfile::Strict,
            "A public enum exposes manual string helpers that should usually be standard traits or derives.",
        ),
        "api_ad_hoc_parse_helper" => (
            LintProfile::Strict,
            "A public enum parsing helper should usually be modeled as `FromStr` or `TryFrom<&str>`.",
        ),
        "api_parallel_enum_metadata_helper" => (
            LintProfile::Strict,
            "Parallel enum metadata helpers suggest a typed descriptor surface instead of repeated matches.",
        ),
        "api_strum_serialize_all_candidate" => (
            LintProfile::Strict,
            "Per-variant `strum` strings could be replaced by one enum-level `serialize_all` rule.",
        ),
        "api_builder_candidate" => (
            LintProfile::Strict,
            "A configuration-heavy entrypoint would read better as a builder or typed options surface.",
        ),
        "api_repeated_parameter_cluster" => (
            LintProfile::Strict,
            "Several entrypoints repeat the same positional parameter cluster instead of sharing a typed shape.",
        ),
        "api_optional_parameter_builder" => (
            LintProfile::Strict,
            "Optional positional parameters suggest a builder so callers can omit unset values.",
        ),
        "api_defaulted_optional_parameter" => (
            LintProfile::Strict,
            "Defaulted optional positional parameters suggest a builder rather than `None`-passing.",
        ),
        "callsite_maybe_some" => (
            LintProfile::Strict,
            "A `maybe_*` call wraps a direct value in `Some(...)` instead of using the direct setter or forwarding an existing option.",
        ),
        "api_standalone_builder_surface" => (
            LintProfile::Strict,
            "Parallel `with_*` or `set_*` free functions suggest a real builder surface.",
        ),
        "api_boolean_protocol_decision" => (
            LintProfile::Strict,
            "A boolean encodes a domain or protocol decision that should usually be typed.",
        ),
        "api_boolean_flag_cluster" => (
            LintProfile::Strict,
            "Several booleans jointly shape behavior and suggest a typed mode or options surface.",
        ),
        "api_forwarding_compat_wrapper" => (
            LintProfile::Strict,
            "A helper only forwards to an existing standard conversion trait.",
        ),
        "api_string_error_surface" => (
            LintProfile::Strict,
            "A caller-facing error surface is carried as raw strings instead of a typed error boundary.",
        ),
        "api_manual_error_surface" => (
            LintProfile::Strict,
            "A public error manually exposes formatting and error boilerplate instead of a smaller typed boundary.",
        ),
        "api_raw_key_value_bag" => (
            LintProfile::Strict,
            "A caller-facing metadata or bag surface is modeled as raw string key-value pairs instead of a typed shape.",
        ),
        "api_stringly_protocol_collection" => (
            LintProfile::Strict,
            "Protocol or state collections are modeled as raw strings instead of typed values.",
        ),
        "api_stringly_protocol_parameter" => (
            LintProfile::Strict,
            "A boundary takes protocol or state descriptors as raw strings instead of typed values.",
        ),
        "api_stringly_model_scaffold" => (
            LintProfile::Strict,
            "A model carries semantic descriptor fields as raw strings instead of typed structure.",
        ),
        "api_integer_protocol_parameter" => (
            LintProfile::Strict,
            "A caller-facing protocol concept is modeled as a raw integer instead of a typed enum or newtype.",
        ),
        "api_raw_id_surface" => (
            LintProfile::Strict,
            "A caller-facing id is modeled as a raw string or primitive integer instead of a typed id value.",
        ),
        "api_manual_flag_set" => (
            LintProfile::Strict,
            "Parallel integer flag constants suggest a typed flags boundary instead of manual bit masks.",
        ),
        _ => return None,
    };

    Some(DiagnosticCodeInfo { profile, summary })
}

fn minimum_profile_for_code(code: &str) -> LintProfile {
    diagnostic_code_info(code)
        .map(|info| info.profile)
        .unwrap_or(LintProfile::Strict)
}

impl std::str::FromStr for DiagnosticSelection {
    type Err = String;

    fn from_str(raw: &str) -> Result<Self, Self::Err> {
        match raw {
            "all" => Ok(Self::All),
            "policy" => Ok(Self::Policy),
            "advisory" => Ok(Self::Advisory),
            _ => Err(format!(
                "invalid show mode `{raw}`; expected all|policy|advisory"
            )),
        }
    }
}