code-system-graph-core 1.0.1

Core extraction, linking, and query engine for Code System Graph.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
//! Deterministic, conservative cross-repository impact and risk analysis.

use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet, VecDeque};

use code_system_graph_model::{
    CommunityId, CommunitySnapshot, Edge, EdgeId, EdgeKind, EpistemicStatus, EvidenceId, Node, NodeId, NodeKind, RepoFreshness, RepoFreshnessState, RepoId
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use thiserror::Error;

const RISK_MODEL_VERSION: &str = "1.0.0";
const MAX_DEPTH: usize = 128;
const MAX_NODES: usize = 100_000;
const MAX_EDGES: usize = 1_000_000;
const MAX_LIMIT: usize = 10_000;
const MAX_OFFSET: usize = 1_000_000;

/// Conservative risk classification for an impact result.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RiskLevel {
    /// Fresh, complete coverage found only bounded low-risk factors.
    Low,
    /// Material but bounded impact was found.
    Medium,
    /// Broad, breaking, or otherwise severe impact was found.
    High,
    /// Explicit critical-domain evidence and a sufficiently high score were found.
    Critical,
    /// Coverage is insufficient for a numeric risk conclusion.
    Unknown,
}

/// Direction in which impact propagates from the resolved target.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ImpactDirection {
    /// Follow incoming relationships to dependents and consumers.
    Upstream,
    /// Follow outgoing relationships to dependencies and providers.
    Downstream,
    /// Follow both incoming and outgoing relationships.
    Both,
}

/// Confidence-aware classification of one affected graph entity.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ImpactClassification {
    /// A confirmed high-confidence edge directly links the entity to the target.
    DirectlyDependent,
    /// A confirmed high-confidence path transitively links the entity to the target.
    TransitivelyAffected,
    /// Candidate, inferred, ambiguous, or low-confidence evidence may link the entity.
    PossiblyAffected,
    /// Stale or incomplete evidence prevents a stronger classification.
    UnknownDueToCoverage,
}

/// Selector used to resolve exactly one graph target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case", tag = "kind", content = "value")]
pub enum ImpactTarget {
    /// Resolve an exact graph node identifier.
    NodeId(NodeId),
    /// Resolve an exact versioned stable key.
    StableKey(String),
}

/// Exact graph target selected for analysis.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ResolvedTarget {
    /// Resolved graph node.
    pub node: Node,
    /// Canonical selector form used to resolve the node.
    pub resolved_by: String,
}

/// One directed relationship in an impact path.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactPathStep {
    /// Node from which this traversal step began.
    pub from: NodeId,
    /// Node reached by this traversal step.
    pub to: NodeId,
    /// Existing graph relationship used by this step.
    pub edge_id: EdgeId,
    /// Relationship kind.
    pub kind: EdgeKind,
    /// Whether the underlying edge was followed from target to source.
    pub reversed: bool,
    /// Edge confidence as supplied by the graph.
    pub confidence: f32,
    /// Edge epistemic status as supplied by the graph.
    pub status: EpistemicStatus,
}

/// One deterministically selected affected graph entity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactItem {
    /// Affected node.
    pub node: Node,
    /// Conservative impact classification.
    pub classification: ImpactClassification,
    /// Number of graph relationships from the target.
    pub depth: usize,
    /// Deterministic shortest and strongest path selected for this node.
    pub path: Vec<ImpactPathStep>,
    /// Sorted evidence identifiers supporting the selected path.
    pub evidence: Vec<EvidenceId>,
}

/// One explainable component of the versioned risk model.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct RiskFactor {
    /// Stable machine-readable factor code.
    pub code: String,
    /// Non-negative score contribution before the final 100-point cap.
    pub weight: f32,
    /// Bounded human-readable explanation.
    pub explanation: String,
    /// Sorted evidence identifiers or explicit context references.
    pub evidence: Vec<String>,
}

/// Aggregate impact for one repository.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RepositoryImpact {
    /// Affected repository.
    pub repo_id: RepoId,
    /// Strongest impact classification observed in the repository.
    pub classification: ImpactClassification,
    /// Minimum path depth among affected nodes.
    pub minimum_depth: usize,
    /// Number of affected graph nodes before pagination.
    pub affected_nodes: usize,
}

/// Aggregate impact for one service.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ServiceImpact {
    /// Service node.
    pub service: Node,
    /// Strongest impact classification observed for service members.
    pub classification: ImpactClassification,
    /// Minimum path depth among affected service members.
    pub minimum_depth: usize,
    /// Number of affected service members.
    pub affected_nodes: usize,
}

/// Impact on a modeled public or private contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ContractImpact {
    /// Affected contract node.
    pub contract: Node,
    /// Conservative impact classification.
    pub classification: ImpactClassification,
    /// Minimum path depth.
    pub depth: usize,
    /// Whether the contract was explicitly declared public in the analysis context.
    pub public: bool,
}

/// Aggregate impact for one detected graph community.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct CommunityImpact {
    /// Community identity.
    pub community_id: CommunityId,
    /// Deterministic community label.
    pub label: String,
    /// Strongest member impact classification.
    pub classification: ImpactClassification,
    /// Number of affected community members.
    pub affected_members: usize,
    /// Accepted edge weight crossing the community boundary.
    pub coupling: f64,
    /// Explicit community limitations copied from the immutable snapshot.
    pub limitations: Vec<String>,
}

/// Availability state of optional repository-local enrichment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LocalEnrichmentStatus {
    /// The local provider completed with current inputs.
    Available,
    /// The local provider returned only part of the requested result.
    Partial,
    /// The local index does not match current repository inputs.
    Stale,
    /// The local capability or repository index is unavailable.
    Unavailable,
}

/// One repository-local symbol supplied as optional input data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LocalImpactItem {
    /// Provider-local symbol name.
    pub symbol: String,
    /// Repository-relative source path.
    pub file_path: String,
    /// One-based source start line when available.
    pub start_line: Option<usize>,
    /// Local traversal depth.
    pub depth: usize,
}

/// Optional local impact input produced before this pure analysis call.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LocalEnrichmentInput {
    /// Repository to which this local result belongs.
    pub repo_id: RepoId,
    /// Exact local anchor requested from the provider.
    pub anchor: String,
    /// Provider/index availability.
    pub status: LocalEnrichmentStatus,
    /// Bounded affected local symbols.
    pub affected: Vec<LocalImpactItem>,
    /// Bounded affected test paths.
    pub affected_tests: Vec<String>,
    /// Whether provider or adapter bounds truncated this local result.
    pub truncated: bool,
    /// Explicit provider degradations and remediation.
    pub degradations: Vec<String>,
}

/// Visible repository-local enrichment included in the report.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct LocalImpactSummary {
    /// Repository to which the local result belongs.
    pub repo_id: RepoId,
    /// Exact local anchor requested from the provider.
    pub anchor: String,
    /// Provider/index availability.
    pub status: LocalEnrichmentStatus,
    /// Number of local symbols returned.
    pub affected_count: usize,
    /// Maximum local depth observed.
    pub maximum_depth: usize,
    /// Whether the local result was truncated.
    pub truncated: bool,
    /// Explicit provider degradations and remediation.
    pub degradations: Vec<String>,
}

/// Origin of a recommended test.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TestRecommendationSource {
    /// A graph `TestCase` linked by `Validates`.
    Graph,
    /// An affected-test result supplied by optional local enrichment.
    LocalEnrichment,
}

/// Ranked, non-executing recommendation for impact validation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct TestRecommendation {
    /// Stable graph node when the recommendation came from a modeled test case.
    pub test_node_id: Option<NodeId>,
    /// Test label or repository-relative test path.
    pub test: String,
    /// Repository containing the test when known.
    pub repo_id: Option<RepoId>,
    /// Recommendation origin.
    pub source: TestRecommendationSource,
    /// One-based deterministic rank.
    pub rank: usize,
    /// Reasons this test is relevant.
    pub reasons: Vec<String>,
    /// Owner nodes linked to the test or validated impact target.
    pub owners: Vec<Node>,
    /// Explicit commands supplied by context; these are never executed.
    pub recommended_commands: Vec<String>,
}

/// Coverage details that control whether a numeric risk score is permitted.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CoverageSummary {
    /// Whether all required graph, freshness, and enrichment inputs are sufficient.
    pub sufficient_for_score: bool,
    /// Relevant repositories discovered from the target and affected nodes.
    pub relevant_repositories: Vec<RepoId>,
    /// Relevant repositories with fresh inputs.
    pub fresh_repositories: Vec<RepoId>,
    /// Relevant repositories with stale or changed inputs.
    pub stale_repositories: Vec<RepoId>,
    /// Relevant repositories with partial inputs.
    pub partial_repositories: Vec<RepoId>,
    /// Relevant repositories whose checkout or data is unavailable.
    pub unavailable_repositories: Vec<RepoId>,
    /// Relevant repositories without a freshness record.
    pub missing_repositories: Vec<RepoId>,
    /// Number of candidate or low-confidence edges selected by traversal.
    pub possible_edges: usize,
    /// Number of stale or incomplete edges selected by traversal.
    pub unknown_edges: usize,
    /// Explicit coverage limitations in deterministic order.
    pub gaps: Vec<String>,
    /// Concrete remediation guidance in deterministic order.
    pub remediation: Vec<String>,
    /// Total affected items before pagination.
    pub total_items: usize,
}

/// Configured bound that stopped complete traversal or result delivery.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct TruncationInfo {
    /// Stable machine-readable bound name.
    pub bound: String,
    /// Configured bound value.
    pub limit: usize,
    /// Number observed when the bound stopped analysis.
    pub observed: usize,
    /// Explanation of the uncertainty introduced by truncation.
    pub explanation: String,
}

/// Counts of impact classifications at one exact path depth.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactDepthBucket {
    /// Exact path depth represented by this bucket.
    pub depth: usize,
    /// Directly dependent item count.
    pub directly_dependent: usize,
    /// Transitively affected item count.
    pub transitively_affected: usize,
    /// Possibly affected item count.
    pub possibly_affected: usize,
    /// Coverage-unknown item count.
    pub unknown_due_to_coverage: usize,
}

/// Deterministic bounds and presentation controls for impact analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactOptions {
    /// Maximum graph path depth.
    #[serde(default = "default_impact_max_depth")]
    pub max_depth: usize,
    /// Maximum number of distinct affected nodes.
    #[serde(default = "default_impact_node_limit")]
    pub node_limit: usize,
    /// Maximum number of graph edges examined.
    #[serde(default = "default_impact_edge_limit")]
    pub edge_limit: usize,
    /// Minimum confidence required for a confirmed edge.
    #[serde(default = "default_confirmed_confidence")]
    pub confirmed_confidence: f32,
    /// Zero-based offset over the stable combined impact order.
    #[serde(default)]
    pub offset: usize,
    /// Maximum number of detailed items returned.
    #[serde(default = "default_impact_limit")]
    pub limit: usize,
    /// Omit detailed impact-item lists while retaining aggregates and counts.
    #[serde(default)]
    pub summary_only: bool,
    /// Include exact-depth classification buckets.
    #[serde(default = "default_include_depth_buckets")]
    pub include_depth_buckets: bool,
}

impl Default for ImpactOptions {
    fn default() -> Self {
        Self {
            max_depth: default_impact_max_depth(),
            node_limit: default_impact_node_limit(),
            edge_limit: default_impact_edge_limit(),
            confirmed_confidence: default_confirmed_confidence(),
            offset: 0,
            limit: default_impact_limit(),
            summary_only: false,
            include_depth_buckets: default_include_depth_buckets(),
        }
    }
}

const fn default_impact_max_depth() -> usize {
    8
}

const fn default_impact_node_limit() -> usize {
    10_000
}

const fn default_impact_edge_limit() -> usize {
    50_000
}

const fn default_confirmed_confidence() -> f32 {
    0.8
}

const fn default_impact_limit() -> usize {
    100
}

const fn default_include_depth_buckets() -> bool {
    true
}

/// Request for one deterministic impact analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactRequest {
    /// Exact node identifier or stable key selector.
    pub target: ImpactTarget,
    /// Requested propagation direction.
    pub direction: ImpactDirection,
    /// Traversal and presentation controls.
    #[serde(default)]
    pub options: ImpactOptions,
}

/// Compatibility classification supplied to the impact engine.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ImpactCompatibilityStatus {
    /// A supported compatibility rule proves a breaking change.
    Breaking,
    /// The change can be breaking but requires runtime or policy confirmation.
    PotentiallyBreaking,
    /// Modeled rules prove compatibility under complete inputs.
    Compatible,
    /// Compatibility coverage is insufficient.
    Unknown,
}

/// Compatibility result associated with a graph contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CompatibilityInput {
    /// Contract node to which this result applies.
    pub contract_node_id: NodeId,
    /// Conservative compatibility classification.
    pub status: ImpactCompatibilityStatus,
    /// Stable rule codes or bounded evidence references.
    pub evidence: Vec<String>,
    /// Recommended compatibility validations.
    pub recommended_validations: Vec<String>,
}

/// Explicit critical-domain tag; labels are never interpreted as tags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CriticalityTag {
    /// Explicitly designated critical system or process.
    Critical,
    /// Authentication or authorization boundary.
    Authentication,
    /// Security-sensitive boundary.
    Security,
    /// Payment or financial boundary.
    Payment,
    /// Data governance, privacy, or storage boundary.
    DataBoundary,
}

/// Explicit, evidence-backed critical-domain assignment.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct CriticalityAssignment {
    /// Tagged graph node.
    pub node_id: NodeId,
    /// Explicit critical-domain tag.
    pub tag: CriticalityTag,
    /// Non-empty evidence or policy reference supplied by the caller.
    pub evidence: Vec<String>,
}

/// Explicit deployment environment associated with a graph node.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct EnvironmentAssignment {
    /// Deployment, service, contract, or repository node.
    pub node_id: NodeId,
    /// Canonical environment name supplied by configuration.
    pub environment: String,
}

/// Explicit non-executing validation command supplied by configuration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RecommendedCommand {
    /// Repository in which the command is valid.
    pub repo_id: RepoId,
    /// Command displayed to the caller but never executed by this module.
    pub command: String,
    /// Bounded explanation of the command's purpose.
    pub description: String,
}

/// Complete immutable input context for pure impact analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactContext {
    /// Federated graph nodes.
    pub nodes: Vec<Node>,
    /// Federated graph relationships.
    pub edges: Vec<Edge>,
    /// Optional immutable community analysis for this graph snapshot.
    pub communities: Option<CommunitySnapshot>,
    /// Repository freshness records.
    pub freshness: Vec<RepoFreshness>,
    /// Compatibility results computed before this call.
    pub compatibility: Vec<CompatibilityInput>,
    /// Optional repository-local impact and affected-test inputs.
    pub local_enrichment: Vec<LocalEnrichmentInput>,
    /// Nodes explicitly declared to be public contracts.
    pub public_contracts: Vec<NodeId>,
    /// Explicit critical-domain assignments.
    pub criticality: Vec<CriticalityAssignment>,
    /// Normalized centrality scores keyed by graph node.
    pub centrality: BTreeMap<NodeId, f32>,
    /// Service memberships keyed by member node.
    pub service_memberships: BTreeMap<NodeId, Vec<NodeId>>,
    /// Explicit deployment environment assignments.
    pub environments: Vec<EnvironmentAssignment>,
    /// Explicit non-executing validation commands.
    pub recommended_commands: Vec<RecommendedCommand>,
    /// Whether graph extraction and linking completed for the requested workspace.
    pub graph_complete: bool,
    /// Additional known coverage gaps.
    pub coverage_gaps: Vec<String>,
}

/// Complete deterministic impact and risk result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactReport {
    /// Version of the deterministic risk model.
    pub risk_model_version: String,
    /// Exact target selected for analysis.
    pub target: ResolvedTarget,
    /// Applied propagation direction.
    pub direction: ImpactDirection,
    /// Conservative aggregate risk.
    pub risk: RiskLevel,
    /// Positive score in `0..=100`, omitted whenever risk is unknown.
    pub risk_score: Option<f32>,
    /// Deterministically ordered risk factors.
    pub reasons: Vec<RiskFactor>,
    /// Confirmed depth-one dependents in the selected page.
    pub direct_consumers: Vec<ImpactItem>,
    /// Confirmed depth-two-or-greater impacts in the selected page.
    pub transitive_consumers: Vec<ImpactItem>,
    /// Candidate, inferred, ambiguous, or low-confidence impacts in the selected page.
    pub possibly_affected: Vec<ImpactItem>,
    /// Impacts whose selected path contains stale or incomplete evidence.
    pub unknown_due_to_coverage: Vec<ImpactItem>,
    /// Repository aggregates computed before pagination.
    pub affected_repositories: Vec<RepositoryImpact>,
    /// Service aggregates computed before pagination.
    pub affected_services: Vec<ServiceImpact>,
    /// Contract impacts computed before pagination.
    pub affected_contracts: Vec<ContractImpact>,
    /// Community aggregates computed before pagination.
    pub affected_communities: Vec<CommunityImpact>,
    /// Optional local-enrichment summaries.
    pub local_impact_summaries: Vec<LocalImpactSummary>,
    /// Ranked test recommendations.
    pub test_recommendations: Vec<TestRecommendation>,
    /// Optional exact-depth counts computed before pagination.
    pub depth_buckets: Vec<ImpactDepthBucket>,
    /// Coverage and remediation details.
    pub coverage: CoverageSummary,
    /// First configured bound that introduced uncertainty.
    pub truncation: Option<TruncationInfo>,
}

/// Validation error returned before impact analysis begins.
#[derive(Debug, Error, PartialEq)]
pub enum ImpactError {
    /// More than one graph node has the same identifier.
    #[error("duplicate node identifier `{0}`")]
    DuplicateNode(String),
    /// More than one graph relationship has the same identifier.
    #[error("duplicate edge identifier `{0}`")]
    DuplicateEdge(String),
    /// More than one freshness record exists for the same repository.
    #[error("duplicate freshness record for repository `{0}`")]
    DuplicateFreshness(String),
    /// A graph relationship references a missing endpoint.
    #[error("edge `{edge}` references missing node `{node}`")]
    DanglingEdge {
        /// Relationship identifier.
        edge: String,
        /// Missing endpoint identifier.
        node: String,
    },
    /// An input edge has non-finite or out-of-range confidence.
    #[error("edge `{0}` confidence must be finite and in the inclusive range 0..=1")]
    InvalidEdgeConfidence(String),
    /// The configured confirmed-confidence threshold is invalid.
    #[error("confirmed confidence must be finite and in the inclusive range 0..=1")]
    InvalidConfirmedConfidence,
    /// One or more traversal or pagination bounds are invalid.
    #[error("impact traversal or pagination bounds are outside supported limits")]
    InvalidBounds,
    /// A supplied centrality score is non-finite or out of range.
    #[error("centrality for node `{0}` must be finite and in the inclusive range 0..=1")]
    InvalidCentrality(String),
    /// An explicit criticality assignment has no evidence.
    #[error("criticality assignment for node `{0}` requires explicit evidence")]
    CriticalityWithoutEvidence(String),
    /// An input context references a node absent from the graph.
    #[error("{context} references missing node `{node}`")]
    UnknownContextNode {
        /// Context collection containing the reference.
        context: &'static str,
        /// Missing node identifier.
        node: String,
    },
    /// No graph node matches the requested target.
    #[error("impact target was not found")]
    UnknownTarget,
    /// A stable-key selector resolves to more than one node.
    #[error("stable key `{0}` resolves to more than one node")]
    AmbiguousTarget(String),
}

#[derive(Debug, Clone)]
struct TraversalState {
    node_id: NodeId,
    certainty: PathCertainty,
    path: Vec<ImpactPathStep>,
    evidence: BTreeSet<EvidenceId>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum PathCertainty {
    Confirmed,
    Possible,
    Unknown,
}

#[derive(Debug, Clone)]
struct Adjacency<'a> {
    neighbor: NodeId,
    edge: &'a Edge,
    reversed: bool,
}

#[derive(Debug, Clone, Copy)]
struct Aggregate {
    classification: ImpactClassification,
    minimum_depth: usize,
    affected_nodes: usize,
}

/// Performs pure deterministic impact propagation, aggregation, and conservative risk analysis.
///
/// The function never invokes providers or executes commands. Optional compatibility, local
/// intelligence, environment, criticality, and command data must already be present in `context`.
///
/// # Errors
///
/// Returns [`ImpactError`] when graph identities, references, confidence values, centrality
/// scores, criticality evidence, target resolution, or configured bounds are invalid.
#[must_use = "impact reports and validation errors must be handled"]
pub fn analyze_impact(
    request: &ImpactRequest,
    context: &ImpactContext,
) -> Result<ImpactReport, ImpactError> {
    let nodes = validate_context(request, context)?;
    let target = resolve_target(&request.target, &nodes)?;
    let (mut items, truncation, possible_edges, unknown_edges) =
        traverse(request, context, &nodes, &target.node)?;
    sort_items(&mut items);

    let repositories = aggregate_repositories(&items);
    let services = aggregate_services(&items, context, &nodes);
    let contracts = aggregate_contracts(&items, context);
    let communities = aggregate_communities(&items, context);
    let local_summaries = summarize_local_enrichment(context);
    let tests = recommend_tests(&items, context, &nodes);
    let depth_buckets = if request.options.include_depth_buckets {
        build_depth_buckets(&items)
    } else {
        Vec::new()
    };
    let coverage = coverage_summary(
        &target.node,
        &items,
        context,
        truncation.as_ref(),
        possible_edges,
        unknown_edges,
    );
    let (risk, risk_score, reasons) = assess_risk(
        &target.node,
        &items,
        &repositories,
        &services,
        &contracts,
        &communities,
        &tests,
        context,
        &coverage,
        truncation.as_ref(),
    );

    let page = if request.options.summary_only {
        Vec::new()
    } else {
        items
            .iter()
            .skip(request.options.offset.min(items.len()))
            .take(request.options.limit)
            .cloned()
            .collect()
    };
    let (direct, transitive, possible, unknown) = split_classifications(page);

    Ok(ImpactReport {
        risk_model_version: RISK_MODEL_VERSION.to_owned(),
        target,
        direction: request.direction,
        risk,
        risk_score,
        reasons,
        direct_consumers: direct,
        transitive_consumers: transitive,
        possibly_affected: possible,
        unknown_due_to_coverage: unknown,
        affected_repositories: repositories,
        affected_services: services,
        affected_contracts: contracts,
        affected_communities: communities,
        local_impact_summaries: local_summaries,
        test_recommendations: tests,
        depth_buckets,
        coverage,
        truncation,
    })
}

fn validate_context<'a>(
    request: &ImpactRequest,
    context: &'a ImpactContext,
) -> Result<BTreeMap<NodeId, &'a Node>, ImpactError> {
    let options = &request.options;
    if options.max_depth == 0
        || options.max_depth > MAX_DEPTH
        || options.node_limit == 0
        || options.node_limit > MAX_NODES
        || options.edge_limit == 0
        || options.edge_limit > MAX_EDGES
        || options.limit == 0
        || options.limit > MAX_LIMIT
        || options.offset > MAX_OFFSET
    {
        return Err(ImpactError::InvalidBounds);
    }
    if !options.confirmed_confidence.is_finite()
        || !(0.0..=1.0).contains(&options.confirmed_confidence)
    {
        return Err(ImpactError::InvalidConfirmedConfidence);
    }

    let mut nodes = BTreeMap::new();
    for node in &context.nodes {
        if nodes.insert(node.id.clone(), node).is_some() {
            return Err(ImpactError::DuplicateNode(node.id.as_str().to_owned()));
        }
    }
    let mut edge_ids = BTreeSet::new();
    for edge in &context.edges {
        if !edge_ids.insert(edge.id.clone()) {
            return Err(ImpactError::DuplicateEdge(edge.id.as_str().to_owned()));
        }
        if !edge.confidence.is_finite() || !(0.0..=1.0).contains(&edge.confidence) {
            return Err(ImpactError::InvalidEdgeConfidence(
                edge.id.as_str().to_owned(),
            ));
        }
        for endpoint in [&edge.source, &edge.target] {
            if !nodes.contains_key(endpoint) {
                return Err(ImpactError::DanglingEdge {
                    edge: edge.id.as_str().to_owned(),
                    node: endpoint.as_str().to_owned(),
                });
            }
        }
    }
    let mut freshness_repositories = BTreeSet::new();
    for record in &context.freshness {
        if !freshness_repositories.insert(&record.repo_id) {
            return Err(ImpactError::DuplicateFreshness(
                record.repo_id.as_str().to_owned(),
            ));
        }
    }
    for (node_id, centrality) in &context.centrality {
        validate_node_reference(&nodes, node_id, "centrality")?;
        if !centrality.is_finite() || !(0.0..=1.0).contains(centrality) {
            return Err(ImpactError::InvalidCentrality(node_id.as_str().to_owned()));
        }
    }
    for assignment in &context.criticality {
        validate_node_reference(&nodes, &assignment.node_id, "criticality")?;
        if assignment.evidence.is_empty()
            || assignment
                .evidence
                .iter()
                .any(|value| value.trim().is_empty())
        {
            return Err(ImpactError::CriticalityWithoutEvidence(
                assignment.node_id.as_str().to_owned(),
            ));
        }
    }
    for compatibility in &context.compatibility {
        validate_node_reference(&nodes, &compatibility.contract_node_id, "compatibility")?;
    }
    for node_id in &context.public_contracts {
        validate_node_reference(&nodes, node_id, "public_contracts")?;
    }
    for assignment in &context.environments {
        validate_node_reference(&nodes, &assignment.node_id, "environments")?;
    }
    for (member, services) in &context.service_memberships {
        validate_node_reference(&nodes, member, "service_memberships")?;
        for service in services {
            validate_node_reference(&nodes, service, "service_memberships")?;
        }
    }
    Ok(nodes)
}

fn validate_node_reference(
    nodes: &BTreeMap<NodeId, &Node>,
    node_id: &NodeId,
    context: &'static str,
) -> Result<(), ImpactError> {
    if nodes.contains_key(node_id) {
        Ok(())
    } else {
        Err(ImpactError::UnknownContextNode {
            context,
            node: node_id.as_str().to_owned(),
        })
    }
}

fn resolve_target(
    selector: &ImpactTarget,
    nodes: &BTreeMap<NodeId, &Node>,
) -> Result<ResolvedTarget, ImpactError> {
    match selector {
        ImpactTarget::NodeId(node_id) => nodes
            .get(node_id)
            .map(|node| ResolvedTarget {
                node: (*node).clone(),
                resolved_by: "node_id".to_owned(),
            })
            .ok_or(ImpactError::UnknownTarget),
        ImpactTarget::StableKey(stable_key) => {
            let mut matches = nodes.values().filter(|node| node.stable_key == *stable_key);
            let Some(node) = matches.next() else {
                return Err(ImpactError::UnknownTarget);
            };
            if matches.next().is_some() {
                return Err(ImpactError::AmbiguousTarget(stable_key.clone()));
            }
            Ok(ResolvedTarget {
                node: (*node).clone(),
                resolved_by: "stable_key".to_owned(),
            })
        }
    }
}

#[expect(
    clippy::too_many_lines,
    reason = "The bounded BFS state transitions remain together for auditability"
)]
fn traverse(
    request: &ImpactRequest,
    context: &ImpactContext,
    nodes: &BTreeMap<NodeId, &Node>,
    target: &Node,
) -> Result<(Vec<ImpactItem>, Option<TruncationInfo>, usize, usize), ImpactError> {
    let adjacency = build_adjacency(&context.edges, request.direction);
    let mut queue = VecDeque::from([TraversalState {
        node_id: target.id.clone(),
        certainty: PathCertainty::Confirmed,
        path: Vec::new(),
        evidence: BTreeSet::new(),
    }]);
    let mut best = BTreeMap::<NodeId, (PathCertainty, usize)>::new();
    best.insert(target.id.clone(), (PathCertainty::Confirmed, 0));
    let mut items = BTreeMap::<NodeId, ImpactItem>::new();
    let mut examined_edges = 0_usize;
    let mut possible_edges = 0_usize;
    let mut unknown_edges = 0_usize;
    let mut truncation = None;

    while let Some(state) = queue.pop_front() {
        let depth = state.path.len();
        let neighbors = adjacency.get(&state.node_id).map_or(&[][..], Vec::as_slice);
        if depth == request.options.max_depth {
            if neighbors.iter().any(|entry| {
                is_propagating(entry.edge.kind)
                    && !state.path.iter().any(|step| step.from == entry.neighbor)
            }) {
                truncation.get_or_insert_with(|| TruncationInfo {
                    bound: "max_depth".to_owned(),
                    limit: request.options.max_depth,
                    observed: depth,
                    explanation: "additional graph relationships exist beyond maximum depth"
                        .to_owned(),
                });
            }
            continue;
        }
        for entry in neighbors {
            if !is_propagating(entry.edge.kind) {
                continue;
            }
            examined_edges = examined_edges.saturating_add(1);
            if examined_edges > request.options.edge_limit {
                truncation.get_or_insert_with(|| TruncationInfo {
                    bound: "edge_limit".to_owned(),
                    limit: request.options.edge_limit,
                    observed: examined_edges,
                    explanation: "edge examination limit stopped impact propagation".to_owned(),
                });
                break;
            }
            if entry.neighbor == target.id
                || state
                    .path
                    .iter()
                    .any(|step| step.from == entry.neighbor || step.to == entry.neighbor)
            {
                continue;
            }
            let edge_certainty = edge_certainty(entry.edge, request.options.confirmed_confidence);
            match edge_certainty {
                PathCertainty::Confirmed => {}
                PathCertainty::Possible => possible_edges = possible_edges.saturating_add(1),
                PathCertainty::Unknown => unknown_edges = unknown_edges.saturating_add(1),
            }
            let certainty = state.certainty.max(edge_certainty);
            let next_depth = depth.saturating_add(1);
            if best
                .get(&entry.neighbor)
                .is_some_and(|existing| *existing <= (certainty, next_depth))
            {
                continue;
            }
            if !items.contains_key(&entry.neighbor) && items.len() >= request.options.node_limit {
                truncation.get_or_insert_with(|| TruncationInfo {
                    bound: "node_limit".to_owned(),
                    limit: request.options.node_limit,
                    observed: items.len().saturating_add(1),
                    explanation: "distinct-node limit stopped impact propagation".to_owned(),
                });
                break;
            }
            let mut path = state.path.clone();
            path.push(ImpactPathStep {
                from: state.node_id.clone(),
                to: entry.neighbor.clone(),
                edge_id: entry.edge.id.clone(),
                kind: entry.edge.kind,
                reversed: entry.reversed,
                confidence: entry.edge.confidence,
                status: entry.edge.status,
            });
            let mut evidence = state.evidence.clone();
            evidence.extend(entry.edge.evidence.iter().cloned());
            let classification = classify(certainty, next_depth);
            let Some(node) = nodes.get(&entry.neighbor) else {
                return Err(ImpactError::DanglingEdge {
                    edge: entry.edge.id.as_str().to_owned(),
                    node: entry.neighbor.as_str().to_owned(),
                });
            };
            best.insert(entry.neighbor.clone(), (certainty, next_depth));
            items.insert(
                entry.neighbor.clone(),
                ImpactItem {
                    node: (*node).clone(),
                    classification,
                    depth: next_depth,
                    path: path.clone(),
                    evidence: evidence.iter().cloned().collect(),
                },
            );
            queue.push_back(TraversalState {
                node_id: entry.neighbor.clone(),
                certainty,
                path,
                evidence,
            });
        }
        if truncation
            .as_ref()
            .is_some_and(|value| value.bound == "edge_limit" || value.bound == "node_limit")
        {
            break;
        }
    }
    Ok((
        items.into_values().collect(),
        truncation,
        possible_edges,
        unknown_edges,
    ))
}

fn build_adjacency(
    edges: &[Edge],
    direction: ImpactDirection,
) -> BTreeMap<NodeId, Vec<Adjacency<'_>>> {
    let mut adjacency = BTreeMap::<NodeId, Vec<Adjacency<'_>>>::new();
    for edge in edges {
        if matches!(
            direction,
            ImpactDirection::Downstream | ImpactDirection::Both
        ) {
            adjacency
                .entry(edge.source.clone())
                .or_default()
                .push(Adjacency {
                    neighbor: edge.target.clone(),
                    edge,
                    reversed: false,
                });
        }
        if matches!(direction, ImpactDirection::Upstream | ImpactDirection::Both) {
            adjacency
                .entry(edge.target.clone())
                .or_default()
                .push(Adjacency {
                    neighbor: edge.source.clone(),
                    edge,
                    reversed: true,
                });
        }
    }
    for entries in adjacency.values_mut() {
        entries.sort_by(|left, right| {
            left.neighbor
                .cmp(&right.neighbor)
                .then_with(|| left.edge.id.cmp(&right.edge.id))
                .then_with(|| left.reversed.cmp(&right.reversed))
        });
    }
    adjacency
}

fn is_propagating(kind: EdgeKind) -> bool {
    !matches!(
        kind,
        EdgeKind::Validates
            | EdgeKind::OwnedBy
            | EdgeKind::Documents
            | EdgeKind::MemberOf
            | EdgeKind::Precedes
            | EdgeKind::Reverts
            | EdgeKind::CompatibleWith
    )
}

fn edge_certainty(edge: &Edge, confirmed_confidence: f32) -> PathCertainty {
    match edge.status {
        EpistemicStatus::Confirmed if edge.confidence >= confirmed_confidence => {
            PathCertainty::Confirmed
        }
        EpistemicStatus::Confirmed | EpistemicStatus::Inferred | EpistemicStatus::Ambiguous => {
            PathCertainty::Possible
        }
        EpistemicStatus::Stale | EpistemicStatus::Incomplete => PathCertainty::Unknown,
    }
}

fn classify(certainty: PathCertainty, depth: usize) -> ImpactClassification {
    match (certainty, depth) {
        (PathCertainty::Confirmed, 1) => ImpactClassification::DirectlyDependent,
        (PathCertainty::Confirmed, _) => ImpactClassification::TransitivelyAffected,
        (PathCertainty::Possible, _) => ImpactClassification::PossiblyAffected,
        (PathCertainty::Unknown, _) => ImpactClassification::UnknownDueToCoverage,
    }
}

fn classification_rank(classification: ImpactClassification) -> u8 {
    match classification {
        ImpactClassification::DirectlyDependent => 0,
        ImpactClassification::TransitivelyAffected => 1,
        ImpactClassification::PossiblyAffected => 2,
        ImpactClassification::UnknownDueToCoverage => 3,
    }
}

fn stronger(left: ImpactClassification, right: ImpactClassification) -> ImpactClassification {
    if classification_rank(left) <= classification_rank(right) {
        left
    } else {
        right
    }
}

fn sort_items(items: &mut [ImpactItem]) {
    items.sort_by(|left, right| {
        classification_rank(left.classification)
            .cmp(&classification_rank(right.classification))
            .then_with(|| left.depth.cmp(&right.depth))
            .then_with(|| left.node.repo_id.cmp(&right.node.repo_id))
            .then_with(|| left.node.stable_key.cmp(&right.node.stable_key))
            .then_with(|| left.node.id.cmp(&right.node.id))
            .then_with(|| path_key(&left.path).cmp(&path_key(&right.path)))
    });
}

fn path_key(path: &[ImpactPathStep]) -> Vec<(&str, bool)> {
    path.iter()
        .map(|step| (step.edge_id.as_str(), step.reversed))
        .collect()
}

fn aggregate_repositories(items: &[ImpactItem]) -> Vec<RepositoryImpact> {
    let mut aggregates = BTreeMap::<RepoId, Aggregate>::new();
    for item in items {
        let Some(repo_id) = &item.node.repo_id else {
            continue;
        };
        update_aggregate(&mut aggregates, repo_id.clone(), item);
    }
    aggregates
        .into_iter()
        .map(|(repo_id, aggregate)| RepositoryImpact {
            repo_id,
            classification: aggregate.classification,
            minimum_depth: aggregate.minimum_depth,
            affected_nodes: aggregate.affected_nodes,
        })
        .collect()
}

fn aggregate_services(
    items: &[ImpactItem],
    context: &ImpactContext,
    nodes: &BTreeMap<NodeId, &Node>,
) -> Vec<ServiceImpact> {
    let mut aggregates = BTreeMap::<NodeId, Aggregate>::new();
    for item in items {
        if item.node.kind == NodeKind::Service {
            update_aggregate(&mut aggregates, item.node.id.clone(), item);
        }
        if let Some(service_ids) = context.service_memberships.get(&item.node.id) {
            for service_id in service_ids {
                update_aggregate(&mut aggregates, service_id.clone(), item);
            }
        }
    }
    aggregates
        .into_iter()
        .filter_map(|(service_id, aggregate)| {
            nodes.get(&service_id).map(|service| ServiceImpact {
                service: (*service).clone(),
                classification: aggregate.classification,
                minimum_depth: aggregate.minimum_depth,
                affected_nodes: aggregate.affected_nodes,
            })
        })
        .collect()
}

fn update_aggregate<K: Ord>(aggregates: &mut BTreeMap<K, Aggregate>, key: K, item: &ImpactItem) {
    aggregates
        .entry(key)
        .and_modify(|aggregate| {
            aggregate.classification = stronger(aggregate.classification, item.classification);
            aggregate.minimum_depth = aggregate.minimum_depth.min(item.depth);
            aggregate.affected_nodes = aggregate.affected_nodes.saturating_add(1);
        })
        .or_insert(Aggregate {
            classification: item.classification,
            minimum_depth: item.depth,
            affected_nodes: 1,
        });
}

fn aggregate_contracts(items: &[ImpactItem], context: &ImpactContext) -> Vec<ContractImpact> {
    let public = context.public_contracts.iter().collect::<BTreeSet<_>>();
    items
        .iter()
        .filter(|item| is_contract(item.node.kind))
        .map(|item| ContractImpact {
            contract: item.node.clone(),
            classification: item.classification,
            depth: item.depth,
            public: public.contains(&item.node.id),
        })
        .collect()
}

fn is_contract(kind: NodeKind) -> bool {
    matches!(
        kind,
        NodeKind::HttpOperation
            | NodeKind::GraphqlOperation
            | NodeKind::RpcMethod
            | NodeKind::EventChannel
            | NodeKind::EventSchema
            | NodeKind::DatabaseTable
            | NodeKind::DatabaseColumn
            | NodeKind::ConfigKey
    )
}

fn aggregate_communities(items: &[ImpactItem], context: &ImpactContext) -> Vec<CommunityImpact> {
    let Some(snapshot) = &context.communities else {
        return Vec::new();
    };
    let impacted = items
        .iter()
        .map(|item| (&item.node.id, item))
        .collect::<BTreeMap<_, _>>();
    let mut result = Vec::new();
    for community in &snapshot.communities {
        let mut aggregate = None::<Aggregate>;
        for member in &community.members {
            if let Some(item) = impacted.get(member) {
                let current = aggregate.get_or_insert(Aggregate {
                    classification: item.classification,
                    minimum_depth: item.depth,
                    affected_nodes: 0,
                });
                current.classification = stronger(current.classification, item.classification);
                current.minimum_depth = current.minimum_depth.min(item.depth);
                current.affected_nodes = current.affected_nodes.saturating_add(1);
            }
        }
        if let Some(aggregate) = aggregate {
            result.push(CommunityImpact {
                community_id: community.id.clone(),
                label: community.label.clone(),
                classification: aggregate.classification,
                affected_members: aggregate.affected_nodes,
                coupling: community.metrics.coupling,
                limitations: community.limitations.clone(),
            });
        }
    }
    result.sort_by(|left, right| left.community_id.cmp(&right.community_id));
    result
}

fn summarize_local_enrichment(context: &ImpactContext) -> Vec<LocalImpactSummary> {
    let mut summaries = context
        .local_enrichment
        .iter()
        .map(|input| LocalImpactSummary {
            repo_id: input.repo_id.clone(),
            anchor: input.anchor.clone(),
            status: input.status,
            affected_count: input.affected.len(),
            maximum_depth: input
                .affected
                .iter()
                .map(|item| item.depth)
                .max()
                .unwrap_or(0),
            truncated: input.truncated,
            degradations: sorted_unique(input.degradations.clone()),
        })
        .collect::<Vec<_>>();
    summaries.sort_by(|left, right| {
        left.repo_id
            .cmp(&right.repo_id)
            .then_with(|| left.anchor.cmp(&right.anchor))
    });
    summaries
}

fn recommend_tests(
    items: &[ImpactItem],
    context: &ImpactContext,
    nodes: &BTreeMap<NodeId, &Node>,
) -> Vec<TestRecommendation> {
    let impacted = items
        .iter()
        .map(|item| (&item.node.id, item))
        .collect::<BTreeMap<_, _>>();
    let mut recommendations = Vec::new();
    for edge in &context.edges {
        if edge.kind != EdgeKind::Validates {
            continue;
        }
        let (test_id, validated_id) = if nodes
            .get(&edge.source)
            .is_some_and(|node| node.kind == NodeKind::TestCase)
        {
            (&edge.source, &edge.target)
        } else if nodes
            .get(&edge.target)
            .is_some_and(|node| node.kind == NodeKind::TestCase)
        {
            (&edge.target, &edge.source)
        } else {
            continue;
        };
        let Some(item) = impacted.get(validated_id) else {
            continue;
        };
        let Some(test) = nodes.get(test_id) else {
            continue;
        };
        recommendations.push(TestRecommendation {
            test_node_id: Some(test.id.clone()),
            test: test.label.clone(),
            repo_id: test.repo_id.clone(),
            source: TestRecommendationSource::Graph,
            rank: 0,
            reasons: vec![format!(
                "validates impacted node `{}` at depth {}",
                item.node.stable_key, item.depth
            )],
            owners: owners_for(&test.id, validated_id, context, nodes),
            recommended_commands: commands_for(test.repo_id.as_ref(), context),
        });
    }
    for local in &context.local_enrichment {
        for test in &local.affected_tests {
            recommendations.push(TestRecommendation {
                test_node_id: None,
                test: test.clone(),
                repo_id: Some(local.repo_id.clone()),
                source: TestRecommendationSource::LocalEnrichment,
                rank: 0,
                reasons: vec![format!(
                    "optional local enrichment for anchor `{}` reported this test",
                    local.anchor
                )],
                owners: Vec::new(),
                recommended_commands: commands_for(Some(&local.repo_id), context),
            });
        }
    }
    recommendations.sort_by(|left, right| {
        test_source_rank(left.source)
            .cmp(&test_source_rank(right.source))
            .then_with(|| left.repo_id.cmp(&right.repo_id))
            .then_with(|| left.test.cmp(&right.test))
            .then_with(|| left.test_node_id.cmp(&right.test_node_id))
    });
    recommendations.dedup_by(|left, right| {
        left.test_node_id == right.test_node_id
            && left.repo_id == right.repo_id
            && left.test == right.test
    });
    for (index, recommendation) in recommendations.iter_mut().enumerate() {
        recommendation.rank = index.saturating_add(1);
    }
    recommendations
}

fn test_source_rank(source: TestRecommendationSource) -> u8 {
    match source {
        TestRecommendationSource::Graph => 0,
        TestRecommendationSource::LocalEnrichment => 1,
    }
}

fn owners_for(
    test_id: &NodeId,
    validated_id: &NodeId,
    context: &ImpactContext,
    nodes: &BTreeMap<NodeId, &Node>,
) -> Vec<Node> {
    let mut owner_ids = BTreeSet::new();
    for edge in &context.edges {
        if edge.kind == EdgeKind::OwnedBy
            && (&edge.source == test_id || &edge.source == validated_id)
            && nodes
                .get(&edge.target)
                .is_some_and(|node| node.kind == NodeKind::Owner)
        {
            owner_ids.insert(edge.target.clone());
        }
    }
    owner_ids
        .iter()
        .filter_map(|owner_id| nodes.get(owner_id).map(|node| (*node).clone()))
        .collect()
}

fn commands_for(repo_id: Option<&RepoId>, context: &ImpactContext) -> Vec<String> {
    let mut commands = context
        .recommended_commands
        .iter()
        .filter(|command| repo_id.is_some_and(|repo| repo == &command.repo_id))
        .map(|command| command.command.clone())
        .collect::<Vec<_>>();
    commands.sort();
    commands.dedup();
    commands
}

fn build_depth_buckets(items: &[ImpactItem]) -> Vec<ImpactDepthBucket> {
    let mut buckets = BTreeMap::<usize, ImpactDepthBucket>::new();
    for item in items {
        let bucket = buckets.entry(item.depth).or_insert(ImpactDepthBucket {
            depth: item.depth,
            directly_dependent: 0,
            transitively_affected: 0,
            possibly_affected: 0,
            unknown_due_to_coverage: 0,
        });
        match item.classification {
            ImpactClassification::DirectlyDependent => {
                bucket.directly_dependent = bucket.directly_dependent.saturating_add(1);
            }
            ImpactClassification::TransitivelyAffected => {
                bucket.transitively_affected = bucket.transitively_affected.saturating_add(1);
            }
            ImpactClassification::PossiblyAffected => {
                bucket.possibly_affected = bucket.possibly_affected.saturating_add(1);
            }
            ImpactClassification::UnknownDueToCoverage => {
                bucket.unknown_due_to_coverage = bucket.unknown_due_to_coverage.saturating_add(1);
            }
        }
    }
    buckets.into_values().collect()
}

#[expect(
    clippy::too_many_lines,
    reason = "Coverage states and their paired remediations remain visibly exhaustive"
)]
fn coverage_summary(
    target: &Node,
    items: &[ImpactItem],
    context: &ImpactContext,
    truncation: Option<&TruncationInfo>,
    possible_edges: usize,
    unknown_edges: usize,
) -> CoverageSummary {
    let mut relevant = items
        .iter()
        .filter_map(|item| item.node.repo_id.clone())
        .collect::<BTreeSet<_>>();
    relevant.extend(target.repo_id.iter().cloned());
    let freshness = context
        .freshness
        .iter()
        .map(|record| (&record.repo_id, record.state))
        .collect::<BTreeMap<_, _>>();
    let mut fresh = Vec::new();
    let mut stale = Vec::new();
    let mut partial = Vec::new();
    let mut unavailable = Vec::new();
    let mut missing = Vec::new();
    for repo_id in &relevant {
        match freshness.get(repo_id) {
            Some(RepoFreshnessState::Fresh) => fresh.push(repo_id.clone()),
            Some(
                RepoFreshnessState::WorkingTreeChanged
                | RepoFreshnessState::CommitsBehind
                | RepoFreshnessState::ConfigChanged
                | RepoFreshnessState::ExtractorChanged
                | RepoFreshnessState::CodegraphPending,
            ) => stale.push(repo_id.clone()),
            Some(RepoFreshnessState::Partial) => partial.push(repo_id.clone()),
            Some(RepoFreshnessState::Unavailable | RepoFreshnessState::Corrupt) => {
                unavailable.push(repo_id.clone());
            }
            Some(RepoFreshnessState::Unknown) | None => missing.push(repo_id.clone()),
        }
    }
    let mut gaps = context.coverage_gaps.clone();
    let mut remediation = Vec::new();
    if !context.coverage_gaps.is_empty() {
        remediation.push("resolve each caller-supplied coverage gap and rerun analysis".to_owned());
    }
    if !context.graph_complete {
        gaps.push("federated graph extraction or linking is incomplete".to_owned());
        remediation.push("complete a fresh workspace scan and relink the graph".to_owned());
    }
    if !stale.is_empty() {
        gaps.push("one or more relevant repositories are stale".to_owned());
        remediation.push("rescan stale repositories at their current revisions".to_owned());
    }
    if !partial.is_empty() {
        gaps.push("one or more relevant repositories have partial coverage".to_owned());
        remediation.push("resolve extractor limitations and complete partial scans".to_owned());
    }
    if !unavailable.is_empty() {
        gaps.push("one or more relevant repositories are unavailable or corrupt".to_owned());
        remediation.push("restore unavailable repositories or valid graph snapshots".to_owned());
    }
    if !missing.is_empty() {
        gaps.push("freshness is missing or unknown for relevant repositories".to_owned());
        remediation.push("record current freshness for every relevant repository".to_owned());
    }
    if possible_edges > 0 {
        gaps.push(
            "candidate, inferred, ambiguous, or low-confidence relationships were used".to_owned(),
        );
        remediation.push("corroborate candidate relationships with direct evidence".to_owned());
    }
    if unknown_edges > 0 {
        gaps.push("stale or incomplete relationships were used".to_owned());
        remediation
            .push("refresh or complete evidence for coverage-unknown relationships".to_owned());
    }
    let impacted_ids = items
        .iter()
        .map(|item| &item.node.id)
        .chain(std::iter::once(&target.id))
        .collect::<BTreeSet<_>>();
    let unknown_compatibility = context.compatibility.iter().filter(|input| {
        impacted_ids.contains(&input.contract_node_id)
            && input.status == ImpactCompatibilityStatus::Unknown
    });
    let mut compatibility_unknown = false;
    for input in unknown_compatibility {
        compatibility_unknown = true;
        gaps.push(format!(
            "compatibility is unknown for contract node `{}`",
            input.contract_node_id.as_str()
        ));
        remediation.extend(input.recommended_validations.iter().cloned());
    }
    for local in &context.local_enrichment {
        if local.status != LocalEnrichmentStatus::Available || local.truncated {
            gaps.push(format!(
                "local enrichment for repository `{}` is {:?}{}",
                local.repo_id.as_str(),
                local.status,
                if local.truncated {
                    " and truncated"
                } else {
                    ""
                }
            ));
            remediation.extend(local.degradations.iter().cloned());
        }
    }
    if truncation.is_some() {
        gaps.push("configured traversal bounds truncated impact analysis".to_owned());
        remediation.push("increase impact bounds or narrow the target scope".to_owned());
    }
    gaps = sorted_unique(gaps);
    remediation = sorted_unique(remediation);
    CoverageSummary {
        sufficient_for_score: context.graph_complete
            && stale.is_empty()
            && partial.is_empty()
            && unavailable.is_empty()
            && missing.is_empty()
            && possible_edges == 0
            && unknown_edges == 0
            && !compatibility_unknown
            && truncation.is_none()
            && context
                .local_enrichment
                .iter()
                .all(|local| local.status == LocalEnrichmentStatus::Available && !local.truncated)
            && context.coverage_gaps.is_empty(),
        relevant_repositories: relevant.into_iter().collect(),
        fresh_repositories: fresh,
        stale_repositories: stale,
        partial_repositories: partial,
        unavailable_repositories: unavailable,
        missing_repositories: missing,
        possible_edges,
        unknown_edges,
        gaps,
        remediation,
        total_items: items.len(),
    }
}

#[expect(
    clippy::too_many_arguments,
    clippy::too_many_lines,
    reason = "Risk inputs stay explicit to make every scored dimension auditable"
)]
fn assess_risk(
    target: &Node,
    items: &[ImpactItem],
    repositories: &[RepositoryImpact],
    services: &[ServiceImpact],
    contracts: &[ContractImpact],
    communities: &[CommunityImpact],
    tests: &[TestRecommendation],
    context: &ImpactContext,
    coverage: &CoverageSummary,
    truncation: Option<&TruncationInfo>,
) -> (RiskLevel, Option<f32>, Vec<RiskFactor>) {
    let impacted_ids = items
        .iter()
        .map(|item| &item.node.id)
        .chain(std::iter::once(&target.id))
        .collect::<BTreeSet<_>>();
    let direct_count = items
        .iter()
        .filter(|item| item.classification == ImpactClassification::DirectlyDependent)
        .count();
    let transitive_count = items
        .iter()
        .filter(|item| item.classification == ImpactClassification::TransitivelyAffected)
        .count();
    let mut factors = Vec::new();
    if direct_count > 0 {
        push_factor(
            &mut factors,
            "direct_consumers",
            usize_to_f32(direct_count).mul_add(4.0, 0.0).min(24.0),
            format!("{direct_count} confirmed direct dependents"),
            direct_evidence(items),
        );
    }
    if transitive_count > 0 {
        push_factor(
            &mut factors,
            "transitive_fanout",
            usize_to_f32(transitive_count).mul_add(1.5, 0.0).min(15.0),
            format!("{transitive_count} confirmed transitive impacts"),
            Vec::new(),
        );
    }
    let mut repository_ids = repositories
        .iter()
        .map(|impact| impact.repo_id.clone())
        .collect::<BTreeSet<_>>();
    repository_ids.extend(target.repo_id.iter().cloned());
    if repository_ids.len() > 1 {
        push_factor(
            &mut factors,
            "cross_repository_count",
            usize_to_f32(repository_ids.len().saturating_sub(1))
                .mul_add(4.0, 0.0)
                .min(16.0),
            format!("impact spans {} repositories", repository_ids.len()),
            repository_ids
                .iter()
                .map(|repo_id| repo_id.as_str().to_owned())
                .collect(),
        );
    }
    if !services.is_empty() {
        push_factor(
            &mut factors,
            "service_impact",
            usize_to_f32(services.len()).mul_add(2.0, 0.0).min(10.0),
            format!("impact reaches {} services", services.len()),
            services
                .iter()
                .map(|impact| impact.service.stable_key.clone())
                .collect(),
        );
    }
    let public_contracts = contracts.iter().filter(|contract| contract.public).count()
        + usize::from(context.public_contracts.contains(&target.id));
    if public_contracts > 0 {
        push_factor(
            &mut factors,
            "public_contract",
            12.0,
            format!("{public_contracts} explicitly public contracts are involved"),
            contracts
                .iter()
                .filter(|contract| contract.public)
                .map(|contract| contract.contract.stable_key.clone())
                .collect(),
        );
    }
    add_compatibility_factors(&mut factors, &impacted_ids, context);
    if let Some(centrality) = context
        .centrality
        .get(&target.id)
        .filter(|value| **value >= 0.75)
    {
        push_factor(
            &mut factors,
            "centrality",
            *centrality * 12.0,
            format!("target centrality is {centrality:.3}"),
            vec![target.id.as_str().to_owned()],
        );
    }
    if !communities.is_empty() {
        let cross_edges = communities
            .iter()
            .filter(|community| community.coupling > 0.0)
            .count();
        if cross_edges > 0 {
            push_factor(
                &mut factors,
                "community_process_fanout",
                usize_to_f32(cross_edges).mul_add(3.0, 0.0).min(9.0),
                format!("{cross_edges} affected communities cross structural boundaries"),
                communities
                    .iter()
                    .map(|community| community.community_id.as_str().to_owned())
                    .collect(),
            );
        }
    }
    add_criticality_factors(&mut factors, &impacted_ids, context);
    if tests.is_empty() && !items.is_empty() {
        push_factor(
            &mut factors,
            "missing_tests",
            10.0,
            "no linked or locally supplied affected tests were found".to_owned(),
            Vec::new(),
        );
    }
    let owners = owner_count(&impacted_ids, context);
    if owners == 0 && !items.is_empty() {
        push_factor(
            &mut factors,
            "missing_owners",
            8.0,
            "no Owner node is linked by OwnedBy to an impacted node".to_owned(),
            Vec::new(),
        );
    }
    let environments = context
        .environments
        .iter()
        .filter(|assignment| impacted_ids.contains(&assignment.node_id))
        .map(|assignment| assignment.environment.as_str())
        .collect::<BTreeSet<_>>();
    if environments.len() > 1 {
        push_factor(
            &mut factors,
            "cross_environment",
            10.0,
            format!("impact spans {} explicit environments", environments.len()),
            environments.into_iter().map(str::to_owned).collect(),
        );
    }
    if !coverage.sufficient_for_score {
        push_factor(
            &mut factors,
            "coverage_unknown",
            0.0,
            "coverage is insufficient for a numeric risk conclusion".to_owned(),
            coverage.gaps.clone(),
        );
    }
    if let Some(info) = truncation {
        push_factor(
            &mut factors,
            "truncated",
            0.0,
            info.explanation.clone(),
            vec![format!("{}={}", info.bound, info.limit)],
        );
    }
    factors.sort_by(|left, right| {
        right
            .weight
            .partial_cmp(&left.weight)
            .unwrap_or(Ordering::Equal)
            .then_with(|| left.code.cmp(&right.code))
            .then_with(|| left.explanation.cmp(&right.explanation))
    });
    if !coverage.sufficient_for_score {
        return (RiskLevel::Unknown, None, factors);
    }
    let score = factors
        .iter()
        .map(|factor| factor.weight)
        .sum::<f32>()
        .clamp(1.0, 100.0);
    let explicit_critical = factors.iter().any(|factor| {
        matches!(
            factor.code.as_str(),
            "critical_tag" | "security_tag" | "payment_tag" | "data_boundary_tag"
        ) && !factor.evidence.is_empty()
    });
    let level = if score >= 85.0 && explicit_critical {
        RiskLevel::Critical
    } else if score >= 50.0 {
        RiskLevel::High
    } else if score >= 25.0 {
        RiskLevel::Medium
    } else {
        RiskLevel::Low
    };
    (level, Some(score), factors)
}

fn add_compatibility_factors(
    factors: &mut Vec<RiskFactor>,
    impacted_ids: &BTreeSet<&NodeId>,
    context: &ImpactContext,
) {
    for input in &context.compatibility {
        if !impacted_ids.contains(&input.contract_node_id) {
            continue;
        }
        match input.status {
            ImpactCompatibilityStatus::Breaking => push_factor(
                factors,
                "breaking_compatibility",
                30.0,
                "a compatibility engine reported a breaking contract change".to_owned(),
                input.evidence.clone(),
            ),
            ImpactCompatibilityStatus::PotentiallyBreaking => push_factor(
                factors,
                "potentially_breaking_compatibility",
                18.0,
                "a compatibility engine reported a potentially breaking change".to_owned(),
                input.evidence.clone(),
            ),
            ImpactCompatibilityStatus::Compatible => {}
            ImpactCompatibilityStatus::Unknown => push_factor(
                factors,
                "compatibility_unknown",
                0.0,
                "compatibility coverage is unknown".to_owned(),
                input
                    .evidence
                    .iter()
                    .chain(input.recommended_validations.iter())
                    .cloned()
                    .collect(),
            ),
        }
    }
}

fn add_criticality_factors(
    factors: &mut Vec<RiskFactor>,
    impacted_ids: &BTreeSet<&NodeId>,
    context: &ImpactContext,
) {
    for assignment in &context.criticality {
        if !impacted_ids.contains(&assignment.node_id) {
            continue;
        }
        let (code, weight) = match assignment.tag {
            CriticalityTag::Critical => ("critical_tag", 55.0),
            CriticalityTag::Authentication => ("authentication_tag", 35.0),
            CriticalityTag::Security => ("security_tag", 50.0),
            CriticalityTag::Payment => ("payment_tag", 50.0),
            CriticalityTag::DataBoundary => ("data_boundary_tag", 45.0),
        };
        push_factor(
            factors,
            code,
            weight,
            format!(
                "explicit {:?} tag applies to impacted node `{}`",
                assignment.tag,
                assignment.node_id.as_str()
            ),
            assignment.evidence.clone(),
        );
    }
}

fn owner_count(impacted_ids: &BTreeSet<&NodeId>, context: &ImpactContext) -> usize {
    context
        .edges
        .iter()
        .filter(|edge| edge.kind == EdgeKind::OwnedBy && impacted_ids.contains(&edge.source))
        .map(|edge| &edge.target)
        .collect::<BTreeSet<_>>()
        .len()
}

fn direct_evidence(items: &[ImpactItem]) -> Vec<String> {
    let mut evidence = items
        .iter()
        .filter(|item| item.classification == ImpactClassification::DirectlyDependent)
        .flat_map(|item| item.evidence.iter().map(|id| id.as_str().to_owned()))
        .collect::<Vec<_>>();
    evidence.sort();
    evidence.dedup();
    evidence
}

fn push_factor(
    factors: &mut Vec<RiskFactor>,
    code: &str,
    weight: f32,
    explanation: String,
    evidence: Vec<String>,
) {
    factors.push(RiskFactor {
        code: code.to_owned(),
        weight,
        explanation,
        evidence: sorted_unique(evidence),
    });
}

fn usize_to_f32(value: usize) -> f32 {
    u16::try_from(value).map_or(f32::from(u16::MAX), f32::from)
}

fn split_classifications(
    items: Vec<ImpactItem>,
) -> (
    Vec<ImpactItem>,
    Vec<ImpactItem>,
    Vec<ImpactItem>,
    Vec<ImpactItem>,
) {
    let mut direct = Vec::new();
    let mut transitive = Vec::new();
    let mut possible = Vec::new();
    let mut unknown = Vec::new();
    for item in items {
        match item.classification {
            ImpactClassification::DirectlyDependent => direct.push(item),
            ImpactClassification::TransitivelyAffected => transitive.push(item),
            ImpactClassification::PossiblyAffected => possible.push(item),
            ImpactClassification::UnknownDueToCoverage => unknown.push(item),
        }
    }
    (direct, transitive, possible, unknown)
}

fn sorted_unique(mut values: Vec<String>) -> Vec<String> {
    values.sort();
    values.dedup();
    values
}

#[cfg(test)]
mod tests {
    use code_system_graph_model::{CheckoutId, Community, CommunityConfig, CommunityMetrics};

    use super::*;

    fn node(id: &str, kind: NodeKind, repo: &str) -> Node {
        Node {
            id: NodeId::new(id),
            kind,
            repo_id: Some(RepoId::new(repo)),
            stable_key: format!("{repo}:{id}"),
            label: id.to_owned(),
        }
    }

    fn edge(id: &str, source: &str, target: &str) -> Edge {
        Edge {
            id: EdgeId::new(id),
            source: NodeId::new(source),
            target: NodeId::new(target),
            kind: EdgeKind::Consumes,
            confidence: 1.0,
            status: EpistemicStatus::Confirmed,
            evidence: vec![EvidenceId::new(format!("e-{id}"))],
        }
    }

    fn freshness(repo: &str, state: RepoFreshnessState) -> RepoFreshness {
        RepoFreshness {
            repo_id: RepoId::new(repo),
            checkout_id: CheckoutId::new(format!("checkout-{repo}")),
            head_commit: Some("abc".to_owned()),
            manifest_hash: "manifest".to_owned(),
            state,
            reason: None,
        }
    }

    fn context(nodes: Vec<Node>, edges: Vec<Edge>) -> ImpactContext {
        let repos = nodes
            .iter()
            .filter_map(|item| item.repo_id.clone())
            .collect::<BTreeSet<_>>();
        ImpactContext {
            nodes,
            edges,
            communities: None,
            freshness: repos
                .iter()
                .map(|repo| freshness(repo.as_str(), RepoFreshnessState::Fresh))
                .collect(),
            compatibility: Vec::new(),
            local_enrichment: Vec::new(),
            public_contracts: Vec::new(),
            criticality: Vec::new(),
            centrality: BTreeMap::new(),
            service_memberships: BTreeMap::new(),
            environments: Vec::new(),
            recommended_commands: Vec::new(),
            graph_complete: true,
            coverage_gaps: Vec::new(),
        }
    }

    fn request(target: &str, direction: ImpactDirection) -> ImpactRequest {
        ImpactRequest {
            target: ImpactTarget::NodeId(NodeId::new(target)),
            direction,
            options: ImpactOptions::default(),
        }
    }

    fn analyze(context: &ImpactContext, direction: ImpactDirection) -> ImpactReport {
        analyze_impact(&request("target", direction), context).expect("analysis should succeed")
    }

    #[test]
    fn breaking_direct_impact_should_raise_high_risk() {
        let mut context = context(
            vec![
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::HttpOperation, "b"),
            ],
            vec![edge("direct", "consumer", "target")],
        );
        context.compatibility.push(CompatibilityInput {
            contract_node_id: NodeId::new("target"),
            status: ImpactCompatibilityStatus::Breaking,
            evidence: vec!["http.required_parameter_added".to_owned()],
            recommended_validations: Vec::new(),
        });
        context.public_contracts.push(NodeId::new("target"));

        let report = analyze(&context, ImpactDirection::Upstream);

        assert_eq!(report.risk, RiskLevel::High);
    }

    #[test]
    fn breaking_transitive_path_should_remain_confirmed() {
        let context = context(
            vec![
                node("far", NodeKind::Service, "a"),
                node("near", NodeKind::Service, "b"),
                node("target", NodeKind::HttpOperation, "c"),
            ],
            vec![edge("one", "near", "target"), edge("two", "far", "near")],
        );

        let report = analyze(&context, ImpactDirection::Upstream);

        assert_eq!(report.transitive_consumers[0].node.id.as_str(), "far");
    }

    #[test]
    fn stale_freshness_should_prevent_false_safe_score() {
        let mut context = context(
            vec![
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::HttpOperation, "b"),
            ],
            vec![edge("direct", "consumer", "target")],
        );
        context.freshness[0].state = RepoFreshnessState::WorkingTreeChanged;

        let report = analyze(&context, ImpactDirection::Upstream);

        assert_eq!((report.risk, report.risk_score), (RiskLevel::Unknown, None));
    }

    #[test]
    fn low_confidence_should_be_unknown_risk_not_low_impact() {
        let mut candidate = edge("candidate", "consumer", "target");
        candidate.confidence = 0.2;
        let context = context(
            vec![
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::HttpOperation, "b"),
            ],
            vec![candidate],
        );

        let report = analyze(&context, ImpactDirection::Upstream);

        assert_eq!(
            (report.risk, report.possibly_affected[0].classification),
            (RiskLevel::Unknown, ImpactClassification::PossiblyAffected)
        );
    }

    #[test]
    fn depth_truncation_should_force_unknown() {
        let context = context(
            vec![
                node("three", NodeKind::Service, "a"),
                node("two", NodeKind::Service, "b"),
                node("one", NodeKind::Service, "c"),
                node("target", NodeKind::HttpOperation, "d"),
            ],
            vec![
                edge("one", "one", "target"),
                edge("two", "two", "one"),
                edge("three", "three", "two"),
            ],
        );
        let mut request = request("target", ImpactDirection::Upstream);
        request.options.max_depth = 2;

        let report = analyze_impact(&request, &context).expect("analysis should succeed");

        assert_eq!(report.risk, RiskLevel::Unknown);
    }

    #[test]
    fn direction_should_select_incoming_or_outgoing_edges() {
        let context = context(
            vec![
                node("upstream", NodeKind::Service, "a"),
                node("target", NodeKind::HttpOperation, "b"),
                node("downstream", NodeKind::Service, "c"),
            ],
            vec![
                edge("incoming", "upstream", "target"),
                edge("outgoing", "target", "downstream"),
            ],
        );

        let report = analyze(&context, ImpactDirection::Downstream);

        assert_eq!(report.direct_consumers[0].node.id.as_str(), "downstream");
    }

    #[test]
    fn both_direction_should_include_both_sides() {
        let context = context(
            vec![
                node("upstream", NodeKind::Service, "a"),
                node("target", NodeKind::HttpOperation, "b"),
                node("downstream", NodeKind::Service, "c"),
            ],
            vec![
                edge("incoming", "upstream", "target"),
                edge("outgoing", "target", "downstream"),
            ],
        );

        let report = analyze(&context, ImpactDirection::Both);

        assert_eq!(report.coverage.total_items, 2);
    }

    #[test]
    fn cycles_should_terminate_without_repeating_target() {
        let context = context(
            vec![
                node("a", NodeKind::Service, "a"),
                node("target", NodeKind::Service, "b"),
            ],
            vec![edge("one", "target", "a"), edge("two", "a", "target")],
        );

        let report = analyze(&context, ImpactDirection::Downstream);

        assert_eq!(report.coverage.total_items, 1);
    }

    #[test]
    fn pagination_should_use_stable_combined_order() {
        let context = context(
            vec![
                node("a", NodeKind::Service, "a"),
                node("b", NodeKind::Service, "b"),
                node("target", NodeKind::Service, "t"),
            ],
            vec![edge("a", "a", "target"), edge("b", "b", "target")],
        );
        let mut request = request("target", ImpactDirection::Upstream);
        request.options.offset = 1;
        request.options.limit = 1;

        let report = analyze_impact(&request, &context).expect("analysis should succeed");

        assert_eq!(report.direct_consumers[0].node.id.as_str(), "b");
    }

    #[test]
    fn summary_only_should_omit_items_and_retain_counts() {
        let context = context(
            vec![
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::Service, "b"),
            ],
            vec![edge("direct", "consumer", "target")],
        );
        let mut request = request("target", ImpactDirection::Upstream);
        request.options.summary_only = true;

        let report = analyze_impact(&request, &context).expect("analysis should succeed");

        assert_eq!(
            (report.direct_consumers.len(), report.coverage.total_items),
            (0, 1)
        );
    }

    #[test]
    fn graph_tests_and_owners_should_be_ranked() {
        let mut validates = edge("validates", "test", "consumer");
        validates.kind = EdgeKind::Validates;
        let mut owned = edge("owned", "test", "owner");
        owned.kind = EdgeKind::OwnedBy;
        let context = context(
            vec![
                node("test", NodeKind::TestCase, "a"),
                node("owner", NodeKind::Owner, "a"),
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::HttpOperation, "b"),
            ],
            vec![edge("direct", "consumer", "target"), validates, owned],
        );

        let report = analyze(&context, ImpactDirection::Upstream);

        assert_eq!(
            report.test_recommendations[0].owners[0].id.as_str(),
            "owner"
        );
    }

    #[test]
    fn explicit_commands_should_only_be_returned_not_executed() {
        let mut validates = edge("validates", "test", "consumer");
        validates.kind = EdgeKind::Validates;
        let mut context = context(
            vec![
                node("test", NodeKind::TestCase, "a"),
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::Service, "b"),
            ],
            vec![edge("direct", "consumer", "target"), validates],
        );
        context.recommended_commands.push(RecommendedCommand {
            repo_id: RepoId::new("a"),
            command: "cargo test -p consumer".to_owned(),
            description: "consumer tests".to_owned(),
        });

        let report = analyze(&context, ImpactDirection::Upstream);

        assert_eq!(
            report.test_recommendations[0].recommended_commands,
            vec!["cargo test -p consumer"]
        );
    }

    #[test]
    fn affected_community_should_include_coupling() {
        let mut context = context(
            vec![
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::Service, "b"),
            ],
            vec![edge("direct", "consumer", "target")],
        );
        context.communities = Some(CommunitySnapshot {
            snapshot_id: "snapshot".to_owned(),
            engine_version: "1.0.0".to_owned(),
            config: CommunityConfig {
                algorithm: code_system_graph_model::CommunityAlgorithm::ConnectedComponents,
                scope: code_system_graph_model::CommunityScope::Federated,
                seed: 0,
                resolution: 1.0,
                minimum_confidence: 0.8,
                edge_weights: Vec::new(),
                max_iterations: 1,
            },
            communities: vec![Community {
                id: CommunityId::new("community"),
                label: "orders".to_owned(),
                members: vec![NodeId::new("consumer")],
                central_nodes: Vec::new(),
                repositories: vec![RepoId::new("a")],
                services: vec![NodeId::new("consumer")],
                inbound_contracts: Vec::new(),
                outbound_contracts: Vec::new(),
                metrics: CommunityMetrics {
                    size: 1,
                    density: 0.0,
                    cohesion: 0.0,
                    coupling: 2.0,
                    cross_community_edges: 1,
                },
                label_evidence: Vec::new(),
                limitations: Vec::new(),
            }],
        });

        let report = analyze(&context, ImpactDirection::Upstream);

        assert!((report.affected_communities[0].coupling - 2.0).abs() < f64::EPSILON);
    }

    #[test]
    fn local_enrichment_degradation_should_be_visible_and_unknown() {
        let mut context = context(
            vec![
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::Service, "b"),
            ],
            vec![edge("direct", "consumer", "target")],
        );
        context.local_enrichment.push(LocalEnrichmentInput {
            repo_id: RepoId::new("a"),
            anchor: "consumer".to_owned(),
            status: LocalEnrichmentStatus::Stale,
            affected: Vec::new(),
            affected_tests: Vec::new(),
            truncated: false,
            degradations: vec!["reindex repository".to_owned()],
        });

        let report = analyze(&context, ImpactDirection::Upstream);

        assert_eq!(
            (report.risk, report.local_impact_summaries[0].status),
            (RiskLevel::Unknown, LocalEnrichmentStatus::Stale)
        );
    }

    #[test]
    fn explicit_security_tag_with_evidence_can_produce_critical() {
        let mut context = context(
            vec![
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::HttpOperation, "b"),
            ],
            vec![edge("direct", "consumer", "target")],
        );
        context.criticality.push(CriticalityAssignment {
            node_id: NodeId::new("target"),
            tag: CriticalityTag::Security,
            evidence: vec!["policy:security-boundary".to_owned()],
        });
        context.public_contracts.push(NodeId::new("target"));
        context.compatibility.push(CompatibilityInput {
            contract_node_id: NodeId::new("target"),
            status: ImpactCompatibilityStatus::Breaking,
            evidence: vec!["breaking".to_owned()],
            recommended_validations: Vec::new(),
        });

        let report = analyze(&context, ImpactDirection::Upstream);

        assert_eq!(report.risk, RiskLevel::Critical);
    }

    #[test]
    fn labels_should_not_infer_critical_tags() {
        let context = context(
            vec![
                node("payment-security", NodeKind::Service, "a"),
                node("target", NodeKind::Service, "b"),
            ],
            vec![edge("direct", "payment-security", "target")],
        );

        let report = analyze(&context, ImpactDirection::Upstream);

        assert!(
            !report
                .reasons
                .iter()
                .any(|factor| factor.code.ends_with("_tag"))
        );
    }

    #[test]
    fn identical_inputs_should_produce_identical_reports() {
        let context = context(
            vec![
                node("b", NodeKind::Service, "b"),
                node("target", NodeKind::Service, "t"),
                node("a", NodeKind::Service, "a"),
            ],
            vec![edge("b", "b", "target"), edge("a", "a", "target")],
        );

        let first = analyze(&context, ImpactDirection::Upstream);
        let second = analyze(&context, ImpactDirection::Upstream);

        assert_eq!(first, second);
    }

    #[test]
    fn invalid_bounds_should_be_rejected() {
        let context = context(vec![node("target", NodeKind::Service, "a")], Vec::new());
        let mut request = request("target", ImpactDirection::Both);
        request.options.max_depth = 0;

        let error = analyze_impact(&request, &context).expect_err("zero depth must be rejected");

        assert_eq!(error, ImpactError::InvalidBounds);
    }

    #[test]
    fn invalid_edge_confidence_should_be_rejected() {
        let mut invalid = edge("invalid", "consumer", "target");
        invalid.confidence = f32::NAN;
        let context = context(
            vec![
                node("consumer", NodeKind::Service, "a"),
                node("target", NodeKind::Service, "b"),
            ],
            vec![invalid],
        );

        let error = analyze_impact(&request("target", ImpactDirection::Upstream), &context)
            .expect_err("NaN confidence must be rejected");

        assert_eq!(
            error,
            ImpactError::InvalidEdgeConfidence("invalid".to_owned())
        );
    }

    #[test]
    fn fresh_complete_empty_impact_should_have_positive_low_score() {
        let context = context(vec![node("target", NodeKind::Service, "a")], Vec::new());

        let report = analyze(&context, ImpactDirection::Both);

        assert_eq!(
            (report.risk, report.risk_score),
            (RiskLevel::Low, Some(1.0))
        );
    }
}