sbom-tools 0.1.22

Semantic SBOM diff and analysis tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
//! Integration tests for sbom-tools
//!
//! These tests verify end-to-end functionality of the SBOM parsing,
//! diff engine, and report generation.

use sbom_tools::{
    diff::DiffEngine,
    matching::FuzzyMatchConfig,
    parsers::{parse_sbom, parse_sbom_str},
};
use std::path::Path;

// ============================================================================
// Test Fixtures
// ============================================================================

const FIXTURES_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures");

fn fixture_path(name: &str) -> std::path::PathBuf {
    Path::new(FIXTURES_DIR).join(name)
}

// ============================================================================
// Parser Tests
// ============================================================================

mod parser_tests {
    use super::*;

    #[test]
    fn test_parse_cyclonedx_minimal() {
        let path = fixture_path("cyclonedx/minimal.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX SBOM");

        // 3 components: metadata.component (test-app) + lodash + express
        assert_eq!(sbom.component_count(), 3);
        assert!(sbom.components.values().any(|c| c.name == "test-app"));
        assert!(sbom.components.values().any(|c| c.name == "lodash"));
        assert!(sbom.components.values().any(|c| c.name == "express"));
        // Primary component should be set from metadata.component
        assert!(sbom.primary_component_id.is_some());
    }

    #[test]
    fn test_parse_spdx_minimal() {
        let path = fixture_path("spdx/minimal.spdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX SBOM");

        assert_eq!(sbom.component_count(), 2);
        assert!(sbom.components.values().any(|c| c.name == "lodash"));
        assert!(sbom.components.values().any(|c| c.name == "express"));
    }

    #[test]
    fn test_parse_spdx_rdf_xml() {
        let path = fixture_path("spdx/minimal.spdx.rdf.xml");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX RDF/XML SBOM");

        assert_eq!(sbom.component_count(), 2, "Should have 2 packages");
        assert!(
            sbom.components.values().any(|c| c.name == "lodash"),
            "Should have lodash"
        );
        assert!(
            sbom.components.values().any(|c| c.name == "express"),
            "Should have express"
        );

        // Verify versions are parsed
        let lodash = sbom
            .components
            .values()
            .find(|c| c.name == "lodash")
            .unwrap();
        assert_eq!(lodash.version.as_deref(), Some("4.17.21"));

        let express = sbom
            .components
            .values()
            .find(|c| c.name == "express")
            .unwrap();
        assert_eq!(express.version.as_deref(), Some("4.18.2"));
    }

    #[test]
    fn test_parse_spdx_rdf_xml_from_string() {
        let content = r#"<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:spdx="http://spdx.org/rdf/terms#">
  <spdx:SpdxDocument rdf:about="https://example.com/test">
    <spdx:specVersion>SPDX-2.3</spdx:specVersion>
    <spdx:dataLicense rdf:resource="http://spdx.org/licenses/CC0-1.0"/>
    <spdx:name>test-doc</spdx:name>
    <spdx:spdxId>SPDXRef-DOCUMENT</spdx:spdxId>
    <spdx:creationInfo>
      <spdx:CreationInfo>
        <spdx:created>2026-01-01T00:00:00Z</spdx:created>
        <spdx:creator>Tool: test</spdx:creator>
      </spdx:CreationInfo>
    </spdx:creationInfo>
    <spdx:Package rdf:about="https://example.com/test#SPDXRef-Package-test">
      <spdx:name>test-package</spdx:name>
      <spdx:versionInfo>1.0.0</spdx:versionInfo>
      <spdx:downloadLocation>NOASSERTION</spdx:downloadLocation>
    </spdx:Package>
  </spdx:SpdxDocument>
</rdf:RDF>"#;

        let sbom = parse_sbom_str(content).expect("Failed to parse SPDX RDF/XML from string");
        assert_eq!(sbom.component_count(), 1);
        assert!(sbom.components.values().any(|c| c.name == "test-package"));
    }

    #[test]
    fn test_parse_cyclonedx_with_vulnerabilities() {
        let path = fixture_path("cyclonedx/with-vulnerabilities.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX SBOM with vulns");

        assert_eq!(sbom.component_count(), 2);

        // Check vulnerabilities are parsed
        let vulns = sbom.all_vulnerabilities();
        assert!(!vulns.is_empty(), "Should have vulnerabilities");

        // Check for specific vulnerabilities
        let vuln_ids: Vec<_> = vulns.iter().map(|(_, v)| v.id.as_str()).collect();
        assert!(
            vuln_ids.contains(&"CVE-2021-44228"),
            "Should contain Log4Shell"
        );
        assert!(
            vuln_ids.contains(&"CVE-2021-23337"),
            "Should contain lodash vuln"
        );
    }

    #[test]
    fn test_parse_cyclonedx_from_string() {
        let content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {
                    "type": "library",
                    "bom-ref": "test@1.0.0",
                    "name": "test",
                    "version": "1.0.0"
                }
            ]
        }"#;

        let sbom = parse_sbom_str(content).expect("Failed to parse CycloneDX from string");
        assert_eq!(sbom.component_count(), 1);
    }

    #[test]
    fn test_parse_spdx_from_string() {
        let content = r#"{
            "spdxVersion": "SPDX-2.3",
            "SPDXID": "SPDXRef-DOCUMENT",
            "name": "test",
            "dataLicense": "CC0-1.0",
            "documentNamespace": "https://example.com/test",
            "creationInfo": {
                "created": "2026-01-01T00:00:00Z",
                "creators": ["Tool: test"]
            },
            "packages": [
                {
                    "SPDXID": "SPDXRef-Package-test",
                    "name": "test-package",
                    "versionInfo": "1.0.0",
                    "downloadLocation": "NOASSERTION"
                }
            ]
        }"#;

        let sbom = parse_sbom_str(content).expect("Failed to parse SPDX from string");
        assert_eq!(sbom.component_count(), 1);
    }

    #[test]
    fn test_format_detection() {
        // CycloneDX detection
        let cdx = r#"{"bomFormat": "CycloneDX", "specVersion": "1.5"}"#;
        assert!(parse_sbom_str(cdx).is_ok() || parse_sbom_str(cdx).is_err()); // Should attempt CycloneDX parsing

        // SPDX detection
        let spdx = r#"{"spdxVersion": "SPDX-2.3", "SPDXID": "SPDXRef-DOCUMENT"}"#;
        assert!(parse_sbom_str(spdx).is_ok() || parse_sbom_str(spdx).is_err()); // Should attempt SPDX parsing
    }

    #[test]
    fn test_unknown_format_error() {
        let unknown = r#"{"unknown": "format"}"#;
        let result = parse_sbom_str(unknown);
        assert!(result.is_err(), "Should fail for unknown format");
    }

    #[test]
    fn test_parse_cyclonedx_1_7() {
        let path = fixture_path("cyclonedx/minimal-1.7.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX 1.7 SBOM");

        // 4 components: metadata.component (acme-app) + lib-a + lib-b + crypto-asset-1
        assert_eq!(sbom.component_count(), 4);
        assert!(sbom.components.values().any(|c| c.name == "acme-app"));
        assert!(sbom.components.values().any(|c| c.name == "lib-a"));
        assert!(sbom.components.values().any(|c| c.name == "lib-b"));
        assert!(sbom.components.values().any(|c| c.name == "AES-256-GCM"));

        // Verify spec version
        assert_eq!(sbom.document.spec_version, "1.7");
        assert_eq!(sbom.document.format_version, "1.7");

        // Primary component should be set
        assert!(sbom.primary_component_id.is_some());

        // Verify distribution classification (TLP)
        assert_eq!(
            sbom.document.distribution_classification.as_deref(),
            Some("GREEN")
        );

        // Verify citations count
        assert_eq!(sbom.document.citations_count, 2);

        // Verify citations stored in format extensions
        assert!(sbom.extensions.cyclonedx.is_some());
        let ext = sbom.extensions.cyclonedx.as_ref().unwrap();
        assert!(ext.get("citations").is_some());

        // Verify completeness declaration
        assert_eq!(
            sbom.document.completeness_declaration,
            sbom_tools::model::CompletenessDeclaration::Complete
        );
    }

    #[test]
    fn test_cyclonedx_1_7_is_external() {
        let path = fixture_path("cyclonedx/minimal-1.7.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX 1.7 SBOM");

        // lib-b has isExternal=true
        let lib_b = sbom
            .components
            .values()
            .find(|c| c.name == "lib-b")
            .expect("lib-b not found");
        assert!(lib_b.is_external);
        assert_eq!(
            lib_b.version_range.as_deref(),
            Some("vers:cargo/>=1.0.0|<3.0.0")
        );

        // lib-a does not
        let lib_a = sbom
            .components
            .values()
            .find(|c| c.name == "lib-a")
            .expect("lib-a not found");
        assert!(!lib_a.is_external);
        assert!(lib_a.version_range.is_none());
    }

    #[test]
    fn test_cyclonedx_1_7_streebog_hash() {
        let path = fixture_path("cyclonedx/minimal-1.7.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX 1.7 SBOM");

        let lib_a = sbom
            .components
            .values()
            .find(|c| c.name == "lib-a")
            .expect("lib-a not found");
        assert_eq!(lib_a.hashes.len(), 2);

        let has_sha256 = lib_a
            .hashes
            .iter()
            .any(|h| h.algorithm == sbom_tools::model::HashAlgorithm::Sha256);
        let has_streebog = lib_a
            .hashes
            .iter()
            .any(|h| h.algorithm == sbom_tools::model::HashAlgorithm::Streebog256);
        assert!(has_sha256, "Should have SHA-256 hash");
        assert!(has_streebog, "Should have Streebog-256 hash");
    }

    #[test]
    fn test_cyclonedx_1_7_cryptographic_component() {
        let path = fixture_path("cyclonedx/minimal-1.7.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX 1.7 SBOM");

        let crypto = sbom
            .components
            .values()
            .find(|c| c.name == "AES-256-GCM")
            .expect("crypto component not found");
        assert_eq!(
            crypto.component_type,
            sbom_tools::model::ComponentType::Cryptographic
        );
    }

    #[test]
    fn test_cyclonedx_1_7_mixed_licenses() {
        let path = fixture_path("cyclonedx/minimal-1.7.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX 1.7 SBOM");

        let lib_a = sbom
            .components
            .values()
            .find(|c| c.name == "lib-a")
            .expect("lib-a not found");
        // Should have both a license object (MIT) and an expression (Apache-2.0)
        assert_eq!(lib_a.licenses.declared.len(), 2);
    }

    #[test]
    fn test_cyclonedx_1_7_backward_compat_with_1_5() {
        // Ensure existing 1.5 fixtures still parse correctly
        let path_15 = fixture_path("cyclonedx/minimal.cdx.json");
        let sbom_15 = parse_sbom(&path_15).expect("Failed to parse CycloneDX 1.5 SBOM");
        assert_eq!(sbom_15.component_count(), 3);
        assert_eq!(sbom_15.document.spec_version, "1.5");

        // 1.7-specific fields should be None/default for 1.5 documents
        assert!(sbom_15.document.distribution_classification.is_none());
        assert_eq!(sbom_15.document.citations_count, 0);
        for comp in sbom_15.components.values() {
            assert!(!comp.is_external);
            assert!(comp.version_range.is_none());
        }
    }

    #[test]
    fn test_parse_cyclonedx_mlbom_fixture() {
        let path = fixture_path("cyclonedx/minimal-mlbom.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX ML BOM fixture");

        assert_eq!(sbom.component_count(), 4);

        let bert = sbom
            .components
            .values()
            .find(|c| c.name == "bert-base")
            .expect("bert-base not found");
        assert_eq!(
            bert.component_type,
            sbom_tools::model::ComponentType::MachineLearningModel
        );

        let ml_info = bert.ml_model.as_ref().expect("ML metadata missing");
        // Spec nesting: approach/architectureFamily/modelArchitecture/task live under modelParameters.
        assert_eq!(ml_info.approach.as_deref(), Some("supervised"));
        assert_eq!(ml_info.architecture_family.as_deref(), Some("transformer"));
        // architecture_name is read from the spec `modelArchitecture` string.
        assert_eq!(ml_info.architecture_name.as_deref(), Some("bert"));
        assert_eq!(ml_info.task.as_deref(), Some("nlp"));
        // `quantization` has no home in the CycloneDX 1.6 modelCard schema → never populated.
        assert_eq!(ml_info.quantization, None);
        // Limitations come from considerations.technicalLimitations (array).
        assert_eq!(
            ml_info.limitations.as_deref(),
            Some("Optimized for English text; may not generalize to non-English languages.")
        );
        // Energy from considerations.environmentalConsiderations[].activityEnergyCost.value (kWh).
        assert_eq!(ml_info.energy_kwh_training, Some(1500.0));
        // datasets: one spec `{ref}` data-reference and one inline componentData.
        assert_eq!(ml_info.training_datasets.len(), 2);
        assert_eq!(
            ml_info.training_datasets[0].reference.as_deref(),
            Some("data-wikipedia")
        );
        assert_eq!(ml_info.training_datasets[0].name, None);
        assert_eq!(
            ml_info.training_datasets[1].name.as_deref(),
            Some("bookscorpus-800M")
        );
        assert_eq!(
            ml_info.model_card_url.as_deref(),
            Some("https://huggingface.co/google-bert/bert-base-uncased")
        );
    }

    #[test]
    fn test_parse_cyclonedx_model_card_sums_training_energy() {
        // Spec shape: energyConsumption.activity + activityEnergyCost { value, unit }.
        // Only "training" activities are summed; other activities are excluded.
        let content = r#"{
                    "bomFormat": "CycloneDX",
                    "specVersion": "1.6",
                    "version": 1,
                    "components": [
                        {
                            "bom-ref": "ml-model-1",
                            "type": "machine-learning-model",
                            "name": "bert-base",
                            "modelCard": {
                                "modelParameters": {
                                    "approach": { "type": "supervised" },
                                    "architectureFamily": "transformer"
                                },
                                "considerations": {
                                    "environmentalConsiderations": {
                                        "energyConsumptions": [
                                            { "activity": "training", "activityEnergyCost": { "value": 100.0, "unit": "kWh" } },
                                            { "activity": "inference", "activityEnergyCost": { "value": 5.0, "unit": "kWh" } },
                                            { "activity": "training", "activityEnergyCost": { "value": 25.0, "unit": "kWh" } }
                                        ]
                                    }
                                }
                            }
                        }
                    ]
                }"#;

        let sbom = parse_sbom_str(content).expect("Failed to parse CycloneDX model card");
        let model = sbom
            .components
            .values()
            .find(|c| c.name == "bert-base")
            .expect("bert-base not found");
        let ml_info = model.ml_model.as_ref().expect("ML metadata missing");

        assert_eq!(ml_info.energy_kwh_training, Some(125.0));
    }

    #[test]
    fn test_parse_cyclonedx_dataset_fixture() {
        let path = fixture_path("cyclonedx/minimal-dataset.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX dataset fixture");

        assert_eq!(sbom.component_count(), 4);

        let training_dataset = sbom
            .components
            .values()
            .find(|c| c.name == "training-dataset-v1")
            .expect("training dataset not found");
        assert_eq!(
            training_dataset.component_type,
            sbom_tools::model::ComponentType::Data
        );

        let dataset = training_dataset
            .dataset
            .as_ref()
            .expect("dataset metadata missing");
        // componentData.type uses the spec enum ("dataset"), parsed from the `data` array.
        assert_eq!(dataset.dataset_type.as_deref(), Some("dataset"));
        // Spec key is `sensitiveData`.
        assert_eq!(dataset.sensitivity_classifications, vec!["pii", "phi"]);
        // owners + custodians + stewards are folded in, as display names (org name, else
        // contact name, else contact email), preserving owners -> custodians -> stewards order.
        assert_eq!(
            dataset.governance_owners,
            vec![
                "Data Platform Team",
                "Jane Doe",
                "ML Ops",
                "steward@example.com"
            ]
        );
    }

    #[test]
    fn test_parse_cyclonedx_data_component_array_and_tolerance() {
        // Regression: spec `component.data` is an ARRAY of componentData. A spec-compliant
        // array previously failed to parse the ENTIRE SBOM; assert it now parses end-to-end
        // and that object-form governance parties + sensitiveData are extracted.
        let content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.6",
            "version": 1,
            "components": [
                {
                    "bom-ref": "ds-spec",
                    "type": "data",
                    "name": "spec-array-dataset",
                    "data": [
                        {
                            "type": "dataset",
                            "name": "corpus",
                            "sensitiveData": ["pii"],
                            "governance": {
                                "owners": [ { "organization": { "name": "Acme AI" } } ],
                                "custodians": [ { "contact": { "name": "Custodian C" } } ]
                            }
                        }
                    ]
                }
            ]
        }"#;

        let sbom = parse_sbom_str(content).expect("spec array-form `data` must parse");
        let ds = sbom
            .components
            .values()
            .find(|c| c.name == "spec-array-dataset")
            .expect("dataset component not found");
        let info = ds.dataset.as_ref().expect("dataset metadata missing");
        assert_eq!(info.dataset_type.as_deref(), Some("dataset"));
        assert_eq!(info.sensitivity_classifications, vec!["pii"]);
        assert_eq!(info.governance_owners, vec!["Acme AI", "Custodian C"]);

        // Backward-compat: the legacy single-object `data`, the `sensitivityData` key, and
        // bare-string governance owners are still tolerated (see the fixture's legacy component).
        let legacy_path = fixture_path("cyclonedx/minimal-dataset.cdx.json");
        let legacy_sbom = parse_sbom(&legacy_path).expect("Failed to parse dataset fixture");
        let legacy = legacy_sbom
            .components
            .values()
            .find(|c| c.name == "legacy-dataset-v1")
            .expect("legacy dataset not found");
        let legacy_info = legacy
            .dataset
            .as_ref()
            .expect("legacy dataset metadata missing");
        assert_eq!(
            legacy_info.sensitivity_classifications,
            vec!["confidential"]
        );
        assert_eq!(
            legacy_info.governance_owners,
            vec!["legacy-team@example.com"]
        );
    }

    // ========================================================================
    // SPDX 3.0 Parser Tests
    // ========================================================================

    #[test]
    fn test_parse_spdx3_minimal() {
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 SBOM");

        assert_eq!(sbom.document.format, sbom_tools::model::SbomFormat::Spdx);
        assert_eq!(sbom.document.spec_version, "3.0.1");
        assert_eq!(
            sbom.document.name,
            Some("Minimal SPDX 3.0 Test Document".to_string())
        );
        // 3 packages + 1 file = 4 components
        assert_eq!(sbom.component_count(), 4);
    }

    #[test]
    fn test_spdx3_creators() {
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 SBOM");

        // Should resolve agent references to creator entries
        assert!(!sbom.document.creators.is_empty());
        let creator_names: Vec<&str> = sbom
            .document
            .creators
            .iter()
            .map(|c| c.name.as_str())
            .collect();
        assert!(
            creator_names.contains(&"sbom-generator"),
            "Expected 'sbom-generator' in creators: {creator_names:?}"
        );
    }

    #[test]
    fn test_spdx3_packages_and_files() {
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 SBOM");

        // Check that packages are converted with correct types
        let components: Vec<_> = sbom.components.values().collect();

        let my_app = components
            .iter()
            .find(|c| c.name == "my-app")
            .expect("my-app not found");
        assert_eq!(
            my_app.component_type,
            sbom_tools::model::ComponentType::Application
        );
        assert_eq!(my_app.version.as_deref(), Some("1.0.0"));
        assert!(my_app.identifiers.purl.is_some());
        assert_eq!(
            my_app.copyright.as_deref(),
            Some("Copyright 2025 Acme Corp")
        );

        let lib_core = components
            .iter()
            .find(|c| c.name == "lib-core")
            .expect("lib-core not found");
        assert_eq!(
            lib_core.component_type,
            sbom_tools::model::ComponentType::Library
        );
        assert_eq!(lib_core.version.as_deref(), Some("2.3.0"));
        // Should have 2 hashes (sha256 + sha512)
        assert_eq!(lib_core.hashes.len(), 2);

        let readme = components
            .iter()
            .find(|c| c.name == "README.md")
            .expect("README.md not found");
        assert_eq!(
            readme.component_type,
            sbom_tools::model::ComponentType::File
        );
    }

    #[test]
    fn test_spdx3_dependency_edges() {
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 SBOM");

        // Should have dependency edges: app->core, app->utils, app->readme(CONTAINS)
        assert!(
            sbom.edges.len() >= 3,
            "Expected at least 3 edges, got {}",
            sbom.edges.len()
        );
    }

    #[test]
    fn test_spdx3_license_relationships() {
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 SBOM");

        // my-app should have declared license MIT
        let my_app = sbom
            .components
            .values()
            .find(|c| c.name == "my-app")
            .expect("my-app not found");
        assert!(
            !my_app.licenses.declared.is_empty(),
            "my-app should have declared license"
        );
        assert!(
            my_app
                .licenses
                .declared
                .iter()
                .any(|l| l.expression.contains("MIT")),
            "Expected MIT license for my-app"
        );

        // lib-core should have concluded license Apache-2.0
        let lib_core = sbom
            .components
            .values()
            .find(|c| c.name == "lib-core")
            .expect("lib-core not found");
        assert!(
            lib_core.licenses.concluded.is_some(),
            "lib-core should have concluded license"
        );
        assert!(
            lib_core
                .licenses
                .concluded
                .as_ref()
                .unwrap()
                .expression
                .contains("Apache-2.0"),
            "Expected Apache-2.0 concluded license for lib-core"
        );
    }

    #[test]
    fn test_spdx3_vulnerability() {
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 SBOM");

        // lib-core should have CVE-2024-1234
        let lib_core = sbom
            .components
            .values()
            .find(|c| c.name == "lib-core")
            .expect("lib-core not found");
        assert!(
            !lib_core.vulnerabilities.is_empty(),
            "lib-core should have vulnerabilities"
        );
        assert!(
            lib_core
                .vulnerabilities
                .iter()
                .any(|v| v.id == "CVE-2024-1234"),
            "Expected CVE-2024-1234 on lib-core"
        );
    }

    #[test]
    fn test_spdx3_supplier() {
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 SBOM");

        let my_app = sbom
            .components
            .values()
            .find(|c| c.name == "my-app")
            .expect("my-app not found");
        assert!(my_app.supplier.is_some(), "my-app should have supplier");
        assert_eq!(my_app.supplier.as_ref().unwrap().name, "Acme Corp");
    }

    #[test]
    fn test_spdx3_external_identifiers() {
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 SBOM");

        let my_app = sbom
            .components
            .values()
            .find(|c| c.name == "my-app")
            .expect("my-app not found");
        // Should have CPE from externalIdentifier
        assert!(!my_app.identifiers.cpe.is_empty(), "my-app should have CPE");
        assert!(my_app.identifiers.cpe[0].starts_with("cpe:2.3:"));
        // Should have VCS external ref
        assert!(
            !my_app.external_refs.is_empty(),
            "my-app should have external refs"
        );
    }

    #[test]
    fn test_parse_spdx3_ai_package() {
        let path = fixture_path("spdx3/ai-dataset.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 AI BOM");

        let bert = sbom
            .components
            .values()
            .find(|c| c.name == "bert-base")
            .expect("bert-base not found");
        assert_eq!(
            bert.component_type,
            sbom_tools::model::ComponentType::MachineLearningModel
        );
        let ml = bert.ml_model.as_ref().expect("ML metadata missing");
        // ai_typeOfModel[0] -> architecture_family.
        assert_eq!(ml.architecture_family.as_deref(), Some("transformer"));
        assert!(
            ml.limitations
                .as_deref()
                .unwrap_or_default()
                .contains("English")
        );
        // Energy from ai_energyConsumption.ai_trainingEnergyConsumption (kWh).
        assert_eq!(ml.energy_kwh_training, Some(1500.0));
        // model_card_url approximated from the `documentation` external reference.
        assert_eq!(
            ml.model_card_url.as_deref(),
            Some("https://huggingface.co/google-bert/bert-base-uncased")
        );
    }

    #[test]
    fn test_parse_spdx3_dataset_package() {
        let path = fixture_path("spdx3/ai-dataset.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 dataset");

        let dataset = sbom
            .components
            .values()
            .find(|c| c.name == "training-dataset-v1")
            .expect("dataset not found");
        assert_eq!(
            dataset.component_type,
            sbom_tools::model::ComponentType::Data
        );
        let info = dataset.dataset.as_ref().expect("dataset metadata missing");
        // dataset_datasetType[0] (modality) -> dataset_type.
        assert_eq!(info.dataset_type.as_deref(), Some("text"));
        // hasSensitivePersonalInformation=="yes" -> "pii"; confidentialityLevel added.
        assert!(
            info.sensitivity_classifications
                .contains(&"pii".to_string())
        );
        assert!(
            info.sensitivity_classifications
                .contains(&"restricted".to_string())
        );
        // governance_owners resolved from suppliedBy agent.
        assert!(info.governance_owners.contains(&"Acme AI".to_string()));
    }

    #[test]
    fn test_spdx3_ai_readiness_scores() {
        use sbom_tools::quality::{QualityScorer, ScoringProfile};

        let path = fixture_path("spdx3/ai-dataset.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 AI BOM");
        // ai pkg + dataset pkg + software pkg (agents are not components).
        assert!(sbom.component_count() >= 3);

        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let metrics = report
            .ai_readiness_metrics
            .as_ref()
            .expect("AI readiness metrics");
        assert!(!metrics.is_not_applicable());
        assert_eq!(metrics.ml_component_count, 1);

        let passed = |id: &str| {
            metrics
                .checks
                .iter()
                .find(|c| c.id == id)
                .unwrap_or_else(|| panic!("check {id} missing"))
                .passed
        };
        // Typed checks. AI-003 (training datasets) is now derived from the
        // `trainedOn` relationship in the fixture.
        for id in ["AI-001", "AI-002", "AI-003", "AI-006", "AI-008"] {
            assert!(passed(id), "expected typed check {id} to pass");
        }
        // AI-004/005/007/009 are now satisfied via the typed MlModelInfo fields
        // (fairness/use_cases/ethical/performance_metrics), not the raw bridge.
        for id in ["AI-004", "AI-005", "AI-007", "AI-009"] {
            assert!(passed(id), "expected typed AI check {id} to pass");
        }

        // The training dataset is linked via the SPDX `trainedOn` relationship.
        let bert = sbom
            .components
            .values()
            .find(|c| c.name == "bert-base")
            .expect("bert-base not found");
        let ml = bert.ml_model.as_ref().expect("ML metadata missing");
        assert_eq!(ml.training_datasets.len(), 1);
        assert_eq!(
            ml.training_datasets[0].name.as_deref(),
            Some("training-dataset-v1")
        );
    }

    /// Regression: a fully-documented CycloneDX 1.6 ML-BOM, scored THROUGH the
    /// parser (not via hand-built extensions.raw), must pass AI-004/005/007/009.
    /// Before the typed-field extraction these checks only ever saw SPDX raw data,
    /// so a complete CycloneDX ML-BOM scored grade F regardless of content.
    #[test]
    fn test_cyclonedx_aibom_typed_ai_checks_pass() {
        use sbom_tools::quality::{QualityGrade, QualityScorer, ScoringProfile};

        let path = fixture_path("cyclonedx/aibom-complete.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse CycloneDX ML-BOM");

        // The typed fields must be populated directly by the parser.
        let model = sbom
            .components
            .values()
            .find(|c| c.name == "sentiment-classifier")
            .expect("ml model not found");
        let ml = model.ml_model.as_ref().expect("ml_model missing");
        assert!(!ml.performance_metrics.is_empty(), "AI-004 source");
        assert!(!ml.fairness.is_empty(), "AI-005 source");
        assert!(!ml.use_cases.is_empty(), "AI-007 source");
        assert!(!ml.ethical_considerations.is_empty(), "AI-009 source");

        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let metrics = report
            .ai_readiness_metrics
            .as_ref()
            .expect("AI readiness metrics");
        assert_eq!(metrics.ml_component_count, 1);
        let passed = |id: &str| {
            metrics
                .checks
                .iter()
                .find(|c| c.id == id)
                .unwrap_or_else(|| panic!("check {id} missing"))
                .passed
        };
        // The previously-broken checks now pass off typed fields.
        for id in ["AI-004", "AI-005", "AI-007", "AI-009"] {
            assert!(passed(id), "expected {id} to pass for CycloneDX ML-BOM");
        }
        // Fully documented (a weight hash for AI-010 and a security-advisory
        // external reference for AI-011) → all eleven pass, grade A.
        for check in &metrics.checks {
            assert!(check.passed, "expected {} to pass", check.id);
        }
        assert!((report.overall_score - 100.0).abs() < 0.01);
        assert_eq!(report.grade, QualityGrade::A);
    }

    /// Cross-format parity: equivalent AI content in CycloneDX and SPDX 3.0 must
    /// yield IDENTICAL AI-readiness scores and per-check pass/fail patterns.
    #[test]
    fn test_aibom_cross_format_score_parity() {
        use sbom_tools::quality::{QualityScorer, ScoringProfile};

        let cdx = parse_sbom(&fixture_path("cyclonedx/aibom-complete.cdx.json"))
            .expect("Failed to parse CycloneDX ML-BOM");
        let spdx = parse_sbom(&fixture_path("spdx3/ai-dataset.spdx3.json"))
            .expect("Failed to parse SPDX 3.0 AI BOM");

        let score = |sbom: &_| {
            let report = QualityScorer::new(ScoringProfile::AiReadiness).score(sbom);
            let metrics = report
                .ai_readiness_metrics
                .clone()
                .expect("AI readiness metrics");
            let mut pattern: Vec<(String, bool)> = metrics
                .checks
                .iter()
                .map(|c| (c.id.clone(), c.passed))
                .collect();
            pattern.sort();
            (report.overall_score, report.grade, pattern)
        };

        let (cdx_score, cdx_grade, cdx_pattern) = score(&cdx);
        let (spdx_score, spdx_grade, spdx_pattern) = score(&spdx);

        assert!(
            (cdx_score - spdx_score).abs() < 0.01,
            "scores differ: CDX={cdx_score} SPDX={spdx_score}"
        );
        assert_eq!(cdx_grade, spdx_grade, "grades differ");
        assert_eq!(
            cdx_pattern, spdx_pattern,
            "per-check pass/fail patterns differ across formats"
        );
    }

    #[test]
    fn test_spdx3_cross_format_diff_with_cyclonedx() {
        // Test that SPDX 3.0 and CycloneDX SBOMs can be diffed against each other
        let spdx3_path = fixture_path("spdx3/minimal.spdx3.json");
        let cdx_path = fixture_path("cyclonedx/minimal.cdx.json");

        let spdx3_sbom = parse_sbom(&spdx3_path).expect("Failed to parse SPDX 3.0");
        let cdx_sbom = parse_sbom(&cdx_path).expect("Failed to parse CycloneDX");

        let engine = DiffEngine::new();
        let diff = engine
            .diff(&spdx3_sbom, &cdx_sbom)
            .expect("Diff should succeed");

        // Both have components; diff should produce results without panicking
        let total = diff.components.added.len()
            + diff.components.removed.len()
            + diff.components.modified.len();
        assert!(total > 0, "Cross-format diff should have component changes");
    }

    #[test]
    fn test_spdx3_format_detection() {
        use sbom_tools::parsers::detect_format;

        let content = std::fs::read_to_string(fixture_path("spdx3/minimal.spdx3.json"))
            .expect("Failed to read fixture");
        let detected = detect_format(&content).expect("Should detect SPDX 3.0 format");
        assert_eq!(detected.format_name, "SPDX");
        assert!(
            detected.confidence >= 0.9,
            "Expected high confidence for SPDX 3.0, got {}",
            detected.confidence
        );
        assert_eq!(detected.variant, Some("JSON-LD".to_string()));
    }
}

// ============================================================================
// Diff Engine Tests
// ============================================================================

mod diff_engine_tests {
    use super::*;

    #[test]
    fn test_diff_identical_sboms() {
        let path = fixture_path("cyclonedx/minimal.cdx.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SBOM");

        let engine = DiffEngine::new();
        let result = engine.diff(&sbom, &sbom).expect("diff should succeed");

        assert!(
            !result.has_changes(),
            "Identical SBOMs should have no changes"
        );
        assert_eq!(result.summary.total_changes, 0);
    }

    #[test]
    fn test_diff_detects_added_components() {
        let old_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"}
            ]
        }"#;

        let new_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"},
                {"type": "library", "bom-ref": "b@1.0", "name": "b", "version": "1.0.0"}
            ]
        }"#;

        let old = parse_sbom_str(old_content).unwrap();
        let new = parse_sbom_str(new_content).unwrap();

        let engine = DiffEngine::new();
        let result = engine.diff(&old, &new).expect("diff should succeed");

        assert!(result.has_changes());
        assert_eq!(result.summary.components_added, 1);
        assert_eq!(result.components.added.len(), 1);
        assert_eq!(result.components.added[0].name, "b");
    }

    #[test]
    fn test_diff_detects_removed_components() {
        let old_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"},
                {"type": "library", "bom-ref": "b@1.0", "name": "b", "version": "1.0.0"}
            ]
        }"#;

        let new_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"}
            ]
        }"#;

        let old = parse_sbom_str(old_content).unwrap();
        let new = parse_sbom_str(new_content).unwrap();

        let engine = DiffEngine::new();
        let result = engine.diff(&old, &new).expect("diff should succeed");

        assert!(result.has_changes());
        assert_eq!(result.summary.components_removed, 1);
        assert_eq!(result.components.removed.len(), 1);
        assert_eq!(result.components.removed[0].name, "b");
    }

    #[test]
    fn test_diff_detects_component_license_changes() {
        let old_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0",
                 "licenses": [{"license": {"id": "MIT"}}]}
            ]
        }"#;

        let new_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0",
                 "licenses": [{"license": {"id": "Apache-2.0"}}]}
            ]
        }"#;

        let old = parse_sbom_str(old_content).unwrap();
        let new = parse_sbom_str(new_content).unwrap();

        let engine = DiffEngine::new();
        let result = engine.diff(&old, &new).expect("diff should succeed");

        assert_eq!(result.licenses.component_changes.len(), 1);
        let change = &result.licenses.component_changes[0];
        assert_eq!(change.component_name, "a");
        assert_eq!(change.old_licenses, vec!["MIT".to_string()]);
        assert_eq!(change.new_licenses, vec!["Apache-2.0".to_string()]);
        assert!(result.semantic_score < 100.0);
    }

    #[test]
    fn test_diff_detects_version_changes() {
        let old_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "pkg@1.0", "name": "pkg", "version": "1.0.0", "purl": "pkg:npm/pkg@1.0.0"}
            ]
        }"#;

        let new_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "pkg@2.0", "name": "pkg", "version": "2.0.0", "purl": "pkg:npm/pkg@2.0.0"}
            ]
        }"#;

        let old = parse_sbom_str(old_content).unwrap();
        let new = parse_sbom_str(new_content).unwrap();

        // Use permissive matching to catch version changes
        let engine = DiffEngine::new().with_fuzzy_config(FuzzyMatchConfig::permissive());
        let result = engine.diff(&old, &new).expect("diff should succeed");

        // Should detect this as a modification (same name, different version)
        assert!(result.has_changes());
    }

    #[test]
    fn test_diff_vulnerability_tracking() {
        let old_path = fixture_path("cyclonedx/minimal.cdx.json");
        let new_path = fixture_path("cyclonedx/with-vulnerabilities.cdx.json");

        let old = parse_sbom(&old_path).unwrap();
        let new = parse_sbom(&new_path).unwrap();

        let engine = DiffEngine::new();
        let result = engine.diff(&old, &new).expect("diff should succeed");

        // New SBOM has vulnerabilities that old one doesn't
        // The exact count depends on component matching
        assert!(
            !result.vulnerabilities.introduced.is_empty()
                || !result.vulnerabilities.persistent.is_empty(),
            "Should detect vulnerability changes"
        );
    }

    #[test]
    fn test_diff_severity_filtering() {
        let old_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": []
        }"#;

        let old = parse_sbom_str(old_content).unwrap();
        let new_path = fixture_path("cyclonedx/with-vulnerabilities.cdx.json");
        let new = parse_sbom(&new_path).unwrap();

        let engine = DiffEngine::new();
        let mut result = engine.diff(&old, &new).expect("diff should succeed");

        let total_before = result.vulnerabilities.introduced.len();

        // Filter to only critical
        result.filter_by_severity("critical");

        let total_after = result.vulnerabilities.introduced.len();

        // Should have fewer or equal vulnerabilities after filtering
        assert!(total_after <= total_before);

        // All remaining should be critical
        for vuln in &result.vulnerabilities.introduced {
            assert_eq!(
                vuln.severity.to_lowercase(),
                "critical",
                "After filtering, only critical vulns should remain"
            );
        }
    }

    #[test]
    fn test_diff_detects_ml_model_metadata_changes() {
        let path = fixture_path("cyclonedx/minimal-mlbom.cdx.json");
        let old = parse_sbom(&path).expect("Failed to parse ML BOM fixture");
        let mut new = old.clone();

        let model = new
            .components
            .values_mut()
            .find(|c| c.name == "bert-base")
            .expect("bert-base not found");
        let ml_info = model.ml_model.as_mut().expect("ML metadata missing");
        ml_info.quantization = Some("int4".to_string());
        model.calculate_content_hash();
        new.calculate_content_hash();

        let engine = DiffEngine::new();
        let result = engine.diff(&old, &new).expect("diff should succeed");

        assert_eq!(result.summary.components_modified, 1);
        let change = result
            .components
            .modified
            .iter()
            .find(|change| change.name == "bert-base")
            .expect("bert-base change not found");
        // ML changes are now granular and prefixed: a quantization swap surfaces as
        // `ml_quantization`, not an opaque `ml_model` blob.
        assert!(
            change.field_changes.iter().all(|f| f.field != "ml_model"),
            "opaque ml_model blob should be gone, got {:?}",
            change.field_changes
        );
        assert!(
            change
                .field_changes
                .iter()
                .any(|field| field.field == "ml_quantization"),
            "Expected ml_quantization field change, got {:?}",
            change.field_changes
        );
    }

    /// End-to-end: a security-relevant ML/dataset revision — model re-quantized,
    /// a training dataset dropped, and a dataset's sensitivity escalated to PII —
    /// must surface as granular, prefixed `FieldChange`s carrying high costs, and
    /// must render through the generic markdown and JSON report paths (no
    /// AI/ML-specific report code).
    #[test]
    fn test_semantic_ml_dataset_diff_end_to_end() {
        use sbom_tools::diff::CostModel;
        use sbom_tools::reports::{JsonReporter, MarkdownReporter, ReportConfig, ReportGenerator};

        let path = fixture_path("cyclonedx/minimal-mlbom.cdx.json");
        let old = parse_sbom(&path).expect("Failed to parse ML BOM fixture");
        let mut new = old.clone();

        // (1) Re-quantize the model fp32-ish -> int4 and (2) drop the
        // `data-wikipedia` training dataset, keeping `bookscorpus-800M`.
        {
            let model = new
                .components
                .values_mut()
                .find(|c| c.name == "bert-base")
                .expect("bert-base not found");
            let ml = model.ml_model.as_mut().expect("ML metadata missing");
            ml.quantization = Some("int4".to_string());
            ml.training_datasets
                .retain(|d| d.reference.as_deref() != Some("data-wikipedia"));
            assert!(
                ml.training_datasets
                    .iter()
                    .any(|d| d.name.as_deref() == Some("bookscorpus-800M")),
                "bookscorpus training dataset should survive"
            );
            model.calculate_content_hash();
        }

        // (3) Escalate the wikipedia dataset's sensitivity to include PII.
        {
            let data = new
                .components
                .values_mut()
                .find(|c| c.name == "wikipedia-2.5B")
                .expect("wikipedia dataset not found");
            let ds = data.dataset.as_mut().expect("dataset metadata missing");
            ds.sensitivity_classifications.push("pii".to_string());
            data.calculate_content_hash();
        }

        new.calculate_content_hash();

        // Use a security-focused cost model so the high-severity signals are bumped.
        let engine = DiffEngine::new().with_cost_model(CostModel::security_focused());
        let result = engine.diff(&old, &new).expect("diff should succeed");

        let model_change = result
            .components
            .modified
            .iter()
            .find(|c| c.name == "bert-base")
            .expect("bert-base change not found");

        let quant = model_change
            .field_changes
            .iter()
            .find(|f| f.field == "ml_quantization")
            .expect("ml_quantization change missing");
        assert_eq!(quant.new_value.as_deref(), Some("int4"));

        let removed_ds = model_change
            .field_changes
            .iter()
            .find(|f| f.field == "ml_training_dataset" && f.new_value.is_none())
            .expect("ml_training_dataset removal missing");
        assert_eq!(removed_ds.old_value.as_deref(), Some("data-wikipedia"));

        let data_change = result
            .components
            .modified
            .iter()
            .find(|c| c.name == "wikipedia-2.5B")
            .expect("wikipedia dataset change not found");
        let sensitivity = data_change
            .field_changes
            .iter()
            .find(|f| f.field == "dataset_sensitivity" && f.old_value.is_none())
            .expect("dataset_sensitivity escalation missing");
        assert_eq!(sensitivity.new_value.as_deref(), Some("pii"));

        // High-cost assertions: under the security profile the model's per-component
        // cost must dominate the bumped quantization + dataset-removal weights, and
        // the dataset's cost must reflect the PII escalation.
        let secure = CostModel::security_focused();
        assert!(
            model_change.cost
                >= secure.ml_quantization_changed + secure.ml_training_dataset_removed,
            "model cost {} should cover quantization+dataset-removal weights",
            model_change.cost
        );
        assert!(
            data_change.cost >= secure.dataset_sensitivity_added,
            "dataset cost {} should cover the PII-escalation weight",
            data_change.cost
        );

        // Generic rendering: the prefixed field names must appear in markdown and the
        // values must appear in JSON, with no dedicated AI/ML report code involved.
        let config = ReportConfig::default();
        let markdown = MarkdownReporter::new()
            .generate_diff_report(&result, &old, &new, &config)
            .expect("markdown report");
        assert!(
            markdown.contains("ml_quantization"),
            "markdown should surface ml_quantization via the generic path"
        );
        assert!(
            markdown.contains("dataset_sensitivity"),
            "markdown should surface dataset_sensitivity via the generic path"
        );

        let json = JsonReporter::new()
            .generate_diff_report(&result, &old, &new, &config)
            .expect("json report");
        assert!(
            json.contains("ml_training_dataset") && json.contains("data-wikipedia"),
            "json should surface the removed training dataset via the generic path"
        );
        assert!(
            json.contains("dataset_sensitivity") && json.contains("pii"),
            "json should surface the PII escalation via the generic path"
        );
    }

    #[test]
    fn test_semantic_score_calculation() {
        let old_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"}
            ]
        }"#;

        let new_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"},
                {"type": "library", "bom-ref": "b@1.0", "name": "b", "version": "1.0.0"}
            ]
        }"#;

        let old = parse_sbom_str(old_content).unwrap();
        let new = parse_sbom_str(new_content).unwrap();

        let engine = DiffEngine::new();
        let result = engine.diff(&old, &new).expect("diff should succeed");

        // Semantic score should be calculated
        assert!(
            result.semantic_score >= 0.0,
            "Semantic score should be non-negative"
        );
    }

    /// Two SBOMs that differ ONLY in document metadata (timestamp, author, tool
    /// version) — identical component sets — must surface those changes as
    /// `metadata_changes`, count as changes, and render in markdown + JSON.
    #[test]
    fn test_diff_surfaces_metadata_only_changes() {
        use sbom_tools::diff::MetadataChangeKind;
        use sbom_tools::reports::{JsonReporter, MarkdownReporter, ReportConfig, ReportGenerator};

        // Same single component in both; only metadata.{timestamp,authors,tools} differ.
        let old_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "metadata": {
                "timestamp": "2024-01-15T10:00:00Z",
                "authors": [{"name": "alice"}],
                "tools": [{"name": "syft", "version": "0.9.0"}]
            },
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"}
            ]
        }"#;
        let new_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "metadata": {
                "timestamp": "2024-06-15T10:00:00Z",
                "authors": [{"name": "bob"}],
                "tools": [{"name": "syft", "version": "1.0.0"}]
            },
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"}
            ]
        }"#;

        let old = parse_sbom_str(old_content).expect("old must parse");
        let new = parse_sbom_str(new_content).expect("new must parse");

        let engine = DiffEngine::new();
        let result = engine.diff(&old, &new).expect("diff should succeed");

        // A metadata-only diff must NOT be reported as "no changes".
        assert!(
            result.has_changes(),
            "metadata-only diff must register as a change"
        );
        assert!(
            !result.metadata_changes.is_empty(),
            "metadata changes must be populated"
        );
        assert!(
            result.components.is_empty(),
            "component set is identical — no component changes expected"
        );

        let by_field = |field: &str| {
            result
                .metadata_changes
                .iter()
                .find(|c| c.field == field)
                .unwrap_or_else(|| {
                    panic!(
                        "expected a `{field}` metadata change, got {:?}",
                        result.metadata_changes
                    )
                })
                .clone()
        };

        // Timestamp modified.
        let created = by_field("created");
        assert_eq!(created.kind, MetadataChangeKind::Modified);
        assert!(
            created
                .old_value
                .as_deref()
                .unwrap()
                .starts_with("2024-01-15")
        );
        assert!(
            created
                .new_value
                .as_deref()
                .unwrap()
                .starts_with("2024-06-15")
        );

        // Author churn: alice removed, bob added (persons are keyed by label).
        let authors: Vec<_> = result
            .metadata_changes
            .iter()
            .filter(|c| c.field == "creator.author")
            .collect();
        assert_eq!(authors.len(), 2, "expected alice removed + bob added");
        assert!(
            authors.iter().any(|c| c.kind == MetadataChangeKind::Removed
                && c.old_value.as_deref() == Some("alice"))
        );
        assert!(
            authors
                .iter()
                .any(|c| c.kind == MetadataChangeKind::Added
                    && c.new_value.as_deref() == Some("bob"))
        );

        // Tool version bump (the parser folds the version into the tool name, so
        // this surfaces as remove old + add new — either way the bump is visible).
        let tools: Vec<_> = result
            .metadata_changes
            .iter()
            .filter(|c| c.field == "creator.tool")
            .collect();
        assert!(
            tools
                .iter()
                .any(|c| c.old_value.as_deref().is_some_and(|v| v.contains("0.9.0")))
                || tools
                    .iter()
                    .any(|c| c.new_value.as_deref().is_some_and(|v| v.contains("1.0.0"))),
            "tool version bump must be surfaced, got {tools:?}"
        );

        // Summary count is wired through.
        assert_eq!(
            result.summary.metadata_changes_count,
            result.metadata_changes.len()
        );
        assert!(result.summary.total_changes >= result.metadata_changes.len());

        // Renders in Markdown.
        let config = ReportConfig::default();
        let md = MarkdownReporter::new()
            .generate_diff_report(&result, &old, &new, &config)
            .expect("markdown must render");
        assert!(
            md.contains("## Metadata Changes"),
            "markdown must include a Metadata Changes section"
        );
        assert!(
            md.contains("creator.author"),
            "markdown must list the author field"
        );

        // Renders in JSON (both the detailed list and the summary count).
        let json = JsonReporter::new()
            .generate_diff_report(&result, &old, &new, &config)
            .expect("json must render");
        let value: serde_json::Value =
            serde_json::from_str(&json).expect("json output must be valid JSON");
        assert!(
            value["reports"]["metadata_changes"].is_array(),
            "json reports must carry metadata_changes array"
        );
        assert_eq!(
            value["summary"]["metadata_changes"].as_u64(),
            Some(result.metadata_changes.len() as u64)
        );
    }
}

// ============================================================================
// Fuzzy Matching Tests
// ============================================================================

mod fuzzy_matching_tests {
    use super::*;
    use sbom_tools::matching::FuzzyMatcher;

    #[test]
    fn test_fuzzy_config_presets() {
        let strict = FuzzyMatchConfig::strict();
        assert_eq!(strict.threshold, 0.95);

        let balanced = FuzzyMatchConfig::balanced();
        assert_eq!(balanced.threshold, 0.85);

        let permissive = FuzzyMatchConfig::permissive();
        assert_eq!(permissive.threshold, 0.70);
    }

    #[test]
    fn test_fuzzy_config_from_preset() {
        assert!(FuzzyMatchConfig::from_preset("strict").is_some());
        assert!(FuzzyMatchConfig::from_preset("balanced").is_some());
        assert!(FuzzyMatchConfig::from_preset("permissive").is_some());
        assert!(FuzzyMatchConfig::from_preset("STRICT").is_some()); // Case insensitive
        assert!(FuzzyMatchConfig::from_preset("invalid").is_none());
    }

    #[test]
    fn test_exact_match_highest_score() {
        let config = FuzzyMatchConfig::balanced();
        let matcher = FuzzyMatcher::new(config);

        // Create two identical components
        let content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "pkg@1.0", "name": "lodash", "version": "4.17.21", "purl": "pkg:npm/lodash@4.17.21"}
            ]
        }"#;

        let sbom = parse_sbom_str(content).unwrap();
        let comp = sbom.components.values().next().unwrap();

        let score = matcher.match_components(comp, comp);
        assert_eq!(score, 1.0, "Identical components should have score 1.0");
    }
}

// ============================================================================
// Cross-Format Tests
// ============================================================================

mod cross_format_tests {
    use super::*;

    #[test]
    fn test_diff_cyclonedx_vs_spdx() {
        let cdx_path = fixture_path("cyclonedx/minimal.cdx.json");
        let spdx_path = fixture_path("spdx/minimal.spdx.json");

        let cdx = parse_sbom(&cdx_path).unwrap();
        let spdx = parse_sbom(&spdx_path).unwrap();

        // CycloneDX includes metadata.component (test-app), SPDX only has package components
        // CDX: test-app, lodash, express = 3
        // SPDX: lodash, express = 2
        assert_eq!(cdx.component_count(), 3);
        assert_eq!(spdx.component_count(), 2);

        // Both should have lodash and express
        assert!(cdx.components.values().any(|c| c.name == "lodash"));
        assert!(cdx.components.values().any(|c| c.name == "express"));
        assert!(spdx.components.values().any(|c| c.name == "lodash"));
        assert!(spdx.components.values().any(|c| c.name == "express"));

        // Diff should show high similarity for shared components
        let engine = DiffEngine::new().with_fuzzy_config(FuzzyMatchConfig::balanced());
        let result = engine.diff(&cdx, &spdx).expect("diff should succeed");

        // lodash and express should match, test-app from cdx has no match in spdx
        assert!(
            result.summary.components_removed <= 1,
            "Only the root app component should be unmatched"
        );
    }

    #[test]
    fn test_spdx3_quality_scoring() {
        use sbom_tools::quality::ScoringProfile;

        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0");

        let scorer = sbom_tools::quality::QualityScorer::new(ScoringProfile::Standard);
        let report = scorer.score(&sbom);

        // SPDX 3.0 should score reasonably well - it has components, hashes, licenses
        assert!(
            report.overall_score > 0.0,
            "SPDX 3.0 quality score should be > 0, got {}",
            report.overall_score
        );
    }

    #[test]
    fn test_spdx3_compliance_no_false_positives() {
        use sbom_tools::quality::{ComplianceChecker, ComplianceLevel};

        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0");

        let checker = ComplianceChecker::new(ComplianceLevel::Minimum);
        let report = checker.check(&sbom);

        // SPDX 3.0 URN-style IDs should not trigger false SPDXRef- format violations
        let spdxref_violations: Vec<_> = report
            .violations
            .iter()
            .filter(|v| v.requirement.contains("SPDXRef-"))
            .collect();
        assert!(
            spdxref_violations.is_empty(),
            "SPDX 3.0 should not trigger SPDXRef- format violations: {spdxref_violations:?}"
        );
    }

    // Phase 1: Security Profile Tests

    #[test]
    fn test_spdx3_security_profile_cvss_extraction() {
        let path = fixture_path("spdx3/security-profile.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 security profile");

        // Find the logging-lib component which has a CVSS assessment
        let logging_lib = sbom
            .components
            .values()
            .find(|c| c.name == "logging-lib")
            .expect("logging-lib not found");

        // Should have vulnerabilities from AFFECTS relationship + CVSS assessment
        assert!(
            !logging_lib.vulnerabilities.is_empty(),
            "logging-lib should have vulnerabilities"
        );

        // Find the vulnerability with CVSS data (from the assessment)
        let vuln_with_cvss = logging_lib
            .vulnerabilities
            .iter()
            .find(|v| !v.cvss.is_empty())
            .expect("Should have a vulnerability with CVSS scores from assessment");

        assert_eq!(vuln_with_cvss.id, "CVE-2025-0001");

        let cvss = &vuln_with_cvss.cvss[0];
        assert!(
            (cvss.base_score - 9.8).abs() < 0.01,
            "CVSS score should be 9.8"
        );
        assert!(cvss.vector.is_some(), "Should have CVSS vector string");
        assert!(
            cvss.vector.as_ref().unwrap().starts_with("CVSS:3.1"),
            "Vector should be CVSS v3.1"
        );

        // Severity should be derived from CVSS
        assert!(
            vuln_with_cvss.severity.is_some(),
            "Severity should be set from CVSS score"
        );
    }

    #[test]
    fn test_spdx3_security_profile_vex_not_affected() {
        let path = fixture_path("spdx3/security-profile.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 security profile");

        // Find the crypto-lib component which has a VEX NotAffected assessment
        let crypto_lib = sbom
            .components
            .values()
            .find(|c| c.name == "crypto-lib")
            .expect("crypto-lib not found");

        // Should have VEX status set
        let vex = crypto_lib
            .vex_status
            .as_ref()
            .expect("crypto-lib should have VEX status");

        assert_eq!(
            vex.status,
            sbom_tools::model::VexState::NotAffected,
            "VEX status should be NotAffected"
        );

        assert!(
            vex.justification.is_some(),
            "Should have justification for NotAffected"
        );
        assert!(
            vex.impact_statement.is_some(),
            "Should have impact statement"
        );
    }

    // Phase 2: Completeness Tests

    #[test]
    fn test_spdx3_snippet_parsing() {
        let path = fixture_path("spdx3/security-profile.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0");

        // Find the snippet component
        let snippet = sbom
            .components
            .values()
            .find(|c| c.name == "auth-handler.js")
            .expect("auth-handler.js snippet not found");

        assert_eq!(
            snippet.component_type,
            sbom_tools::model::ComponentType::File,
            "Snippets should map to File type"
        );

        // Should have range info in description
        assert!(
            snippet
                .description
                .as_ref()
                .is_some_and(|d| d.contains("bytes") && d.contains("lines")),
            "Snippet should have byte/line range in description"
        );
    }

    #[test]
    fn test_spdx3_annotation_parsing() {
        let path = fixture_path("spdx3/security-profile.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0");

        // Find logging-lib which has a REVIEW annotation
        let logging_lib = sbom
            .components
            .values()
            .find(|c| c.name == "logging-lib")
            .expect("logging-lib not found");

        assert!(
            !logging_lib.extensions.annotations.is_empty(),
            "logging-lib should have annotations"
        );

        let ann = &logging_lib.extensions.annotations[0];
        assert_eq!(ann.annotation_type, "REVIEW");
        assert!(ann.comment.contains("security compliance"));

        // webapp should also have annotation
        let webapp = sbom
            .components
            .values()
            .find(|c| c.name == "webapp")
            .expect("webapp not found");
        assert!(
            !webapp.extensions.annotations.is_empty(),
            "webapp should have annotations"
        );
    }

    #[test]
    fn test_spdx3_duplicate_element_detection() {
        // Create a document with duplicate element IDs
        let content = r#"{
            "@context": "https://spdx.org/rdf/3.0.1/spdx-context.jsonld",
            "type": "SpdxDocument",
            "spdxId": "urn:spdx:doc:dupe-test",
            "creationInfo": { "specVersion": "3.0.1", "created": "2025-01-01T00:00:00Z" },
            "element": [
                {
                    "type": "software_Package",
                    "spdxId": "urn:spdx:pkg:dupe",
                    "name": "package-a",
                    "packageVersion": "1.0.0"
                },
                {
                    "type": "software_Package",
                    "spdxId": "urn:spdx:pkg:dupe",
                    "name": "package-b",
                    "packageVersion": "2.0.0"
                }
            ]
        }"#;

        // Should parse without panic, second element overwrites first
        let sbom = parse_sbom_str(content).expect("Should parse despite duplicates");
        // At least one component should be present
        assert!(!sbom.components.is_empty());
    }

    #[test]
    fn test_spdx3_data_license_in_extensions() {
        let content = r#"{
            "@context": "https://spdx.org/rdf/3.0.1/spdx-context.jsonld",
            "type": "SpdxDocument",
            "spdxId": "urn:spdx:doc:data-lic-test",
            "dataLicense": "CC0-1.0",
            "creationInfo": { "specVersion": "3.0.1", "created": "2025-01-01T00:00:00Z" },
            "element": []
        }"#;

        let sbom = parse_sbom_str(content).expect("Should parse");
        assert!(
            sbom.extensions.spdx.is_some(),
            "Should have SPDX extensions with dataLicense"
        );
        let ext = sbom.extensions.spdx.as_ref().unwrap();
        assert_eq!(ext["dataLicense"], "CC0-1.0");
    }

    // Phase 6: Compliance Refinement Tests

    #[test]
    fn test_spdx3_cra_security_profile_conformance_check() {
        use sbom_tools::quality::{ComplianceChecker, ComplianceLevel};

        let path = fixture_path("spdx3/security-profile.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0 security profile");

        let checker = ComplianceChecker::new(ComplianceLevel::CraPhase1);
        let report = checker.check(&sbom);

        // Security profile IS declared in this fixture, so no profile conformance warning
        let profile_violations: Vec<_> = report
            .violations
            .iter()
            .filter(|v| v.requirement.contains("Security profile conformance"))
            .collect();
        assert!(
            profile_violations.is_empty(),
            "Should not have Security profile conformance violation when declared: {profile_violations:?}"
        );
    }

    #[test]
    fn test_spdx3_cra_missing_security_profile_warning() {
        use sbom_tools::quality::{ComplianceChecker, ComplianceLevel};

        // The minimal fixture has vulns but no Security profile declaration
        let path = fixture_path("spdx3/minimal.spdx3.json");
        let sbom = parse_sbom(&path).expect("Failed to parse SPDX 3.0");

        let checker = ComplianceChecker::new(ComplianceLevel::CraPhase1);
        let report = checker.check(&sbom);

        // Should warn about missing Security profile
        let profile_warnings: Vec<_> = report
            .violations
            .iter()
            .filter(|v| v.message.contains("Security profile"))
            .collect();
        assert!(
            !profile_warnings.is_empty(),
            "Should warn about missing Security profile when vulns present"
        );
    }
}

// ============================================================================
// Model Tests
// ============================================================================

mod model_tests {
    use super::*;

    #[test]
    fn test_normalized_sbom_content_hash() {
        let content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "a@1.0", "name": "a", "version": "1.0.0"}
            ]
        }"#;

        let mut sbom = parse_sbom_str(content).unwrap();
        sbom.calculate_content_hash();

        assert_ne!(sbom.content_hash, 0, "Content hash should be calculated");

        // Same content should produce same hash
        let mut sbom2 = parse_sbom_str(content).unwrap();
        sbom2.calculate_content_hash();

        // Note: Hash might differ due to parsing order, but should be consistent
        // for the same input
    }

    #[test]
    fn test_component_display_name() {
        let content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [
                {"type": "library", "bom-ref": "test@1.0", "name": "test-pkg", "version": "1.0.0"}
            ]
        }"#;

        let sbom = parse_sbom_str(content).unwrap();
        let comp = sbom.components.values().next().unwrap();

        assert_eq!(comp.display_name(), "test-pkg@1.0.0");
    }

    #[test]
    fn test_vulnerability_counts() {
        let path = fixture_path("cyclonedx/with-vulnerabilities.cdx.json");
        let sbom = parse_sbom(&path).unwrap();

        let counts = sbom.vulnerability_counts();
        assert!(counts.total() > 0, "Should have vulnerabilities");
        assert!(
            counts.critical > 0 || counts.high > 0,
            "Should have high severity vulns"
        );
    }
}

// ============================================================================
// Report Security Tests
// ============================================================================

mod report_security_tests {
    use super::*;
    use sbom_tools::reports::escape::{
        escape_html, escape_html_attr, escape_markdown_inline, escape_markdown_table,
    };
    use sbom_tools::reports::{HtmlReporter, MarkdownReporter, ReportConfig, ReportGenerator};

    // Malicious payloads for testing
    const XSS_SCRIPT: &str = "<script>alert('xss')</script>";
    const XSS_EVENT: &str = "<img onerror=\"alert('xss')\">";
    const XSS_ENTITY: &str = "&lt;script&gt;alert('double')&lt;/script&gt;";
    const MD_PIPE_INJECT: &str = "name|evil|payload";
    const MD_NEWLINE_INJECT: &str = "name\n| new | row |";
    const MD_LINK_INJECT: &str = "[evil](http://malware.com)";
    const MD_CODE_INJECT: &str = "```\ncode block\n```";

    #[test]
    fn test_html_escape_xss_script() {
        let escaped = escape_html(XSS_SCRIPT);
        assert!(
            !escaped.contains("<script>"),
            "Script tags should be escaped"
        );
        assert!(
            !escaped.contains("</script>"),
            "Closing script tags should be escaped"
        );
        assert!(
            escaped.contains("&lt;script&gt;"),
            "Should use HTML entities"
        );
    }

    #[test]
    fn test_html_escape_xss_event_handler() {
        let escaped = escape_html(XSS_EVENT);
        // The key is that < and > are escaped, making the tag inert
        assert!(
            !escaped.contains("<img"),
            "Raw tag opening should be escaped"
        );
        assert!(escaped.contains("&lt;img"), "Tags should be escaped");
        assert!(
            escaped.contains("&quot;"),
            "Quotes in attributes should be escaped"
        );
    }

    #[test]
    fn test_html_escape_double_encoding() {
        let escaped = escape_html(XSS_ENTITY);
        // Already-escaped entities should be re-escaped
        assert!(
            escaped.contains("&amp;lt;"),
            "Should escape the ampersand in entities"
        );
    }

    #[test]
    fn test_html_attr_escape_newlines() {
        let input = "value with\nnewline";
        let escaped = escape_html_attr(input);
        assert!(
            !escaped.contains('\n'),
            "Newlines should be escaped in attributes"
        );
        assert!(
            escaped.contains("&#10;"),
            "Should use numeric entity for newline"
        );
    }

    #[test]
    fn test_markdown_table_pipe_injection() {
        let escaped = escape_markdown_table(MD_PIPE_INJECT);
        // Check that pipes are preceded by backslash (escaped)
        // Original: "name|evil|payload" -> "name\|evil\|payload"
        assert!(escaped.contains("\\|"), "Pipes should be backslash-escaped");
        // Verify the exact expected output
        assert_eq!(
            escaped, "name\\|evil\\|payload",
            "Should escape all pipes with backslashes"
        );
    }

    #[test]
    fn test_markdown_table_newline_injection() {
        let escaped = escape_markdown_table(MD_NEWLINE_INJECT);
        assert!(
            !escaped.contains('\n'),
            "Newlines should be removed/escaped"
        );
    }

    #[test]
    fn test_markdown_link_injection() {
        let escaped = escape_markdown_table(MD_LINK_INJECT);
        assert!(escaped.contains("\\["), "Square brackets should be escaped");
    }

    #[test]
    fn test_markdown_code_block_injection() {
        let escaped = escape_markdown_table(MD_CODE_INJECT);
        assert!(!escaped.contains("```"), "Backticks should be escaped");
        assert!(
            escaped.contains("\\`"),
            "Backticks should be backslash-escaped"
        );
    }

    #[test]
    fn test_html_report_with_malicious_component_name() {
        // Create SBOM with malicious component name
        let content = format!(
            r#"{{
                "bomFormat": "CycloneDX",
                "specVersion": "1.5",
                "version": 1,
                "components": [
                    {{"type": "library", "bom-ref": "evil@1.0", "name": "{}", "version": "1.0.0"}}
                ]
            }}"#,
            XSS_SCRIPT
        );

        let sbom = parse_sbom_str(&content).unwrap();
        let reporter = HtmlReporter::new();
        let config = ReportConfig::default();

        let html = reporter
            .generate_view_report(&sbom, &config)
            .expect("Should generate report");

        // Verify the malicious content is escaped
        assert!(
            !html.contains("<script>"),
            "HTML report should escape script tags in component names"
        );
        assert!(
            html.contains("&lt;script&gt;"),
            "HTML report should contain escaped version"
        );
    }

    #[test]
    fn test_html_report_with_malicious_title() {
        let sbom_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": []
        }"#;

        let sbom = parse_sbom_str(sbom_content).unwrap();
        let reporter = HtmlReporter::new();
        let config = ReportConfig {
            title: Some(XSS_SCRIPT.to_string()),
            ..Default::default()
        };

        let html = reporter
            .generate_view_report(&sbom, &config)
            .expect("Should generate report");

        // Verify the malicious title is escaped
        assert!(
            !html.contains("<script>alert"),
            "HTML report should escape script tags in title"
        );
    }

    #[test]
    fn test_markdown_report_with_malicious_component_name() {
        // Create SBOM with table-breaking component name
        let content = format!(
            r#"{{
                "bomFormat": "CycloneDX",
                "specVersion": "1.5",
                "version": 1,
                "components": [
                    {{"type": "library", "bom-ref": "evil@1.0", "name": "{}", "version": "1.0.0"}}
                ]
            }}"#,
            MD_PIPE_INJECT
        );

        let sbom = parse_sbom_str(&content).unwrap();
        let reporter = MarkdownReporter::new();
        let config = ReportConfig::default();

        let md = reporter
            .generate_view_report(&sbom, &config)
            .expect("Should generate report");

        // Verify pipes are escaped (count pipes on component row)
        // A properly escaped row should have the expected number of pipes (5 for table delimiters)
        // not extra ones from the malicious payload
        let component_line = md
            .lines()
            .find(|l| l.contains("evil"))
            .expect("Should have component line");

        // Count escaped pipes (the backslash-pipe sequence)
        let escaped_pipe_count = component_line.matches("\\|").count();

        // The malicious payload "name|evil|payload" has 2 pipes, which should all be escaped
        assert!(
            escaped_pipe_count >= 2,
            "Malicious pipes should be escaped: {}",
            component_line
        );
    }

    #[test]
    fn test_markdown_report_with_malicious_title() {
        let sbom_content = r#"{
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": []
        }"#;

        let sbom = parse_sbom_str(sbom_content).unwrap();
        let reporter = MarkdownReporter::new();
        let config = ReportConfig {
            title: Some("# Injected Heading\n## Another".to_string()),
            ..Default::default()
        };

        let md = reporter
            .generate_view_report(&sbom, &config)
            .expect("Should generate report");

        // Title's hash marks should be escaped
        assert!(md.contains("\\#"), "Hash marks in title should be escaped");
    }

    #[test]
    fn test_escape_preserves_unicode() {
        let unicode_name = "日本語パッケージ";
        let escaped_html = escape_html(unicode_name);
        let escaped_md = escape_markdown_table(unicode_name);

        assert_eq!(
            escaped_html, unicode_name,
            "Unicode should pass through HTML escape"
        );
        assert_eq!(
            escaped_md, unicode_name,
            "Unicode should pass through Markdown escape"
        );
    }

    #[test]
    fn test_escape_empty_string() {
        assert_eq!(escape_html(""), "");
        assert_eq!(escape_markdown_table(""), "");
        assert_eq!(escape_markdown_inline(""), "");
    }

    #[test]
    fn test_realistic_purl_escaping() {
        // PURLs can contain special characters
        let purl = "pkg:npm/%40scope/name@1.0.0?vcs_url=git%2Bhttps://github.com/org/repo";
        let html_escaped = escape_html(purl);
        let md_escaped = escape_markdown_table(purl);

        // Should preserve URL encoding but escape any HTML/MD special chars
        assert!(
            html_escaped.contains("%40"),
            "URL encoding should be preserved in HTML"
        );
        assert!(
            md_escaped.contains("%40"),
            "URL encoding should be preserved in Markdown"
        );
    }
}

/// Tests for ID-stable component selection across sort/filter changes.
///
/// These tests ensure that component selection remains stable when the view is
/// re-sorted or filtered, by using CanonicalId for identification rather than
/// positional indices.
mod id_stable_selection_tests {
    use sbom_tools::model::{
        CanonicalId, Component, DocumentMetadata, NormalizedSbom, NormalizedSbomIndex,
    };

    /// Helper to create a test SBOM with multiple components
    fn create_test_sbom() -> NormalizedSbom {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());

        // Create components with different names and versions for sorting tests
        let mut comp_a = Component::new("alpha".to_string(), "alpha-id".to_string());
        comp_a.version = Some("1.0.0".to_string());

        let mut comp_b = Component::new("beta".to_string(), "beta-id".to_string());
        comp_b.version = Some("2.0.0".to_string());

        let mut comp_c = Component::new("gamma".to_string(), "gamma-id".to_string());
        comp_c.version = Some("0.5.0".to_string());

        let mut comp_d = Component::new("delta".to_string(), "delta-id".to_string());
        comp_d.version = Some("3.0.0".to_string());

        sbom.add_component(comp_a);
        sbom.add_component(comp_b);
        sbom.add_component(comp_c);
        sbom.add_component(comp_d);

        sbom
    }

    #[test]
    fn test_canonical_id_stability_across_sorts() {
        let sbom = create_test_sbom();
        let index = NormalizedSbomIndex::build(&sbom);

        // Get all component IDs
        let mut ids: Vec<CanonicalId> = sbom.components.keys().cloned().collect();

        // Store original order
        let original_order: Vec<String> = ids.iter().map(|id| id.value().to_string()).collect();

        // Sort by name
        ids.sort_by(|a, b| {
            let key_a = index.sort_key(a).unwrap();
            let key_b = index.sort_key(b).unwrap();
            key_a.name_lower.cmp(&key_b.name_lower)
        });

        // Verify IDs are still valid after sort
        for id in &ids {
            assert!(
                sbom.components.contains_key(id),
                "Component should still be accessible by ID after sort"
            );
        }

        // Verify sorted order is by name
        let sorted_names: Vec<&str> = ids
            .iter()
            .map(|id| sbom.components.get(id).unwrap().name.as_str())
            .collect();

        assert_eq!(sorted_names, vec!["alpha", "beta", "delta", "gamma"]);

        // Original IDs should still resolve to same components
        for original_id_str in &original_order {
            let original_id = ids.iter().find(|id| id.value() == original_id_str).unwrap();
            assert!(
                sbom.components.contains_key(original_id),
                "Original ID '{}' should still resolve",
                original_id_str
            );
        }
    }

    #[test]
    fn test_selection_preserved_after_filter() {
        let sbom = create_test_sbom();

        // Simulate selecting "beta" component by its ID
        let selected_id = sbom
            .components
            .keys()
            .find(|id| id.value().contains("beta"))
            .cloned()
            .unwrap();

        // Simulate filtering - only show components matching "ph" (alpha only)
        let filtered_ids: Vec<&CanonicalId> = sbom
            .components
            .iter()
            .filter(|(_, comp)| comp.name.contains("ph"))
            .map(|(id, _)| id)
            .collect();

        // "beta" doesn't match filter, but ID should still be valid
        assert!(
            sbom.components.contains_key(&selected_id),
            "Selected ID should still be valid even if filtered out"
        );

        // Filtered list should contain only alpha (has "ph")
        assert_eq!(filtered_ids.len(), 1);

        // When filter is removed, selected ID should still resolve
        let component = sbom.components.get(&selected_id).unwrap();
        assert_eq!(component.name, "beta");
    }

    #[test]
    fn test_id_lookup_performance_with_index() {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());

        // Create many components
        for i in 0..100 {
            let comp = Component::new(format!("component-{}", i), format!("id-{}", i));
            sbom.add_component(comp);
        }

        let index = NormalizedSbomIndex::build(&sbom);

        // All lookups should be O(1)
        assert_eq!(index.component_count(), 100);

        // Test name search
        let matches = index.search_by_name("component-5");
        assert!(
            !matches.is_empty(),
            "Should find components matching 'component-5'"
        );
    }

    #[test]
    fn test_canonical_id_equality_across_sources() {
        // IDs with same value should be equal regardless of source
        let id1 = CanonicalId::from_purl("pkg:npm/lodash@4.0.0");
        let id2 = CanonicalId::from_purl("pkg:npm/lodash@4.0.0");

        assert_eq!(id1, id2, "Same PURL should produce equal IDs");

        // Synthetic IDs with same content should be equal
        let id3 = CanonicalId::synthetic(Some("org"), "package", Some("1.0.0"));
        let id4 = CanonicalId::synthetic(Some("org"), "package", Some("1.0.0"));

        assert_eq!(
            id3, id4,
            "Same synthetic ID params should produce equal IDs"
        );
    }

    #[test]
    fn test_id_stability_markers() {
        // PURL-based ID should be stable
        let purl_id = CanonicalId::from_purl("pkg:npm/react@18.0.0");
        assert!(purl_id.is_stable(), "PURL-based ID should be stable");

        // UUID-like format ID should not be stable
        let uuid_id = CanonicalId::from_format_id("550e8400-e29b-41d4-a716-446655440000");
        assert!(!uuid_id.is_stable(), "UUID format ID should not be stable");

        // Synthetic ID should be stable
        let synthetic_id = CanonicalId::synthetic(None, "mypackage", Some("1.0.0"));
        assert!(synthetic_id.is_stable(), "Synthetic ID should be stable");
    }
}

/// Tests for dependency adjacency in NormalizedSbomIndex.
///
/// These tests verify that the index correctly tracks dependency relationships
/// and can efficiently query both dependencies (outgoing) and dependents (incoming).
mod dependency_adjacency_tests {
    use sbom_tools::model::{
        Component, DependencyEdge, DependencyType, DocumentMetadata, NormalizedSbom,
        NormalizedSbomIndex, SbomIndexBuilder,
    };

    /// Create a test SBOM with a known dependency graph:
    /// ```
    ///     A
    ///    / \
    ///   B   C
    ///   |   |
    ///   D   D  (D has two dependents)
    ///   |
    ///   E
    /// ```
    fn create_dependency_graph() -> NormalizedSbom {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());

        let comp_a = Component::new("root".to_string(), "A".to_string());
        let comp_b = Component::new("lib-b".to_string(), "B".to_string());
        let comp_c = Component::new("lib-c".to_string(), "C".to_string());
        let comp_d = Component::new("shared-d".to_string(), "D".to_string());
        let comp_e = Component::new("leaf-e".to_string(), "E".to_string());

        let id_a = comp_a.canonical_id.clone();
        let id_b = comp_b.canonical_id.clone();
        let id_c = comp_c.canonical_id.clone();
        let id_d = comp_d.canonical_id.clone();
        let id_e = comp_e.canonical_id.clone();

        sbom.add_component(comp_a);
        sbom.add_component(comp_b);
        sbom.add_component(comp_c);
        sbom.add_component(comp_d);
        sbom.add_component(comp_e);

        // A -> B, A -> C
        sbom.add_edge(DependencyEdge::new(
            id_a.clone(),
            id_b.clone(),
            DependencyType::DependsOn,
        ));
        sbom.add_edge(DependencyEdge::new(
            id_a.clone(),
            id_c.clone(),
            DependencyType::DependsOn,
        ));

        // B -> D, C -> D (D is shared)
        sbom.add_edge(DependencyEdge::new(
            id_b.clone(),
            id_d.clone(),
            DependencyType::DependsOn,
        ));
        sbom.add_edge(DependencyEdge::new(
            id_c.clone(),
            id_d.clone(),
            DependencyType::DependsOn,
        ));

        // D -> E
        sbom.add_edge(DependencyEdge::new(
            id_d.clone(),
            id_e.clone(),
            DependencyType::DependsOn,
        ));

        sbom
    }

    #[test]
    fn test_dependency_count() {
        let sbom = create_dependency_graph();
        let index = NormalizedSbomIndex::build(&sbom);

        // Find each component's ID
        let find_id = |name: &str| {
            sbom.components
                .iter()
                .find(|(_, c)| c.name == name)
                .map(|(id, _)| id)
                .unwrap()
        };

        let id_a = find_id("root");
        let id_b = find_id("lib-b");
        let id_d = find_id("shared-d");
        let id_e = find_id("leaf-e");

        // A has 2 dependencies (B, C)
        assert_eq!(index.dependency_count(id_a), 2);

        // B has 1 dependency (D)
        assert_eq!(index.dependency_count(id_b), 1);

        // D has 1 dependency (E)
        assert_eq!(index.dependency_count(id_d), 1);

        // E has no dependencies (leaf)
        assert_eq!(index.dependency_count(id_e), 0);
    }

    #[test]
    fn test_dependent_count() {
        let sbom = create_dependency_graph();
        let index = NormalizedSbomIndex::build(&sbom);

        let find_id = |name: &str| {
            sbom.components
                .iter()
                .find(|(_, c)| c.name == name)
                .map(|(id, _)| id)
                .unwrap()
        };

        let id_a = find_id("root");
        let id_b = find_id("lib-b");
        let id_d = find_id("shared-d");
        let id_e = find_id("leaf-e");

        // A has no dependents (root)
        assert_eq!(index.dependent_count(id_a), 0);

        // B has 1 dependent (A)
        assert_eq!(index.dependent_count(id_b), 1);

        // D has 2 dependents (B, C) - shared dependency
        assert_eq!(index.dependent_count(id_d), 2);

        // E has 1 dependent (D)
        assert_eq!(index.dependent_count(id_e), 1);
    }

    #[test]
    fn test_dependencies_of_returns_edges() {
        let sbom = create_dependency_graph();
        let index = NormalizedSbomIndex::build(&sbom);

        let id_a = sbom
            .components
            .iter()
            .find(|(_, c)| c.name == "root")
            .map(|(id, _)| id)
            .unwrap();

        let deps = index.dependencies_of(id_a, &sbom.edges);

        assert_eq!(deps.len(), 2, "A should have 2 dependencies");

        // Check that edges point from A
        for edge in deps {
            assert_eq!(&edge.from, id_a, "Edge should originate from A");
        }
    }

    #[test]
    fn test_dependents_of_returns_edges() {
        let sbom = create_dependency_graph();
        let index = NormalizedSbomIndex::build(&sbom);

        let id_d = sbom
            .components
            .iter()
            .find(|(_, c)| c.name == "shared-d")
            .map(|(id, _)| id)
            .unwrap();

        let dependents = index.dependents_of(id_d, &sbom.edges);

        assert_eq!(dependents.len(), 2, "D should have 2 dependents");

        // Check that edges point to D
        for edge in dependents {
            assert_eq!(&edge.to, id_d, "Edge should point to D");
        }
    }

    #[test]
    fn test_has_dependencies_and_dependents() {
        let sbom = create_dependency_graph();
        let index = NormalizedSbomIndex::build(&sbom);

        let find_id = |name: &str| {
            sbom.components
                .iter()
                .find(|(_, c)| c.name == name)
                .map(|(id, _)| id)
                .unwrap()
        };

        let id_a = find_id("root");
        let id_d = find_id("shared-d");
        let id_e = find_id("leaf-e");

        // A is root: has dependencies, no dependents
        assert!(index.has_dependencies(id_a));
        assert!(!index.has_dependents(id_a));

        // D is middle: has both
        assert!(index.has_dependencies(id_d));
        assert!(index.has_dependents(id_d));

        // E is leaf: no dependencies, has dependent
        assert!(!index.has_dependencies(id_e));
        assert!(index.has_dependents(id_e));
    }

    #[test]
    fn test_root_and_leaf_counts() {
        let sbom = create_dependency_graph();
        let index = NormalizedSbomIndex::build(&sbom);

        // Root (no incoming): A
        // Note: The root_count implementation counts components not in edges_by_target
        // Let's verify expected behavior
        assert!(index.root_count() >= 1, "Should have at least one root");

        // Leaf (no outgoing): E
        assert!(index.leaf_count() >= 1, "Should have at least one leaf");
    }

    #[test]
    fn test_edge_indices_are_valid() {
        let sbom = create_dependency_graph();
        let index = NormalizedSbomIndex::build(&sbom);

        // Get dependency indices for root
        let id_a = sbom
            .components
            .iter()
            .find(|(_, c)| c.name == "root")
            .map(|(id, _)| id)
            .unwrap();

        let indices = index.dependency_indices(id_a);

        // All indices should be valid
        for &idx in indices {
            assert!(
                idx < sbom.edges.len(),
                "Edge index {} should be valid (< {})",
                idx,
                sbom.edges.len()
            );
        }
    }

    #[test]
    fn test_empty_sbom_index() {
        let sbom = NormalizedSbom::default();
        let index = NormalizedSbomIndex::build(&sbom);

        assert_eq!(index.component_count(), 0);
        assert_eq!(index.edge_count(), 0);
        assert_eq!(index.root_count(), 0);
        assert_eq!(index.leaf_count(), 0);
    }

    #[test]
    fn test_minimal_index_builder() {
        let sbom = create_dependency_graph();
        let index = SbomIndexBuilder::minimal().build(&sbom);

        // Edges should still work
        assert_eq!(index.edge_count(), 5);

        // But name lookup should be empty (not indexed)
        let matches = index.find_by_name_lower("root");
        assert!(matches.is_empty(), "Minimal index should not index names");
    }

    #[test]
    fn test_full_index_builder() {
        let sbom = create_dependency_graph();
        let index = SbomIndexBuilder::new()
            .with_name_index()
            .with_sort_keys()
            .build(&sbom);

        // Name lookup should work
        let matches = index.find_by_name_lower("root");
        assert!(!matches.is_empty(), "Full index should index names");

        // Sort keys should be available
        let id = matches.first().unwrap();
        let sort_key = index.sort_key(id);
        assert!(sort_key.is_some(), "Sort key should be available");
    }
}

/// Tests for search navigation and ID resolution.
///
/// These tests ensure that search results correctly resolve to component IDs
/// and that navigation within search results works properly.
mod search_navigation_tests {
    use sbom_tools::model::{
        CanonicalId, Component, DocumentMetadata, NormalizedSbom, NormalizedSbomIndex,
    };
    use sbom_tools::tui::state::ListNavigation;
    use sbom_tools::tui::viewmodel::SearchState;

    /// Create a test SBOM with searchable components
    fn create_searchable_sbom() -> NormalizedSbom {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());

        let names = vec![
            "react",
            "react-dom",
            "react-router",
            "lodash",
            "lodash-es",
            "express",
            "express-validator",
            "axios",
            "moment",
            "moment-timezone",
        ];

        for name in names {
            let comp = Component::new(name.to_string(), format!("{}-id", name));
            sbom.add_component(comp);
        }

        sbom
    }

    #[test]
    fn test_search_by_name_finds_matches() {
        let sbom = create_searchable_sbom();
        let index = NormalizedSbomIndex::build(&sbom);

        // Search for "react" should find 3 matches
        let matches = index.search_by_name("react");
        assert_eq!(matches.len(), 3, "Should find 3 react-related components");

        // Search for "lodash" should find 2 matches
        let matches = index.search_by_name("lodash");
        assert_eq!(matches.len(), 2, "Should find 2 lodash-related components");

        // Search for "express" should find 2 matches
        let matches = index.search_by_name("express");
        assert_eq!(matches.len(), 2, "Should find 2 express-related components");
    }

    #[test]
    fn test_search_results_resolve_to_components() {
        let sbom = create_searchable_sbom();
        let index = NormalizedSbomIndex::build(&sbom);

        let matches = index.search_by_name("moment");

        // Each match should resolve to a valid component
        for id in &matches {
            let component = sbom.components.get(id);
            assert!(
                component.is_some(),
                "Search result ID should resolve to component"
            );

            let comp = component.unwrap();
            assert!(
                comp.name.contains("moment"),
                "Component name should contain search term"
            );
        }
    }

    #[test]
    fn test_search_state_navigation() {
        let mut search: SearchState<CanonicalId> = SearchState::new();

        // Simulate search results
        let ids: Vec<CanonicalId> = vec![
            CanonicalId::synthetic(None, "result1", None),
            CanonicalId::synthetic(None, "result2", None),
            CanonicalId::synthetic(None, "result3", None),
            CanonicalId::synthetic(None, "result4", None),
            CanonicalId::synthetic(None, "result5", None),
        ];

        search.set_results(ids);

        // Initial selection
        assert_eq!(search.selected, 0);
        assert!(search.selected_result().is_some());

        // Navigate forward
        search.select_next();
        assert_eq!(search.selected, 1);

        search.select_next();
        search.select_next();
        assert_eq!(search.selected, 3);

        // Navigate backward
        search.select_prev();
        assert_eq!(search.selected, 2);

        // Can't go past end
        search.select_next();
        search.select_next();
        search.select_next();
        assert_eq!(search.selected, 4); // Stays at last

        // Can't go before start
        search.set_selected(0);
        search.select_prev();
        assert_eq!(search.selected, 0); // Stays at first
    }

    #[test]
    fn test_search_result_id_stability() {
        let sbom = create_searchable_sbom();
        let index = NormalizedSbomIndex::build(&sbom);

        // Get search results
        let matches = index.search_by_name("axios");
        assert_eq!(matches.len(), 1);

        let selected_id = matches[0].clone();

        // Even after rebuilding index, same search should find same component
        let index2 = NormalizedSbomIndex::build(&sbom);
        let matches2 = index2.search_by_name("axios");

        assert_eq!(matches2.len(), 1);
        assert_eq!(
            matches2[0], selected_id,
            "Same search should return same ID"
        );
    }

    #[test]
    fn test_case_insensitive_search() {
        let sbom = create_searchable_sbom();
        let index = NormalizedSbomIndex::build(&sbom);

        // Searches should be case-insensitive
        let lower = index.search_by_name("react");

        // Note: search_by_name expects lowercase input, so uppercase searches
        // need to be lowercased by the caller
        assert_eq!(lower.len(), 3);

        // For case-insensitive search, caller must lowercase the query
        let upper_lower = index.search_by_name(&"REACT".to_lowercase());
        assert_eq!(upper_lower.len(), lower.len());

        let mixed_lower = index.search_by_name(&"ReAcT".to_lowercase());
        assert_eq!(mixed_lower.len(), lower.len());
    }

    #[test]
    fn test_search_with_empty_query() {
        let sbom = create_searchable_sbom();
        let index = NormalizedSbomIndex::build(&sbom);

        // Empty search should return no results
        let matches = index.search_by_name("");
        // Empty string matches everything due to contains("")
        assert_eq!(matches.len(), 10, "Empty search matches all components");
    }

    #[test]
    fn test_search_no_matches() {
        let sbom = create_searchable_sbom();
        let index = NormalizedSbomIndex::build(&sbom);

        // Search for non-existent term
        let matches = index.search_by_name("nonexistent");
        assert!(matches.is_empty(), "Should find no matches");
    }

    #[test]
    fn test_find_by_exact_name_lower() {
        let sbom = create_searchable_sbom();
        let index = NormalizedSbomIndex::build(&sbom);

        // Exact name match (lowercase)
        let matches = index.find_by_name_lower("react");
        assert_eq!(matches.len(), 1, "Exact match should find one component");

        // Partial name shouldn't match exact lookup
        let matches = index.find_by_name_lower("reac");
        assert!(matches.is_empty(), "Partial should not match exact lookup");
    }

    #[test]
    fn test_sort_key_contains_search() {
        use sbom_tools::model::ComponentSortKey;

        let mut comp = Component::new("my-package".to_string(), "pkg-1".to_string());
        comp.version = Some("2.3.4".to_string());

        let key = ComponentSortKey::from_component(&comp);

        // Should find by name
        assert!(key.contains("my-pack"));
        assert!(key.contains("package"));

        // Should find by version
        assert!(key.contains("2.3.4"));
        assert!(key.contains("2.3"));

        // Should not find non-matching
        assert!(!key.contains("react"));
        assert!(!key.contains("5.0.0"));
    }
}

/// Tests for streaming mode configuration and activation.
mod streaming_tests {
    use sbom_tools::config::StreamingConfig;

    #[test]
    fn test_streaming_config_default() {
        let config = StreamingConfig::default();
        assert_eq!(config.threshold_bytes, 10 * 1024 * 1024); // 10 MB
        assert!(!config.force);
        assert!(!config.disabled);
        assert!(config.stream_stdin);
    }

    #[test]
    fn test_streaming_config_should_stream_below_threshold() {
        let config = StreamingConfig::default();
        // File smaller than 10 MB should not trigger streaming
        assert!(!config.should_stream(Some(1024 * 1024), false)); // 1 MB
        assert!(!config.should_stream(Some(5 * 1024 * 1024), false)); // 5 MB
    }

    #[test]
    fn test_streaming_config_should_stream_above_threshold() {
        let config = StreamingConfig::default();
        // File equal to or larger than 10 MB should trigger streaming
        assert!(config.should_stream(Some(10 * 1024 * 1024), false)); // 10 MB exactly
        assert!(config.should_stream(Some(20 * 1024 * 1024), false)); // 20 MB
        assert!(config.should_stream(Some(100 * 1024 * 1024), false)); // 100 MB
    }

    #[test]
    fn test_streaming_config_force_mode() {
        let config = StreamingConfig::always();
        assert!(config.force);
        // Force mode should always stream regardless of file size
        assert!(config.should_stream(Some(1024), false)); // 1 KB
        assert!(config.should_stream(Some(0), false)); // 0 bytes
        assert!(config.should_stream(None, false)); // Unknown size
    }

    #[test]
    fn test_streaming_config_disabled_mode() {
        let config = StreamingConfig::never();
        assert!(config.disabled);
        // Disabled should never stream regardless of file size
        assert!(!config.should_stream(Some(100 * 1024 * 1024), false)); // 100 MB
        assert!(!config.should_stream(Some(1024 * 1024 * 1024), false)); // 1 GB
        assert!(!config.should_stream(None, true)); // stdin
    }

    #[test]
    fn test_streaming_config_stdin_mode() {
        let config = StreamingConfig::default();
        // stdin should trigger streaming (since size is unknown)
        assert!(config.should_stream(None, true));
    }

    #[test]
    fn test_streaming_config_stdin_disabled() {
        let config = StreamingConfig {
            stream_stdin: false,
            ..StreamingConfig::default()
        };
        // stdin with stream_stdin=false should not trigger streaming
        assert!(!config.should_stream(None, true));
    }

    #[test]
    fn test_streaming_config_with_threshold_mb() {
        let config = StreamingConfig::default().with_threshold_mb(50);
        assert_eq!(config.threshold_bytes, 50 * 1024 * 1024); // 50 MB

        // Below threshold
        assert!(!config.should_stream(Some(40 * 1024 * 1024), false));
        // At/above threshold
        assert!(config.should_stream(Some(50 * 1024 * 1024), false));
    }

    #[test]
    fn test_streaming_config_custom_threshold() {
        let config = StreamingConfig {
            threshold_bytes: 1024 * 1024, // 1 MB
            force: false,
            disabled: false,
            stream_stdin: true,
        };

        // Files >= 1 MB should stream
        assert!(!config.should_stream(Some(512 * 1024), false)); // 512 KB
        assert!(config.should_stream(Some(1024 * 1024), false)); // 1 MB
        assert!(config.should_stream(Some(2 * 1024 * 1024), false)); // 2 MB
    }

    #[test]
    fn test_streaming_json_reporter_implements_writer_reporter() {
        use sbom_tools::WriterReporter;
        use sbom_tools::reports::StreamingJsonReporter;

        let reporter = StreamingJsonReporter::new();
        assert_eq!(
            WriterReporter::format(&reporter),
            sbom_tools::ReportFormat::Json,
            "StreamingJsonReporter should implement WriterReporter"
        );
    }

    #[test]
    fn test_ndjson_reporter_implements_writer_reporter() {
        use sbom_tools::WriterReporter;
        use sbom_tools::reports::NdjsonReporter;

        let reporter = NdjsonReporter::new();
        assert_eq!(
            WriterReporter::format(&reporter),
            sbom_tools::ReportFormat::Ndjson,
            "NdjsonReporter should implement WriterReporter"
        );
    }

    #[test]
    fn test_streaming_spdx3_via_reader() {
        use std::path::Path;

        // SPDX 3.0 should work through the reader path (used by streaming parser)
        let path = Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/fixtures/spdx3/minimal.spdx3.json"
        ));
        let file = std::fs::File::open(path).expect("Failed to open fixture");
        let reader = std::io::BufReader::new(file);

        let detector = sbom_tools::parsers::FormatDetector::new();
        let sbom = detector
            .parse_reader(reader)
            .expect("SPDX 3.0 should parse via reader path");

        assert_eq!(sbom.document.spec_version, "3.0.1");
        assert_eq!(sbom.component_count(), 4);
    }
}

// ============================================================================
// Sparse Assignment Matching Tests
// ============================================================================

mod sparse_assignment_tests {
    use super::*;
    use sbom_tools::model::{Component, DocumentMetadata, Ecosystem, NormalizedSbom};
    use std::time::Instant;

    /// Build a component whose canonical ID comes solely from its (unstable)
    /// format id, so two SBOMs using different format ids share *no* canonical
    /// IDs even when names/versions match — forcing the fuzzy assignment path.
    fn comp(format_id: &str, name: &str, version: &str, eco: Ecosystem) -> Component {
        let mut c = Component::new(name.to_string(), format_id.to_string())
            .with_version(version.to_string());
        c.ecosystem = Some(eco);
        c.calculate_content_hash();
        c
    }

    #[test]
    fn disjoint_canonical_ids_match_fast_and_sensibly() {
        // Two medium SBOMs describing the same packages but with regenerated
        // bom-refs (different format ids → disjoint canonical IDs). Every
        // component therefore enters fuzzy assignment.
        let names: Vec<(String, &str)> = (0..400)
            .map(|i| {
                (
                    format!("lib-{i:04}"),
                    if i % 2 == 0 { "npm" } else { "pypi" },
                )
            })
            .collect();

        let mut old = NormalizedSbom::new(DocumentMetadata::default());
        let mut new = NormalizedSbom::new(DocumentMetadata::default());
        for (i, (name, eco_str)) in names.iter().enumerate() {
            let eco = Ecosystem::from_purl_type(eco_str);
            old.add_component(comp(&format!("old-ref-{i}"), name, "1.0.0", eco.clone()));
            // Same name + ecosystem, bumped version, brand-new ref.
            new.add_component(comp(&format!("new-ref-{i}"), name, "2.0.0", eco));
        }

        // No canonical IDs are shared between the two documents.
        let shared = old
            .components
            .keys()
            .filter(|id| new.components.contains_key(*id))
            .count();
        assert_eq!(shared, 0, "test setup must have disjoint canonical IDs");

        let engine = DiffEngine::new();
        let start = Instant::now();
        let result = engine.diff(&old, &new).expect("diff should succeed");
        let elapsed = start.elapsed();

        // The dense-matrix path would effectively hang here; the sparse solver
        // must finish near-instantly. Generous bound to stay CI-stable.
        assert!(
            elapsed.as_secs() < 10,
            "fuzzy assignment took too long: {elapsed:?}"
        );

        // Same-name components should pair up as modifications, not be reported
        // as a wholesale add/remove churn.
        assert!(
            result.components.modified.len() >= 380,
            "expected nearly all 400 components matched as modified, got {}",
            result.components.modified.len()
        );
        assert!(
            result.components.added.len() <= 20,
            "expected few spurious additions, got {}",
            result.components.added.len()
        );
        assert!(
            result.components.removed.len() <= 20,
            "expected few spurious removals, got {}",
            result.components.removed.len()
        );

        // Spot-check a specific pair was matched (lib-0100 v1 → v2).
        let matched = result
            .components
            .modified
            .iter()
            .any(|change| change.name == "lib-0100");
        assert!(matched, "lib-0100 should be matched across versions");
    }

    #[test]
    fn trigram_ranking_surfaces_true_match_in_oversized_bucket() {
        // One ecosystem bucket far larger than max_candidates (100). The true
        // match for the source shares all trigrams with it; the decoys share
        // none. Without trigram ranking of Priority-1 candidates, the true
        // match could be cut by truncate(max_candidates) purely by insertion
        // order — here it is deliberately placed last.
        let mut old = NormalizedSbom::new(DocumentMetadata::default());
        old.add_component(comp("old-target", "libsignal", "1.0.0", Ecosystem::Npm));

        let mut new = NormalizedSbom::new(DocumentMetadata::default());
        // 250 decoys with names that share no trigrams with "libsignal".
        for i in 0..250 {
            new.add_component(comp(
                &format!("new-decoy-{i}"),
                &format!("zzqx{i:04}wkpv"),
                "1.0.0",
                Ecosystem::Npm,
            ));
        }
        // The real match, inserted last so insertion-order truncation would drop it.
        new.add_component(comp("new-target", "libsignal", "2.0.0", Ecosystem::Npm));

        let engine = DiffEngine::new();
        let result = engine.diff(&old, &new).expect("diff should succeed");

        let matched = result
            .components
            .modified
            .iter()
            .any(|change| change.name == "libsignal");
        assert!(
            matched,
            "trigram ranking should surface libsignal despite the oversized bucket; \
             modified={:?}, removed={}",
            result
                .components
                .modified
                .iter()
                .map(|c| c.name.as_str())
                .collect::<Vec<_>>(),
            result.components.removed.len()
        );
    }
}