complior-cli 1.0.0

AI Act Compliance Scanner & Fixer — CLI
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
#[cfg(test)]
mod tests {
    use crate::headless::format::{
        FormatOptions, format_human, format_json, format_sarif, sarif_level,
    };
    use crate::types::{
        CategoryScore, CheckResultType, ExternalToolResult, Finding, FindingExplanation,
        FrameworkScoreResult, ScanResult, ScoreBreakdown, Severity, Zone,
    };

    fn default_opts() -> FormatOptions {
        FormatOptions {
            framework_scores: None,
            quiet: false,
            prev_score: None,
        }
    }

    fn mock_scan_result() -> ScanResult {
        ScanResult {
            score: ScoreBreakdown {
                total_score: 72.0,
                zone: Zone::Yellow,
                category_scores: vec![CategoryScore {
                    category: "transparency".into(),
                    weight: 0.3,
                    score: 80.0,
                    obligation_count: 5,
                    passed_count: 4,
                }],
                critical_cap_applied: false,
                total_checks: 25,
                passed_checks: 18,
                failed_checks: 5,
                skipped_checks: 2,
                confidence_summary: None,
            },
            findings: vec![
                Finding {
                    check_id: "fria".into(),
                    r#type: CheckResultType::Fail,
                    message: "Missing FRIA document".into(),
                    severity: Severity::High,
                    obligation_id: Some("OBL-015".into()),
                    article_reference: Some("Art. 27".into()),
                    fix: Some("Create docs/FRIA.md".into()),
                    file: None,
                    line: None,
                    code_context: None,
                    fix_diff: None,
                    priority: None,
                    confidence: None,
                    confidence_level: None,
                    evidence: None,
                    explanation: None,
                    agent_id: None,
                    doc_quality: None,
                    l5_analyzed: None,
                },
                Finding {
                    check_id: "l4-bare-llm".into(),
                    r#type: CheckResultType::Fail,
                    message: "Bare LLM API call detected".into(),
                    severity: Severity::Medium,
                    obligation_id: None,
                    article_reference: Some("Art. 50(1)".into()),
                    fix: Some("Wrap with complior(client)".into()),
                    file: Some("src/chat/anthropic.ts".into()),
                    line: Some(8),
                    code_context: None,
                    fix_diff: None,
                    priority: None,
                    confidence: None,
                    confidence_level: None,
                    evidence: None,
                    explanation: None,
                    agent_id: None,
                    doc_quality: None,
                    l5_analyzed: None,
                },
            ],
            project_path: "/tmp/test-project".into(),
            scanned_at: "2026-02-19T12:00:00Z".into(),
            duration: 1234,
            files_scanned: 42,
            files_excluded: None,
            deep_analysis: None,
            l5_cost: None,
            regulation_version: None,
            tier: None,
            external_tool_results: None,
            agent_summaries: None,
            filter_context: None,
            top_actions: None,
            disclaimer: None,
        }
    }

    fn make_finding(
        check_id: &str,
        typ: CheckResultType,
        message: &str,
        severity: Severity,
    ) -> Finding {
        Finding {
            check_id: check_id.into(),
            r#type: typ,
            message: message.into(),
            severity,
            obligation_id: None,
            article_reference: None,
            fix: None,
            file: None,
            line: None,
            code_context: None,
            fix_diff: None,
            priority: None,
            confidence: None,
            confidence_level: None,
            evidence: None,
            explanation: None,
            agent_id: None,
            doc_quality: None,
            l5_analyzed: None,
        }
    }

    // ── JSON / SARIF (unchanged) ────────────────────────────────

    #[test]
    fn format_json_output() {
        let result = mock_scan_result();
        let json = format_json(&result);
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
        assert_eq!(parsed["score"]["totalScore"], 72.0);
        assert_eq!(parsed["findings"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn format_sarif_output() {
        let result = mock_scan_result();
        let sarif = format_sarif(&result);
        let parsed: serde_json::Value = serde_json::from_str(&sarif).expect("valid SARIF JSON");
        assert_eq!(parsed["version"], "2.1.0");
        let runs = parsed["runs"].as_array().unwrap();
        assert_eq!(runs.len(), 1);
        let results = runs[0]["results"].as_array().unwrap();
        assert_eq!(results.len(), 2);
        assert_eq!(results[0]["ruleId"], "fria");
        assert_eq!(results[0]["level"], "error"); // High = error
        assert_eq!(results[1]["level"], "warning"); // Medium = warning
    }

    #[test]
    fn sarif_level_mapping() {
        assert_eq!(sarif_level(&Severity::Critical), "error");
        assert_eq!(sarif_level(&Severity::High), "error");
        assert_eq!(sarif_level(&Severity::Medium), "warning");
        assert_eq!(sarif_level(&Severity::Low), "note");
        assert_eq!(sarif_level(&Severity::Info), "note");
    }

    // ── Data extraction helpers (unchanged) ─────────────────────

    #[test]
    fn project_name_via_header() {
        // project_name is tested indirectly through format_human header
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        assert!(text.contains("test-project"));
    }

    // ── New format_human tests ──────────────────────────────────

    #[test]
    fn format_human_header() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Header with version
        assert!(text.contains("Complior v"));
        assert!(text.contains("EU AI Act Compliance Scanner"));
        // Scan info
        assert!(text.contains("test-project"));
        assert!(text.contains("42 collected"));
        assert!(text.contains("L1"));
        assert!(text.contains("L4"));
    }

    #[test]
    fn format_human_score_block() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Compliance score
        assert!(text.contains("COMPLIANCE SCORE"));
        assert!(text.contains("72 / 100"));
        // Security score N/A hint when no framework_scores
        assert!(text.contains("SECURITY SCORE"));
        assert!(text.contains("N/A"));
    }

    #[test]
    fn format_human_dual_score() {
        let result = mock_scan_result();
        let opts = FormatOptions {
            framework_scores: Some(vec![
                FrameworkScoreResult {
                    framework_id: "eu-ai-act".into(),
                    framework_name: "EU AI Act 2024/1689".into(),
                    score: 72.0,
                    grade: "C".into(),
                    grade_type: "letter".into(),
                    gaps: 5,
                    total_checks: 25,
                    passed_checks: 18,
                    deadline: None,
                    categories: vec![],
                },
                FrameworkScoreResult {
                    framework_id: "owasp-llm-top10".into(),
                    framework_name: "OWASP LLM Top 10".into(),
                    score: 85.0,
                    grade: "B".into(),
                    grade_type: "letter".into(),
                    gaps: 2,
                    total_checks: 10,
                    passed_checks: 8,
                    deadline: None,
                    categories: vec![],
                },
            ]),
            quiet: false,
            prev_score: None,
        };
        let text = format_human(&result, &opts);
        assert!(text.contains("COMPLIANCE SCORE"));
        assert!(text.contains("SECURITY SCORE"));
        assert!(text.contains("85 / 100"));
        // Framework breakdown
        assert!(text.contains("Framework Breakdown"));
        assert!(text.contains("EU AI Act 2024/1689"));
        assert!(text.contains("OWASP LLM Top 10"));
    }

    #[test]
    fn format_human_findings_section() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Findings header
        assert!(text.contains("FINDINGS"));
        assert!(text.contains("2 total"));
        assert!(text.contains("1 high"));
        assert!(text.contains("1 medium"));
        // Finding details
        assert!(text.contains("HIGH"));
        assert!(text.contains("MEDIUM"));
        // Layer subgroup headers
        assert!(text.contains("L1"));
        assert!(text.contains("File Presence"));
        assert!(text.contains("L4"));
        assert!(text.contains("Code Patterns"));
        // Article references
        assert!(text.contains("Art. 27"));
        assert!(text.contains("Art. 50(1)"));
        // Labels
        assert!(text.contains("Fundamental Rights Assessment"));
        assert!(text.contains("Bare LLM API Call"));
        // Messages
        assert!(text.contains("Missing FRIA document"));
        assert!(text.contains("Bare LLM API call detected"));
        // Fix suggestions
        assert!(text.contains("Create docs/FRIA.md"));
        assert!(text.contains("Wrap with complior(client)"));
        // File location
        assert!(text.contains("src/chat/anthropic.ts:8"));
    }

    #[test]
    fn format_human_no_findings() {
        let mut result = mock_scan_result();
        result.findings.clear();
        result.score.failed_checks = 0;
        result.score.total_score = 85.0;
        let text = format_human(&result, &default_opts());
        assert!(text.contains("No compliance issues found"));
        assert!(text.contains("on track"));
    }

    #[test]
    fn format_human_layer_results() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        assert!(text.contains("Layer Results"));
        assert!(text.contains("File Presence"));
        assert!(text.contains("FAIL")); // L1 has high severity → FAIL
        assert!(text.contains("Code Patterns"));
        assert!(text.contains("WARN")); // L4 has only medium → WARN
    }

    #[test]
    fn format_human_quick_actions() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        assert!(text.contains("QUICK ACTIONS"));
        assert!(text.contains("Auto-fix available"));
        assert!(text.contains("complior fix"));
        assert!(text.contains("complior scan --deep"));
        // T-9: "complior tui" replaced with "complior" (TUI launches with no args)
        assert!(text.contains("complior"));
        assert!(text.contains("Next"));
        // T-9: "complior docs generate --missing" replaced with "complior fix --doc <type>"
        assert!(text.contains("complior fix --doc"));
    }

    #[test]
    fn format_human_deep_scan_hint_absent_when_deep() {
        let mut result = mock_scan_result();
        result.tier = Some(2);
        let text = format_human(&result, &default_opts());
        // Should NOT suggest --deep when already Tier 2
        assert!(!text.contains("complior scan --deep"));
        // Deep mode label in header
        assert!(text.contains("Deep Mode"));
    }

    #[test]
    fn format_human_critical_cap_warning() {
        let mut result = mock_scan_result();
        result.score.critical_cap_applied = true;
        result.score.total_score = 40.0; // Cap only shows when score <= 50
        let text = format_human(&result, &default_opts());
        assert!(text.contains("Score capped"));
        assert!(text.contains("critical violations"));
    }

    #[test]
    fn format_human_critical_cap_hidden_when_score_high() {
        let mut result = mock_scan_result();
        result.score.critical_cap_applied = true;
        result.score.total_score = 78.0; // Flag set but score high — cap not limiting
        let text = format_human(&result, &default_opts());
        assert!(
            !text.contains("Score capped"),
            "cap message should be hidden when score > 50"
        );
    }

    #[test]
    fn format_human_severity_counts() {
        let mut result = mock_scan_result();
        result.findings = vec![
            make_finding(
                "fria",
                CheckResultType::Fail,
                "Missing FRIA",
                Severity::Critical,
            ),
            make_finding(
                "risk-management",
                CheckResultType::Fail,
                "Missing risk mgmt",
                Severity::High,
            ),
            make_finding(
                "risk-management",
                CheckResultType::Fail,
                "Missing risk mgmt 2",
                Severity::High,
            ),
            make_finding(
                "l4-bare-llm",
                CheckResultType::Fail,
                "Bare LLM",
                Severity::Medium,
            ),
        ];
        let text = format_human(&result, &default_opts());
        assert!(text.contains("4 total"));
        assert!(text.contains("1 critical"));
        assert!(text.contains("2 high"));
        assert!(text.contains("1 medium"));
    }

    #[test]
    fn format_human_finding_limits_medium() {
        let mut result = mock_scan_result();
        result.findings.clear();
        // 8 medium findings — should only show 5
        for i in 0..8 {
            let mut f = make_finding(
                "l4-bare-llm",
                CheckResultType::Fail,
                &format!("Bare LLM instance {i}"),
                Severity::Medium,
            );
            f.fix = Some(format!("Fix {i}"));
            f.file = Some(format!("src/file{i}.ts"));
            f.line = Some(i + 1);
            result.findings.push(f);
        }
        let text = format_human(&result, &default_opts());
        // Header shows all 8
        assert!(text.contains("8 total"));
        assert!(text.contains("8 medium"));
        // But only 5 are displayed, rest hidden
        assert!(text.contains("3 medium not shown"));
    }

    #[test]
    fn format_human_low_findings_hidden() {
        let mut result = mock_scan_result();
        result.findings = vec![
            make_finding(
                "fria",
                CheckResultType::Fail,
                "Missing FRIA",
                Severity::High,
            ),
            make_finding(
                "l4-bare-llm",
                CheckResultType::Fail,
                "Bare LLM",
                Severity::Low,
            ),
        ];
        let text = format_human(&result, &default_opts());
        // Low findings are not displayed
        assert!(text.contains("1 low not shown"));
        // High finding is shown
        assert!(text.contains("HIGH"));
        // LOW severity label should NOT appear in findings section
        // (it appears in the "not shown" note only)
    }

    #[test]
    fn format_human_all_critical_high_shown() {
        let mut result = mock_scan_result();
        result.findings.clear();
        // 10 critical findings — all should be shown
        for i in 0..10 {
            result.findings.push(make_finding(
                &format!("check-{i}"),
                CheckResultType::Fail,
                &format!("Critical issue {i}"),
                Severity::Critical,
            ));
        }
        let text = format_human(&result, &default_opts());
        assert!(text.contains("10 total"));
        assert!(text.contains("10 critical"));
        // All 10 findings should be shown (all critical messages present)
        assert!(text.contains("Critical issue 9"));
        // No "not shown" note
        assert!(!text.contains("not shown"));
    }

    #[test]
    fn format_human_layer_subgrouping() {
        let mut result = mock_scan_result();
        result.findings = vec![
            make_finding(
                "fria",
                CheckResultType::Fail,
                "L1 issue A",
                Severity::Critical,
            ),
            make_finding(
                "documentation",
                CheckResultType::Fail,
                "L1 issue B",
                Severity::High,
            ),
            make_finding(
                "l4-bare-llm",
                CheckResultType::Fail,
                "L4 issue",
                Severity::Medium,
            ),
            make_finding("l2-fria", CheckResultType::Fail, "L2 issue", Severity::High),
        ];
        let text = format_human(&result, &default_opts());
        // Layer subgroup headers should appear
        assert!(text.contains("L1"));
        assert!(text.contains("File Presence"));
        assert!(text.contains("L2"));
        assert!(text.contains("Document Structure"));
        assert!(text.contains("L4"));
        assert!(text.contains("Code Patterns"));
        // L1 group should come before L2, L2 before L4
        let l1_pos = text.find("File Presence").unwrap();
        let l2_pos = text.find("Document Structure").unwrap();
        let l4_pos = text.find("Code Patterns").unwrap();
        assert!(l1_pos < l2_pos);
        assert!(l2_pos < l4_pos);
    }

    #[test]
    fn format_human_clean_fix_message() {
        let mut result = mock_scan_result();
        result.findings = vec![Finding {
            check_id: "l4-bare-llm".into(),
            r#type: CheckResultType::Fail,
            message: "Bare LLM call".into(),
            severity: Severity::High,
            obligation_id: None,
            article_reference: None,
            fix: Some("Fix complior.injection: Validate user input before LLM call".into()),
            file: None,
            line: None,
            code_context: None,
            fix_diff: None,
            priority: None,
            confidence: None,
            confidence_level: None,
            evidence: None,
            explanation: None,
            agent_id: None,
            doc_quality: None,
            l5_analyzed: None,
        }];
        let text = format_human(&result, &default_opts());
        // Engine prefix should be stripped
        assert!(!text.contains("Fix complior.injection:"));
        // Clean message should remain
        assert!(text.contains("Validate user input before LLM call"));
    }

    #[test]
    fn format_human_layer_group_headers() {
        let mut result = mock_scan_result();
        result.findings = vec![
            make_finding("fria", CheckResultType::Fail, "L1 finding", Severity::High),
            make_finding(
                "l2-fria",
                CheckResultType::Fail,
                "L2 finding",
                Severity::High,
            ),
            make_finding(
                "l3-missing-bias-testing",
                CheckResultType::Fail,
                "L3 finding",
                Severity::High,
            ),
            make_finding(
                "l4-bare-llm",
                CheckResultType::Fail,
                "L4 finding",
                Severity::High,
            ),
            make_finding(
                "l4-nhi-api-key",
                CheckResultType::Fail,
                "NHI finding",
                Severity::High,
            ),
            make_finding(
                "cross-doc-code-mismatch",
                CheckResultType::Fail,
                "Cross finding",
                Severity::High,
            ),
        ];
        let text = format_human(&result, &default_opts());
        // Layer group headers with labels
        assert!(text.contains("L1") && text.contains("File Presence"));
        assert!(text.contains("L2") && text.contains("Document Structure"));
        assert!(text.contains("L3") && text.contains("Dependencies"));
        assert!(text.contains("L4") && text.contains("Code Patterns"));
        assert!(text.contains("NHI") && text.contains("Secrets"));
        assert!(text.contains("CROSS") && text.contains("Cross-Layer"));
    }

    #[test]
    fn format_human_deep_mode_grouping() {
        let mut result = mock_scan_result();
        result.tier = Some(2);
        result.external_tool_results = Some(vec![ExternalToolResult {
            tool: "semgrep".into(),
            version: "1.0.0".into(),
            findings: vec![],
            duration: 1000,
            exit_code: 0,
            error: None,
        }]);
        result.findings = vec![
            make_finding(
                "fria",
                CheckResultType::Fail,
                "Base scan finding",
                Severity::High,
            ),
            make_finding(
                "ext-semgrep-unsafe-deser",
                CheckResultType::Fail,
                "Deep finding",
                Severity::High,
            ),
        ];
        let text = format_human(&result, &default_opts());
        // Deep mode grouping (uppercase)
        assert!(text.contains("NEW IN --DEEP"));
        assert!(text.contains("FROM BASE SCAN"));
        // Deep findings grouped under L4+ layer header
        assert!(text.contains("Ext. Code Analysis"));
    }

    #[test]
    fn format_human_deep_mode_layers() {
        let mut result = mock_scan_result();
        result.tier = Some(2);
        result.findings = vec![
            make_finding("fria", CheckResultType::Fail, "Base", Severity::High),
            make_finding(
                "ext-semgrep-unsafe-deser",
                CheckResultType::Fail,
                "Semgrep finding",
                Severity::High,
            ),
            make_finding(
                "ext-bandit-B301",
                CheckResultType::Fail,
                "Bandit finding",
                Severity::High,
            ),
        ];
        let text = format_human(&result, &default_opts());
        // Header shows tool names for deep layers
        assert!(text.contains("L4+ Semgrep"));
        assert!(text.contains("L4+ Bandit"));
        assert!(text.contains("L3+ ModelScan"));
        assert!(text.contains("NHI+ detect-secrets"));
        // Layer Results section uses descriptive labels
        assert!(text.contains("Ext. Code Analysis"));
        // Scan info shows deep mode
        assert!(text.contains("Deep Mode"));
    }

    #[test]
    fn format_human_pass_findings_layer_status() {
        let mut result = mock_scan_result();
        result.findings = vec![make_finding(
            "l4-disclosure",
            CheckResultType::Pass,
            "Disclosure found",
            Severity::Info,
        )];
        result.score.failed_checks = 0;
        result.score.total_score = 100.0;
        let text = format_human(&result, &default_opts());
        // Layer Results should show PASS for L4
        assert!(text.contains("Layer Results"));
        assert!(text.contains("PASS"));
        assert!(text.contains("Code Patterns"));
    }

    #[test]
    fn format_human_next_hint_critical() {
        let mut result = mock_scan_result();
        result.findings = vec![
            make_finding(
                "fria",
                CheckResultType::Fail,
                "Critical",
                Severity::Critical,
            ),
            make_finding(
                "risk-management",
                CheckResultType::Fail,
                "Also critical",
                Severity::Critical,
            ),
        ];
        let text = format_human(&result, &default_opts());
        assert!(text.contains("fix 2 critical issues"));
    }

    #[test]
    fn format_human_next_hint_high() {
        let mut result = mock_scan_result();
        result.findings = vec![make_finding(
            "fria",
            CheckResultType::Fail,
            "High",
            Severity::High,
        )];
        let text = format_human(&result, &default_opts());
        assert!(text.contains("fix 1 high-severity issue"));
    }

    #[test]
    fn format_human_next_hint_compliant() {
        let mut result = mock_scan_result();
        result.findings.clear();
        result.score.total_score = 90.0;
        result.score.failed_checks = 0;
        let text = format_human(&result, &default_opts());
        assert!(text.contains("on track for EU AI Act compliance"));
    }

    #[test]
    fn format_human_framework_breakdown_bar_chart() {
        let mut result = mock_scan_result();
        // T-5 fix: framework breakdown uses compliance score (72.0), not fw.score (60.0)
        result.score.total_score = 72.0;
        let opts = FormatOptions {
            framework_scores: Some(vec![FrameworkScoreResult {
                framework_id: "eu-ai-act".into(),
                framework_name: "EU AI Act 2024/1689".into(),
                // Framework-specific score differs from compliance score
                score: 60.0,
                grade: "D".into(),
                grade_type: "letter".into(),
                gaps: 10,
                total_checks: 25,
                passed_checks: 15,
                deadline: None,
                categories: vec![],
            }]),
            quiet: false,
            prev_score: None,
        };
        let text = format_human(&result, &opts);
        assert!(text.contains("Framework Breakdown"));
        assert!(text.contains("EU AI Act 2024/1689"));
        // T-5: Bar + number now use compliance score (72), not framework score (60)
        assert!(
            text.contains("72 / 100"),
            "Framework breakdown should use compliance score 72 not fw.score 60"
        );
        // Bar chart characters (uses ASCII fallback in test/CI environment)
        use crate::headless::format::colors::{bar_empty, bar_filled};
        assert!(text.contains(bar_filled()));
        assert!(text.contains(bar_empty()));
    }

    #[test]
    fn format_human_no_framework_breakdown_without_scores() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // No framework breakdown when no framework_scores provided
        assert!(!text.contains("Framework Breakdown"));
    }

    #[test]
    fn format_human_generate_docs_action() {
        let mut result = mock_scan_result();
        result.findings = vec![
            // L1 finding (missing doc) triggers "Generate docs" action
            make_finding(
                "fria",
                CheckResultType::Fail,
                "Missing FRIA",
                Severity::High,
            ),
        ];
        let text = format_human(&result, &default_opts());
        assert!(text.contains("Generate docs"));
        // T-9: "complior docs generate --missing" replaced with "complior fix --doc <type>"
        assert!(
            text.contains("complior fix --doc"),
            "Generate docs action should reference 'complior fix --doc <type>'"
        );
    }

    #[test]
    fn format_human_separator_width() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Dynamic separator uses h_line() repeated to display_width()
        use crate::headless::format::colors::h_line;
        use crate::headless::format::layers::display_width;
        let sep = h_line().repeat(display_width());
        assert!(text.contains(&sep));
    }

    #[test]
    fn format_human_finding_with_article() {
        let mut result = mock_scan_result();
        result.findings = vec![Finding {
            check_id: "fria".into(),
            r#type: CheckResultType::Fail,
            message: "Missing FRIA document".into(),
            severity: Severity::High,
            obligation_id: None,
            article_reference: Some("Art. 27".into()),
            fix: Some("Create docs/FRIA.md".into()),
            file: None,
            line: None,
            code_context: None,
            fix_diff: None,
            priority: None,
            confidence: None,
            confidence_level: None,
            evidence: None,
            explanation: None,
            agent_id: None,
            doc_quality: None,
            l5_analyzed: None,
        }];
        let text = format_human(&result, &default_opts());
        // Article and label combined on same line
        assert!(text.contains("Art. 27"));
        assert!(text.contains("Fundamental Rights Assessment"));
    }

    #[test]
    fn format_human_finding_article_from_explanation() {
        let mut result = mock_scan_result();
        result.findings = vec![Finding {
            check_id: "fria".into(),
            r#type: CheckResultType::Fail,
            message: "Missing FRIA".into(),
            severity: Severity::High,
            obligation_id: None,
            article_reference: None,
            fix: None,
            file: None,
            line: None,
            code_context: None,
            fix_diff: None,
            priority: None,
            confidence: None,
            confidence_level: None,
            evidence: None,
            explanation: Some(FindingExplanation {
                article: "Art. 27".into(),
                penalty: String::new(),
                deadline: String::new(),
                business_impact: String::new(),
            }),
            agent_id: None,
            doc_quality: None,
            l5_analyzed: None,
        }];
        let text = format_human(&result, &default_opts());
        // Article from explanation fallback
        assert!(text.contains("Art. 27"));
    }

    #[test]
    fn format_human_ext_finding_label() {
        let mut result = mock_scan_result();
        result.tier = Some(2);
        result.findings = vec![make_finding(
            "ext-bandit-B301",
            CheckResultType::Fail,
            "Pickle issue",
            Severity::High,
        )];
        let text = format_human(&result, &default_opts());
        // ext_check_label should provide nice label
        assert!(text.contains("Unsafe Pickle Usage"));
    }

    // ── New tests for CLI output spec compliance ──────────────────

    #[test]
    fn format_human_finding_ids_hidden() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Finding IDs are hidden from human output (kept in JSON/SARIF)
        assert!(!text.contains("F-001"));
        assert!(!text.contains("F-002"));
    }

    #[test]
    fn format_human_layer_tag_in_finding() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Layer tags should appear in finding lines
        assert!(text.contains("[L1]") || text.contains("[L4]"));
    }

    #[test]
    fn format_human_grade_in_score() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Grade letter should appear near score (72 = C)
        assert!(text.contains("C"));
    }

    #[test]
    fn format_human_elapsed_time() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Elapsed time should be displayed (1234ms = 1.2s)
        assert!(text.contains("Elapsed"));
        assert!(text.contains("1.2s"));
    }

    #[test]
    fn format_human_quiet_mode() {
        let mut result = mock_scan_result();
        result.findings = vec![
            make_finding(
                "l1-crit",
                CheckResultType::Fail,
                "Critical issue",
                Severity::Critical,
            ),
            make_finding(
                "l4-med",
                CheckResultType::Fail,
                "Medium issue",
                Severity::Medium,
            ),
        ];
        let opts = FormatOptions {
            framework_scores: None,
            quiet: true,
            prev_score: None,
        };
        let text = format_human(&result, &opts);
        // Quiet mode: shows critical findings
        assert!(text.contains("CRITICAL FINDINGS"));
        assert!(text.contains("Critical issue"));
        // Quiet mode: does NOT show quick actions or framework breakdown
        assert!(!text.contains("QUICK ACTIONS"));
        assert!(!text.contains("Framework Breakdown"));
    }

    #[test]
    fn format_human_security_na_hint() {
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        // Security N/A when no OWASP/MITRE framework data
        assert!(text.contains("SECURITY SCORE"));
        assert!(text.contains("N/A"));
        assert!(text.contains("complior eval --security"));
    }

    #[test]
    fn format_human_docs_command() {
        // V1-M30.9 W-1 spec supersession: removed `complior docs --article N`
        // hint from format/human.rs because the `complior docs` subcommand does
        // NOT exist in v1.0.0 (only `complior fix --doc <type>` is valid).
        // The test now ASSERTS THE OPPOSITE — invalid hint must not appear.
        // Article reference is still shown in finding metadata above the fix
        // hint; the fix hint itself is `complior fix --check-id` which IS valid.
        let result = mock_scan_result();
        let text = format_human(&result, &default_opts());
        assert!(
            !text.contains("complior docs --article"),
            "format_human MUST NOT emit invalid `complior docs --article N` hint (V1-M30.9 W-1)",
        );
        // The valid actionable hint must be present somewhere
        assert!(
            text.contains("complior fix"),
            "format_human should emit valid `complior fix` hint"
        );
    }

    #[test]
    fn format_human_prev_score_delta() {
        let result = mock_scan_result();
        let opts = FormatOptions {
            framework_scores: None,
            quiet: false,
            prev_score: Some(85.0),
        };
        let text = format_human(&result, &opts);
        // Previous score delta displayed
        assert!(text.contains("was 85"));
    }

    #[test]
    fn format_human_severity_icons_distinct() {
        // Critical and High should have different icons
        use crate::headless::format::colors::severity_icon;
        let crit = severity_icon(&Severity::Critical);
        let high = severity_icon(&Severity::High);
        assert_ne!(crit, high, "Critical and High should have different icons");
    }

    #[test]
    fn format_json_has_grade() {
        let result = mock_scan_result();
        let json_text = format_json(&result);
        let v: serde_json::Value = serde_json::from_str(&json_text).unwrap();
        let grade = v.get("grade").expect("grade object should exist");
        assert_eq!(grade.get("compliance").unwrap().as_str().unwrap(), "C");
    }

    #[test]
    fn format_json_has_finding_ids() {
        let result = mock_scan_result();
        let json_text = format_json(&result);
        let v: serde_json::Value = serde_json::from_str(&json_text).unwrap();
        let findings = v.get("findings").unwrap().as_array().unwrap();
        // All fail findings should have IDs
        let ids: Vec<&str> = findings
            .iter()
            .filter_map(|f| f.get("id").and_then(|v| v.as_str()))
            .collect();
        assert!(!ids.is_empty());
        assert!(ids.contains(&"F-001"));
    }

    #[test]
    fn format_json_has_obligation_ids() {
        let result = mock_scan_result();
        let json_text = format_json(&result);
        let v: serde_json::Value = serde_json::from_str(&json_text).unwrap();
        let findings = v.get("findings").unwrap().as_array().unwrap();
        // Finding with obligationId should also have obligationIds array
        let has_ids = findings
            .iter()
            .any(|f| f.get("obligationIds").and_then(|v| v.as_array()).is_some());
        assert!(
            has_ids,
            "At least one finding should have obligationIds array"
        );
    }

    #[test]
    fn resolve_grade_boundaries() {
        use crate::headless::format::colors::resolve_grade;
        assert_eq!(resolve_grade(95.0), "A");
        assert_eq!(resolve_grade(90.0), "A");
        assert_eq!(resolve_grade(89.9), "B");
        assert_eq!(resolve_grade(75.0), "B");
        assert_eq!(resolve_grade(74.9), "C");
        assert_eq!(resolve_grade(60.0), "C");
        assert_eq!(resolve_grade(59.9), "D");
        assert_eq!(resolve_grade(40.0), "D");
        assert_eq!(resolve_grade(39.9), "F");
        assert_eq!(resolve_grade(0.0), "F");
    }

    #[test]
    fn cli_parse_quiet_flag() {
        use crate::cli::Cli;
        use clap::Parser;
        let cli = Cli::parse_from(["complior", "scan", "--quiet"]);
        match cli.command {
            Some(crate::cli::Command::Scan { quiet, .. }) => assert!(quiet),
            _ => panic!("Expected Scan command"),
        }
    }

    #[test]
    fn cli_parse_quiet_short() {
        use crate::cli::Cli;
        use clap::Parser;
        let cli = Cli::parse_from(["complior", "scan", "-q"]);
        match cli.command {
            Some(crate::cli::Command::Scan { quiet, .. }) => assert!(quiet),
            _ => panic!("Expected Scan command"),
        }
    }

    #[test]
    fn cli_parse_no_color_flag() {
        use crate::cli::Cli;
        use clap::Parser;
        let cli = Cli::parse_from(["complior", "--no-color", "scan"]);
        assert!(cli.no_color);
    }

    #[test]
    fn format_human_large_project_warning() {
        let mut result = mock_scan_result();
        result.files_scanned = 600;
        let text = format_human(&result, &default_opts());
        assert!(text.contains("Large project"));
        assert!(text.contains(".compliorignore"));
    }

    #[test]
    fn format_human_files_excluded() {
        let mut result = mock_scan_result();
        result.files_excluded = Some(15);
        let text = format_human(&result, &default_opts());
        assert!(text.contains("15 excluded"));
    }

    /// V1-M17: Quiet mode must produce ≤5 non-empty lines (score block only).
    /// No header, no scan info, no layer list — just score for CI consumption.
    #[test]
    fn format_human_quiet_compact() {
        let result = mock_scan_result();
        let opts = FormatOptions {
            framework_scores: None,
            quiet: true,
            prev_score: None,
        };
        let text = format_human(&result, &opts);
        let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect();
        // Quiet mode: ≤5 non-empty lines (score block only, no header/info)
        assert!(
            lines.len() <= 5,
            "Quiet mode should produce ≤5 non-empty lines, got {}: {lines:?}",
            lines.len(),
        );
        // Must NOT contain header or scan info
        assert!(
            !text.contains("Complior v"),
            "Quiet mode should not show header"
        );
        assert!(
            !text.contains("Scanning"),
            "Quiet mode should not show scan info"
        );
        assert!(
            !text.contains("Elapsed"),
            "Quiet mode should not show elapsed time"
        );
        assert!(
            !text.contains("Layers"),
            "Quiet mode should not show layer list"
        );
        // Must still contain the score
        assert!(
            text.contains("COMPLIANCE SCORE"),
            "Quiet mode must show score"
        );
    }

    #[test]
    fn sort_findings_full_order() {
        use crate::headless::format::layers::sort_findings_full;
        let f1 = make_finding("l4-bare", CheckResultType::Fail, "m1", Severity::Medium);
        let f2 = make_finding("l1-risk", CheckResultType::Fail, "m2", Severity::Critical);
        let f3 = make_finding("l2-fria", CheckResultType::Fail, "m3", Severity::High);
        let mut refs: Vec<&Finding> = vec![&f1, &f2, &f3];
        sort_findings_full(&mut refs);
        // Critical first, then High, then Medium
        assert_eq!(refs[0].severity, Severity::Critical);
        assert_eq!(refs[1].severity, Severity::High);
        assert_eq!(refs[2].severity, Severity::Medium);
    }

    // ── B-02: --fail-on works outside --ci block ─────────────────────────────

    /// Extract exit code from scan output by checking for "FAIL" prefix.
    fn scan_exit_code_from_text(text: &str) -> i32 {
        if text.contains("FAIL:") { 2 } else { 0 }
    }

    fn make_finding_full(check_id: &str, severity: Severity) -> Finding {
        Finding {
            check_id: check_id.into(),
            r#type: CheckResultType::Fail,
            message: format!("Test finding {check_id}"),
            severity,
            obligation_id: None,
            article_reference: None,
            fix: None,
            file: None,
            line: None,
            code_context: None,
            fix_diff: None,
            priority: None,
            confidence: None,
            confidence_level: None,
            evidence: None,
            explanation: None,
            agent_id: None,
            doc_quality: None,
            l5_analyzed: None,
        }
    }

    /// T-4: `scan --fail-on medium` exits 2 WITHOUT --ci flag (B-02 CRITICAL).
    /// Before the fix, `--fail-on` was inside `if ci { }` so it was silently ignored.
    #[test]
    fn scan_fail_on_medium_exits_2_without_ci() {
        use crate::cli::SeverityLevel;

        let mut result = mock_scan_result();
        // Override findings to have exactly 1 medium severity finding
        result.findings = vec![make_finding_full("test-medium", Severity::Medium)];

        let fail_on = Some(SeverityLevel::Medium);
        let _ci = false; // NO --ci flag

        // Simulate the exit-code logic from run_headless_scan (lines 396-433)
        let exit_code = if let Some(level) = fail_on {
            let has_severity = result.findings.iter().any(|f| match level {
                SeverityLevel::Critical => matches!(f.severity, Severity::Critical),
                SeverityLevel::High => matches!(f.severity, Severity::Critical | Severity::High),
                SeverityLevel::Medium => {
                    matches!(
                        f.severity,
                        Severity::Critical | Severity::High | Severity::Medium
                    )
                }
                SeverityLevel::Low => {
                    matches!(
                        f.severity,
                        Severity::Critical | Severity::High | Severity::Medium | Severity::Low
                    )
                }
            });
            if has_severity {
                2 // FAIL exit code
            } else {
                0
            }
        } else {
            0
        };

        // MUST exit 2 when medium finding present, even without --ci
        assert_eq!(
            exit_code, 2,
            "--fail-on medium must exit 2 without --ci when medium severity finding exists"
        );
    }

    /// T-4: `scan --fail-on low` exits 2 WITHOUT --ci flag.
    #[test]
    fn scan_fail_on_low_exits_2_without_ci() {
        use crate::cli::SeverityLevel;

        let mut result = mock_scan_result();
        result.findings = vec![make_finding_full("test-low", Severity::Low)];

        let fail_on = Some(SeverityLevel::Low);
        let exit_code = if let Some(level) = fail_on {
            let has_severity = result.findings.iter().any(|f| match level {
                SeverityLevel::Critical => matches!(f.severity, Severity::Critical),
                SeverityLevel::High => matches!(f.severity, Severity::Critical | Severity::High),
                SeverityLevel::Medium => {
                    matches!(
                        f.severity,
                        Severity::Critical | Severity::High | Severity::Medium
                    )
                }
                SeverityLevel::Low => {
                    matches!(
                        f.severity,
                        Severity::Critical | Severity::High | Severity::Medium | Severity::Low
                    )
                }
            });
            if has_severity { 2 } else { 0 }
        } else {
            0
        };

        assert_eq!(
            exit_code, 2,
            "--fail-on low must exit 2 without --ci when low severity finding exists"
        );
    }

    /// T-4: `scan --fail-on critical` exits 0 when only medium/low findings exist.
    #[test]
    fn scan_fail_on_critical_passes_when_only_medium_findings() {
        use crate::cli::SeverityLevel;

        let mut result = mock_scan_result();
        result.findings = vec![
            make_finding_full("test-medium", Severity::Medium),
            make_finding_full("test-low", Severity::Low),
        ];

        let fail_on = Some(SeverityLevel::Critical);
        let exit_code = if let Some(level) = fail_on {
            let has_severity = result.findings.iter().any(|f| match level {
                SeverityLevel::Critical => matches!(f.severity, Severity::Critical),
                SeverityLevel::High => matches!(f.severity, Severity::Critical | Severity::High),
                SeverityLevel::Medium => {
                    matches!(
                        f.severity,
                        Severity::Critical | Severity::High | Severity::Medium
                    )
                }
                SeverityLevel::Low => {
                    matches!(
                        f.severity,
                        Severity::Critical | Severity::High | Severity::Medium | Severity::Low
                    )
                }
            });
            if has_severity { 2 } else { 0 }
        } else {
            0
        };

        assert_eq!(
            exit_code, 0,
            "--fail-on critical must exit 0 when no critical severity findings exist"
        );
    }

    /// T-4: `scan --fail-on high` exits 2 for HIGH severity (includes critical).
    #[test]
    fn scan_fail_on_high_exits_2_for_critical_findings() {
        use crate::cli::SeverityLevel;

        let mut result = mock_scan_result();
        result.findings = vec![make_finding_full("test-critical", Severity::Critical)];

        let fail_on = Some(SeverityLevel::High);
        let exit_code = if let Some(level) = fail_on {
            let has_severity = result.findings.iter().any(|f| match level {
                SeverityLevel::Critical => matches!(f.severity, Severity::Critical),
                SeverityLevel::High => matches!(f.severity, Severity::Critical | Severity::High),
                SeverityLevel::Medium => {
                    matches!(
                        f.severity,
                        Severity::Critical | Severity::High | Severity::Medium
                    )
                }
                SeverityLevel::Low => {
                    matches!(
                        f.severity,
                        Severity::Critical | Severity::High | Severity::Medium | Severity::Low
                    )
                }
            });
            if has_severity { 2 } else { 0 }
        } else {
            0
        };

        assert_eq!(
            exit_code, 2,
            "--fail-on high must exit 2 when critical severity finding exists"
        );
    }

    // ── T-5: Score consistency ────────────────────────────────────────────────

    /// T-5: Framework breakdown bar width must use compliance score (total_score),
    /// not fw.score, so bar and number are visually consistent.
    #[test]
    fn framework_breakdown_uses_compliance_score_not_framework_score() {
        let mut result = mock_scan_result();
        // Override compliance score to 72.0
        result.score.total_score = 72.0;
        let opts = FormatOptions {
            framework_scores: Some(vec![FrameworkScoreResult {
                framework_id: "eu-ai-act".into(),
                framework_name: "EU AI Act 2024/1689".into(),
                // Framework-specific score (e.g. unweighted) is DIFFERENT from compliance score
                score: 82.0,
                grade: "B".into(),
                grade_type: "letter".into(),
                gaps: 5,
                total_checks: 25,
                passed_checks: 18,
                deadline: None,
                categories: vec![],
            }]),
            quiet: false,
            prev_score: None,
        };
        let text = format_human(&result, &opts);

        // Bar width for score=72 → 72/100 * BAR_WIDTH bars filled
        // Before fix: fw.score=82 → bar would use 82 bars
        // After fix: compliance score=72 → bar uses 72 bars
        // We verify that "82" appears numerically (the framework score label)
        // and the bar is generated from the compliance score (72).
        // The simplest check: the framework name + "82.0" string is NOT in the bar
        // (bar uses compliance score 72 which rounds differently).
        assert!(
            text.contains("EU AI Act 2024/1689"),
            "Framework breakdown must show EU AI Act framework"
        );
        // Verify the text contains the compliance score used in the bar
        assert!(
            text.contains("72"),
            "Framework breakdown bar text should reflect compliance score 72, not framework 82"
        );
    }

    /// T-5: Both COMPLIANCE SCORE and Framework Breakdown show the same score number.
    #[test]
    fn compliance_score_matches_framework_breakdown_number() {
        let mut result = mock_scan_result();
        result.score.total_score = 85.0;
        let opts = FormatOptions {
            framework_scores: Some(vec![FrameworkScoreResult {
                framework_id: "eu-ai-act".into(),
                framework_name: "EU AI Act 2024/1689".into(),
                score: 85.0, // Same as compliance score
                grade: "B".into(),
                grade_type: "letter".into(),
                gaps: 3,
                total_checks: 20,
                passed_checks: 17,
                deadline: None,
                categories: vec![],
            }]),
            quiet: false,
            prev_score: None,
        };
        let text = format_human(&result, &opts);
        // Both should show 85
        let score_occurrences = text.matches("85").count();
        assert!(
            score_occurrences >= 2,
            "Both COMPLIANCE SCORE and Framework Breakdown should display 85, found {score_occurrences} occurrences"
        );
    }

    // ── T-10: Weight display (U-01) ─────────────────────────────────────────

    /// T-10: Category weight display must be in range 0-100 (percentage).
    /// If weight is already expressed as percentage (e.g. 9.0), display as-is.
    /// The E2E test showed "weight 900%" — this happens when weight=9.0 is
    /// multiplied by 100 (9.0 * 100 = 900). Fix: display `weight.round() as usize`.
    #[test]
    fn weight_display_is_percentage_0_to_100() {
        // Simulate the weight calculation from status.rs render_categories()
        // If engine sends weight already as percentage (0-100 range):
        let weight_as_percentage_cases = [9.0_f64, 13.0_f64, 25.0_f64, 50.0_f64, 100.0_f64];
        for weight in weight_as_percentage_cases {
            let weight_pct = weight.round() as usize;
            assert!(
                weight_pct <= 100,
                "Weight {weight} rounded to {weight_pct}% must be ≤ 100"
            );
        }

        // If weight is 0-1 fraction (e.g. 0.09 = 9%):
        let weight_as_fraction_cases = [0.09_f64, 0.13_f64, 0.25_f64, 0.50_f64, 1.0_f64];
        for weight in weight_as_fraction_cases {
            let weight_pct = (weight * 100.0).round() as usize;
            assert!(
                weight_pct <= 100,
                "Weight fraction {weight} converted to {weight_pct}% must be ≤ 100"
            );
        }

        // Edge cases
        assert_eq!(0.0_f64 as usize, 0);
        assert_eq!(100.0_f64 as usize, 100);
        assert_eq!((0.001_f64 * 100.0).round() as usize, 0); // rounds down
    }

    // ── T-12: Protocol hints (U-05) ─────────────────────────────────────────

    /// T-12: Protocol hints (openai://, anthropic://, ollama://) are normalized
    /// to valid HTTP URLs before being sent to the engine. This enables
    /// `complior eval openai://localhost:4000` which would otherwise fail
    /// with "must be HTTP(S) URL" validation.
    #[test]
    fn protocol_hints_normalized_to_http() {
        // Simulate the normalization logic from main.rs
        fn normalize(target_raw: &str) -> String {
            target_raw
                .strip_prefix("openai://")
                .or_else(|| target_raw.strip_prefix("anthropic://"))
                .or_else(|| target_raw.strip_prefix("ollama://"))
                .map_or_else(
                    || target_raw.to_string(),
                    |stripped| {
                        if stripped.starts_with("http://") || stripped.starts_with("https://") {
                            stripped.to_string()
                        } else {
                            format!("http://{stripped}")
                        }
                    },
                )
        }

        // openai://localhost:4000 → http://localhost:4000
        assert_eq!(
            normalize("openai://localhost:4000"),
            "http://localhost:4000"
        );

        // openai://http://localhost:4000 → http://localhost:4000
        assert_eq!(
            normalize("openai://http://localhost:4000"),
            "http://localhost:4000"
        );

        // anthropic://api.anthropic.com → http://api.anthropic.com
        assert_eq!(
            normalize("anthropic://api.anthropic.com"),
            "http://api.anthropic.com"
        );

        // ollama://localhost:11434 → http://localhost:11434
        assert_eq!(
            normalize("ollama://localhost:11434"),
            "http://localhost:11434"
        );

        // http://localhost:4000 → unchanged
        assert_eq!(normalize("http://localhost:4000"), "http://localhost:4000");

        // https://api.openai.com/v1/chat → unchanged
        assert_eq!(
            normalize("https://api.openai.com/v1/chat"),
            "https://api.openai.com/v1/chat"
        );

        // No protocol → unchanged
        assert_eq!(normalize("localhost:4000"), "localhost:4000"); // no http prefix
    }

    /// V1-M20 / TD-35: RED test — no `#[allow(dead_code)] // TODO(T10)` markers must
    /// remain in cli/src/. Either responsive widget selection is wired, or the
    /// stale fields are removed.
    ///
    /// Architecture requirement: dead code is technical debt; if a field is unused,
    /// either implement the feature that uses it or delete the field. `TODO(T10)`
    /// markers were carried over from S03 and must be resolved before v1.0.0 release.
    #[test]
    fn no_dead_code_markers() {
        use std::fs;
        use std::path::Path;

        // Only flag REAL `#[allow(dead_code)]` annotations bearing the
        // `TODO(T10)` marker — not docstring/comment mentions of the marker
        // (this very test references TD-35 in its docs).
        fn scan_dir(dir: &Path, hits: &mut Vec<String>) {
            if let Ok(entries) = fs::read_dir(dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_dir() {
                        if path.file_name().is_some_and(|n| n == "target") {
                            continue;
                        }
                        scan_dir(&path, hits);
                    } else if path.extension().is_some_and(|e| e == "rs") {
                        if let Ok(content) = fs::read_to_string(&path) {
                            for (i, line) in content.lines().enumerate() {
                                let trimmed = line.trim_start();
                                // Match: `#[allow(dead_code)] // TODO(T10)…`
                                let is_allow_dead = trimmed.starts_with("#[allow(dead_code)]")
                                    || trimmed.starts_with("#[ allow ( dead_code ) ]");
                                if is_allow_dead && line.contains("TODO(T10)") {
                                    hits.push(format!("{}:{}", path.display(), i + 1));
                                }
                            }
                        }
                    }
                }
            }
        }

        let cli_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        let mut hits = Vec::new();
        scan_dir(&cli_src, &mut hits);

        assert!(
            hits.is_empty(),
            "TD-35: Found {} `#[allow(dead_code)]` lines tagged TODO(T10) — must be resolved (implement OR remove). Locations:\n  {}",
            hits.len(),
            hits.join("\n  "),
        );
    }

    // ── V1-M22 / B-1 (B-3): passport notify subcommand ──────────

    /// V1-M22: `complior passport notify <agent>` must be a recognized subcommand.
    /// Current state (V1-M21 discovery): "error: unrecognized subcommand 'notify'".
    ///
    /// Spec: PassportAction enum in cli.rs must have a variant named `Notify`.
    /// Source-level test (not type-level) so this file still compiles during RED.
    #[test]
    fn passport_notify_variant_in_cli_source() {
        use std::fs;
        use std::path::Path;

        let cli_rs = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("cli.rs");
        let content = fs::read_to_string(&cli_rs).expect("cli.rs readable");

        // Find the PassportAction enum block
        let start = content
            .find("pub enum PassportAction")
            .expect("PassportAction enum must exist");
        let tail = &content[start..];
        let end = tail.find("\n}\n").expect("enum has closing brace");
        let enum_body = &tail[..end];

        assert!(
            enum_body.contains("Notify"),
            "V1-M22 B-1: PassportAction enum must have `Notify` variant. \
             Current enum body:\n{enum_body}"
        );
    }

    // ── V1-M22 / D-1 (U-2): passport export format alias ────────

    /// V1-M22: `--format aiuc1` should be accepted as alias for `aiuc-1`.
    /// Dev can fix either by clap value_parser alias or by normalizing in handler.
    /// Source-level spec: cli.rs should document/configure `aiuc1` alongside `aiuc-1`.
    #[test]
    fn passport_export_format_supports_aiuc1_alias() {
        use std::fs;
        use std::path::Path;

        let cli_rs = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("cli.rs");
        let content = fs::read_to_string(&cli_rs).expect("cli.rs readable");

        // Either:
        //   - clap alias: #[arg(value_parser = ..., alias = "aiuc1")]  OR
        //   - documented both: "aiuc-1, aiuc1" in help
        //   - value_parser list containing both "aiuc-1" and "aiuc1"
        let has_both_forms = content.contains("\"aiuc1\"") && content.contains("\"aiuc-1\"");
        let has_alias_attr =
            content.contains("alias = \"aiuc1\"") || content.contains("aliases = &[\"aiuc1\"]");

        assert!(
            has_both_forms || has_alias_attr,
            "V1-M22 D-1: cli.rs must accept `aiuc1` as alias for `aiuc-1`. \
             Expected either both strings or #[arg(alias = \"aiuc1\")] in PassportAction::Export."
        );
    }

    // ── V1-M22 / C-3: ISO 42001 removed from Rust CLI ───────────

    /// V1-M22: zero `iso42001` references in cli/src/. User decision:
    /// ISO 42001 deferred, code preserved in `archive/iso-42001` branch.
    #[test]
    fn no_iso42001_references_in_cli() {
        use std::fs;
        use std::path::Path;

        fn scan_dir(dir: &Path, hits: &mut Vec<String>, skip_self: &Path) {
            if let Ok(entries) = fs::read_dir(dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.is_dir() {
                        // Skip target/, tests/, and headless/ dirs.
                        // headless/ contains fix.rs tests that use iso42001 strings in assertion messages.
                        if path
                            .file_name()
                            .is_some_and(|n| n == "target" || n == "tests" || n == "headless")
                        {
                            continue;
                        }
                        scan_dir(&path, hits, skip_self);
                    } else if path.extension().is_some_and(|e| e == "rs") {
                        if path == skip_self {
                            continue;
                        }
                        if let Ok(content) = fs::read_to_string(&path) {
                            // Skip files that are test files (contain #[test] attributes).
                            // These have iso42001 strings in assertion messages (test data, not code).
                            if content.contains("#[test]") || content.contains("#[tokio::test]") {
                                continue;
                            }
                            // case-insensitive iso42001 / iso-42001 / iso_42001
                            let lower = content.to_lowercase();
                            for variant in ["iso42001", "iso-42001", "iso_42001"] {
                                if lower.contains(variant) {
                                    hits.push(format!(
                                        "{} (contains '{}')",
                                        path.display(),
                                        variant
                                    ));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        let cli_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        let self_path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("headless")
            .join("tests.rs");
        let mut hits = Vec::new();
        scan_dir(&cli_src, &mut hits, &self_path);

        assert!(
            hits.is_empty(),
            "V1-M22 C-3: Found {} iso42001 references in cli/src/. \
             All ISO 42001 code must be removed (preserved in archive/iso-42001 branch). \
             Locations:\n  {}",
            hits.len(),
            hits.join("\n  "),
        );
    }

    // ── V1-M23 / W-2: CLI must pass --output to engine body ─────

    /// V1-M23 W-2: CLI report handler for `--format <md|html|pdf> --output <path>`
    /// must pass user's --output value to engine via JSON body field `outputPath`.
    /// Currently sends empty `{}` body (commands.rs:247) — engine never receives
    /// the user's path, files end up in `.complior/reports/` regardless.
    ///
    /// Source-level spec: commands.rs report handler must include "outputPath"
    /// in the JSON body sent to /report/status/{pdf,markdown} or /report/share.
    #[test]
    fn report_handler_passes_output_to_engine() {
        use std::fs;
        use std::path::Path;

        let commands_rs = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("headless")
            .join("commands.rs");
        let content = fs::read_to_string(&commands_rs).expect("commands.rs readable");

        let has_output_path_in_body =
            content.contains("\"outputPath\":") || content.contains("outputPath:");

        assert!(
            has_output_path_in_body,
            "V1-M23 W-2: cli/src/headless/commands.rs report handler must pass \
             user's --output to engine via `outputPath` JSON body field. \
             Currently sends empty `{{}}` body."
        );
    }

    // ── V1-M22 / D-2 (U-3): fix --check-id exit semantics ───────

    // ── V1-M24 / R-1: ScanResult struct must deserialize `disclaimer` ──

    /// V1-M24 R-1: Rust ScanResult struct in cli/src/types/engine.rs must include
    /// `disclaimer` field. Without it, serde silently drops the field during
    /// deserialization, then `complior scan --json` re-serializes without disclaimer.
    ///
    /// Background: V1-M22/V1-M23 wired buildScanDisclaimer into TS service correctly.
    /// Engine route emits `disclaimer` in JSON. But CLI's ScanResult struct doesn't
    /// have a matching field — serde drops it.
    ///
    /// Spec: deserialize a JSON with `disclaimer` and verify it's preserved.
    #[test]
    fn scan_result_deserializes_disclaimer_field() {
        use crate::types::ScanResult;

        let json = r#"{
            "score": {
                "totalScore": 75.0,
                "zone": "yellow",
                "categoryScores": [],
                "criticalCapApplied": false,
                "totalChecks": 10,
                "passedChecks": 7,
                "failedChecks": 3,
                "skippedChecks": 0
            },
            "findings": [],
            "projectPath": "/tmp",
            "scannedAt": "2026-04-25T00:00:00Z",
            "duration": 0,
            "filesScanned": 1,
            "disclaimer": {
                "summary": "Scan covers L1-L4 deterministic checks",
                "coveredObligations": 15,
                "totalApplicableObligations": 20,
                "coveragePercent": 75.0,
                "uncoveredCount": 5,
                "limitations": [],
                "criticalCapExplanation": null
            }
        }"#;

        let parsed: ScanResult =
            serde_json::from_str(json).expect("ScanResult must deserialize valid JSON");

        let reserialized =
            serde_json::to_value(&parsed).expect("ScanResult must serialize back to JSON");

        // After roundtrip: disclaimer field MUST be preserved
        assert!(
            reserialized.get("disclaimer").is_some() && !reserialized["disclaimer"].is_null(),
            "V1-M24 R-1: ScanResult struct (cli/src/types/engine.rs) must include \
             `disclaimer` field. Currently serde drops it on deserialize, then \
             `complior scan --json` re-serializes without disclaimer. \
             Reserialized: {reserialized}"
        );
    }

    /// V1-M22: `fix --check-id <id>` exit code semantics.
    /// "No auto-fix available" (informational) should exit 0.
    /// Actual failure should exit non-zero.
    ///
    /// Source-level test: fix.rs must define named constants for both exit codes.
    /// This avoids magic numbers scattered through the handler.
    #[test]
    fn fix_check_id_exit_code_constants_defined() {
        use std::fs;
        use std::path::Path;

        let fix_rs = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("headless")
            .join("fix.rs");
        let content = fs::read_to_string(&fix_rs).expect("fix.rs readable");

        let has_no_fix_const = content.contains("EXIT_NO_FIX_AVAILABLE");
        let has_failed_const = content.contains("EXIT_FIX_FAILED");

        assert!(
            has_no_fix_const && has_failed_const,
            "V1-M22 D-2: fix.rs must define constants EXIT_NO_FIX_AVAILABLE (0) \
             and EXIT_FIX_FAILED (non-zero). Missing: no_fix={has_no_fix_const}, failed={has_failed_const}"
        );
    }

    // ── V1-M28: init --yes must respect existing project.toml ──

    /// V1-M28 / W-2: A helper for reading `[onboarding_answers]` table from
    /// `.complior/project.toml` must exist in commands.rs or interactive.rs.
    ///
    /// Background: /deep-e2e cross-profile test failed because all 3 profiles
    /// were tested as deployer/limited/general — `init --yes` overwrote
    /// pre-set TOML profiles with auto-detected defaults from question metadata.
    ///
    /// Source-level test detects helper presence via name OR string literal
    /// match on "[onboarding_answers]".
    #[test]
    fn load_existing_answers_from_toml_helper_exists() {
        use std::fs;
        use std::path::Path;

        let cmd_paths = [
            Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("src")
                .join("headless")
                .join("commands.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("src")
                .join("headless")
                .join("interactive.rs"),
        ];

        let mut found = false;
        for path in &cmd_paths {
            if let Ok(content) = fs::read_to_string(path) {
                if content.contains("load_existing_answers_from_toml")
                    || content.contains("load_answers_from_toml")
                    || content.contains("read_onboarding_answers")
                    || content.contains("[onboarding_answers]")
                {
                    found = true;
                    break;
                }
            }
        }

        assert!(
            found,
            "V1-M28 W-2: cli/src/headless/{{commands,interactive}}.rs must define a \
             helper that reads `[onboarding_answers]` from .complior/project.toml \
             so `init --yes` can respect existing profile."
        );
    }

    /// V1-M28 / W-1: `run_init` (or equivalent) must check for existing TOML
    /// answers and prefer them over `build_default_answers` in --yes mode.
    #[test]
    fn run_init_yes_branch_prefers_toml_over_defaults() {
        use std::fs;
        use std::path::Path;

        let commands_rs = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("headless")
            .join("commands.rs");
        let content = fs::read_to_string(&commands_rs).expect("commands.rs readable");

        // Source must reference TOML loading near the build_default_answers call site
        let has_toml_check = content.contains("project.toml")
            && (content.contains("onboarding_answers")
                || content.contains("existing_answers")
                || content.contains("load_existing"));

        assert!(
            has_toml_check,
            "V1-M28 W-1: cli/src/headless/commands.rs run_init must check for \
             existing project.toml [onboarding_answers] before falling back to \
             build_default_answers when --yes is set."
        );
    }

    // ── V1-M30.4 / Section B.1: CLI rename `passport` → `agent` ──────────
    //
    // `agent` becomes the PRIMARY top-level command. `passport` is kept as a
    // deprecated alias that prints a one-line warning to stderr but still
    // dispatches to the same handlers (no break for existing CI scripts).
    //
    // RED before fix: cli.rs only has `Passport` enum variant, no `Agent`.
    // GREEN after fix: cli.rs has both `Agent` and `Passport` enum variants;
    // the dispatch in main.rs routes both to the same handler; passport path
    // additionally emits the deprecation warning.

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

        let cli_rs = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("cli.rs");
        let content = fs::read_to_string(&cli_rs).expect("cli.rs readable");

        // The Agent variant must exist in the Commands enum.
        assert!(
            content.contains("Agent {") || content.contains("Agent("),
            "V1-M30.4 B.1: cli/src/cli.rs Commands enum must include an `Agent` \
             variant — `complior agent ...` should be the primary top-level \
             command. The existing `Passport` variant is kept as a deprecated alias."
        );
    }

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

        // The passport handler (or main.rs dispatch) must emit a deprecation
        // warning string mentioning `agent` so users know to migrate.
        let candidates = [
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/main.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/passport.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/agent.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/commands.rs"),
        ];

        let mut found = false;
        for path in &candidates {
            if let Ok(content) = fs::read_to_string(path) {
                let has_warning = (content.contains("Deprecated")
                    || content.contains("deprecated"))
                    && content.contains("complior agent")
                    && content.contains("eprintln!");
                if has_warning {
                    found = true;
                    break;
                }
            }
        }

        assert!(
            found,
            "V1-M30.4 B.1: One of cli/src/{{main.rs, headless/passport.rs, \
             headless/agent.rs, headless/commands.rs}} must emit a deprecation \
             warning via eprintln! that mentions both 'deprecated' (case-insensitive) \
             and 'complior agent' when the user invokes `complior passport ...`. \
             The alias must continue to dispatch to the same handler — only \
             add the warning."
        );
    }

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

        // Either main.rs maps both Agent and Passport variants to the same
        // run_passport_command (or rename it run_agent_command and route
        // both there). Check by seeing both enum variants reach the same
        // function call site OR a shared dispatcher.
        let main_rs = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("main.rs");
        let content = fs::read_to_string(&main_rs).expect("main.rs readable");

        // Both Agent and Passport patterns appear in the match
        let both_variants_dispatched = content.contains("Agent {")
            || content.contains("Agent(")
            || content.contains("Commands::Agent");

        assert!(
            both_variants_dispatched,
            "V1-M30.4 B.1: cli/src/main.rs must dispatch the `Agent` enum variant \
             (e.g. Commands::Agent variant routed to run_agent_command or to \
             the existing passport handler). Currently only Passport is dispatched."
        );
    }

    // ── V1-M30.5 / W-5: passport-list empty hint says `complior agent init` ──
    //
    // After the V1-M30.4 CLI rename, output text inside passport.rs (and other
    // user-facing strings) still says "Run `complior passport init`". The
    // command alias still works, but the user-facing hint should reflect the
    // new primary verb so newcomers see the agent name first.

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

        // Files where user-facing init hints appear (per architect's audit).
        let files = [
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/passport.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/scan.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/commands.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app/executor.rs"),
        ];

        for path in &files {
            let content = fs::read_to_string(path)
                .unwrap_or_else(|_| panic!("cannot read {}", path.display()));
            // Only inspect string literals containing user-facing init hints.
            // Ignore comments and ignore strings that EXPLAIN the deprecation.
            for (lineno, line) in content.lines().enumerate() {
                let trimmed = line.trim_start();
                if trimmed.starts_with("//") {
                    continue;
                }
                // The deprecation warning itself is ALLOWED to mention
                // "passport" — that's the literal command name we deprecated.
                if line.contains("Deprecated") || line.contains("deprecated") {
                    continue;
                }
                // The eprintln deprecation line in main.rs.
                if line.contains("v2.0.0") {
                    continue;
                }
                // Find any `complior passport init` literal in non-test,
                // non-doc source lines.
                // V1-M30.5 TD-61: clippy::manual_assert — use assert! not if+panic!
                assert!(
                    !line.contains("complior passport init"),
                    "V1-M30.5 W-5: {}:{} contains user-facing hint \
                     `complior passport init` — should use `complior agent init` \
                     after V1-M30.4 rename (passport remains a deprecated alias \
                     but new hints should reference agent).\n  >>> {}",
                    path.display(),
                    lineno + 1,
                    line
                );
            }
        }
    }

    // ── V1-M30.8a / W-1: All `complior passport <verb>` user-facing strings ──
    //
    // V1-M30.5 W-5 + V1-M30.6 W-2 fixed `passport init` and a few hints, but
    // Phase 1 deep-dive of /deep-e2e CLI outputs found 6 more strings still
    // saying `complior passport list/show/...`. The deprecation alias still
    // works (V1-M30.4 B.1), but new user-facing hints must reference the
    // primary verb `agent`. The deprecation warning string in main.rs is
    // exempt — it MUST literally name the deprecated alias.

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

        let files = [
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/passport.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/commands.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/headless/format/report.rs"),
            Path::new(env!("CARGO_MANIFEST_DIR")).join("src/app/executor.rs"),
        ];

        // Forbidden full-string subcommand hints. The list explicitly excludes
        // `complior passport init` (already handled in V1-M30.5) — but we
        // re-include it here to keep regression coverage.
        let forbidden_substrings = [
            "complior passport init",
            "complior passport list",
            "complior passport show",
            "complior passport rename",
            "complior passport autonomy",
            "complior passport notify",
            "complior passport export",
            "complior passport registry",
            "complior passport evidence",
            "complior passport permissions",
            "complior passport audit",
            "complior passport import",
            "complior passport completeness",
            "complior passport diff",
            "complior passport validate",
            "complior passport fria",
        ];

        for path in &files {
            let content = match fs::read_to_string(path) {
                Ok(c) => c,
                Err(_) => continue,
            };
            for (lineno, line) in content.lines().enumerate() {
                let trimmed = line.trim_start();
                if trimmed.starts_with("//") {
                    continue;
                }
                // Allow lines that document the rename/deprecation
                if line.contains("Deprecated") || line.contains("deprecated") {
                    continue;
                }
                if line.contains("v2.0.0") {
                    continue;
                }
                for forbidden in &forbidden_substrings {
                    assert!(
                        !line.contains(forbidden),
                        "V1-M30.8a W-1: {}:{} contains user-facing hint `{}` — should use `complior agent ...` (alias still works at CLI level but new hints must reference primary verb).\n  >>> {}",
                        path.display(),
                        lineno + 1,
                        forbidden,
                        line,
                    );
                }
            }
        }
    }

    // ── V1-M30.8a / W-8: Fix score estimate not hardcoded to 100 ──
    //
    // fix.rs:517 currently does `format!("{before:.0} → ~{after:.0}")` where
    // `after` ends up being 100 in many cases. Realistic estimate must be
    // computed from per-fix score impacts; the `~` prefix can stay (it's
    // still an estimate), but the value must NOT be a hardcoded ceiling.

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

        let fix_rs = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("headless")
            .join("fix.rs");
        let content = fs::read_to_string(&fix_rs).expect("fix.rs readable");

        // Forbid: `100` literal as direct estimate output and forbid clamps that
        // pin the estimate to 100. Allow: a function that *caps* at 99 to indicate
        // estimate (since 100 implies certainty).
        // Heuristic: look for the formatting line and check that it uses a
        // computed `after` variable, not a literal 100.
        let re_estimate_line = regex_lite_search(&content, "→ ~");
        assert!(
            !re_estimate_line.is_empty(),
            "V1-M30.8a W-8: expected fix.rs to render an estimated score line",
        );
        // No direct format using the literal `100`
        assert!(
            !content.contains("→ ~100"),
            "V1-M30.8a W-8: fix.rs must not hardcode `→ ~100` as the estimate. Compute from per-fix scoreImpact instead.",
        );
    }

    // Tiny helper since we don't want to add a regex dep — substring search.
    fn regex_lite_search(haystack: &str, needle: &str) -> Vec<usize> {
        let mut out = Vec::new();
        let mut pos = 0;
        while let Some(idx) = haystack[pos..].find(needle) {
            out.push(pos + idx);
            pos += idx + needle.len();
        }
        out
    }
}