req-cli 0.5.0-rc.7

Managed requirements CLI for LLM agents and humans
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
// REQ-0134: functional-safety command surface (IEC 61508).
//
// Three artifact families — hazards (HAZ), safety functions (SF), and
// safety requirements (SR) — plus `req trace`, the end-to-end safety
// case. Every mutation goes through the same load-lock-conform-save
// cycle as the requirement commands, records a reasoned history entry,
// and never lets a caller hand-set a SIL: integrity levels are always
// derived from the risk graph and the link structure.
use anyhow::{anyhow, Result};
use chrono::Utc;
use std::path::PathBuf;

use crate::cli::{
    HazAdqConcludeArgs, HazAdqCoverArgs, HazAdqPlanArgs, HazardAddArgs, HazardAdequacyCmd,
    HazardAssessArgs, HazardCmd, HazardConfirmArgs, HazardListArgs, HazardShowArgs,
    HazardUpdateArgs, SfAddArgs, SfCmd, SfListArgs, SfMitigateArgs, SfShowArgs, SfUpdateArgs,
    SreqAddArgs, SreqCmd, SreqListArgs, SreqRealizeArgs, SreqShowArgs, SreqUpdateArgs,
    SreqVerifyArgs, TraceArgs,
};
use crate::model::{
    EvidenceKind, Hazard, HazardStatus, Link, LinkKind, Project, SafetyFunction,
    SafetyFunctionStatus, SafetyRequirement, Sil, Status, TestOutcome, TestRecord,
};
use crate::storage::{self, load_for_mutation, load_resolved};

// SF-0008 / SR-0009: the achieved-integrity boundary stamp that stops a
// target-only trace being misread as evidence of achieved integrity (HAZ-0004).
/// REQ-0203: the achieved-integrity boundary stamp. `req` tracks the
/// REQUIRED/allocated/inherited integrity TARGET and the verified links
/// between artifacts — never the ACHIEVED failure measure. Printed on every
/// safety-function and safety-requirement view so the gap travels with the
/// artifact, not just the README/disclaimer (61508-2; 61508-3 §7.4.3).
const ACHIEVED_INTEGRITY_STAMP: &str =
    "target only — no PFD/PFH, architectural-constraint (HFT/SFF), diagnostic-coverage \
     or systematic-capability evidence is recorded here; achieved integrity is out of scope \
     (see `req help safety`).";

// ---------------------------------------------------------------------------
// id resolution
// ---------------------------------------------------------------------------

/// Normalise a typed id of a given family to canonical `PREFIX-NNNN`.
fn normalize(prefix: &str, raw: &str) -> String {
    let trimmed = raw.trim();
    let upper = trimmed.to_uppercase();
    let want = format!("{}-", prefix);
    let digits = if let Some(rest) = upper.strip_prefix(&want) {
        rest.to_string()
    } else if trimmed.chars().all(|c| c.is_ascii_digit()) && !trimmed.is_empty() {
        trimmed.to_string()
    } else {
        return upper;
    };
    match digits.parse::<u32>() {
        Ok(n) => format!("{}-{:04}", prefix, n),
        Err(_) => upper,
    }
}

fn resolve_haz(project: &Project, raw: &str) -> Result<String> {
    let id = normalize("HAZ", raw);
    if project.hazards.contains_key(&id) {
        Ok(id)
    } else {
        Err(anyhow!("no such hazard: {}", raw))
    }
}

fn resolve_sf(project: &Project, raw: &str) -> Result<String> {
    let id = normalize("SF", raw);
    if project.safety_functions.contains_key(&id) {
        Ok(id)
    } else {
        Err(anyhow!("no such safety function: {}", raw))
    }
}

fn resolve_sr(project: &Project, raw: &str) -> Result<String> {
    let id = normalize("SR", raw);
    if project.safety_requirements.contains_key(&id) {
        Ok(id)
    } else {
        Err(anyhow!("no such safety requirement: {}", raw))
    }
}

fn sil_str(s: Option<Sil>) -> String {
    s.map(|s| s.as_str().to_string())
        .unwrap_or_else(|| "".to_string())
}

fn git_head() -> String {
    std::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_default()
}

// ---------------------------------------------------------------------------
// hazard
// ---------------------------------------------------------------------------

pub fn run_hazard(cmd: HazardCmd, file: &Option<PathBuf>) -> Result<()> {
    match cmd {
        // REQ-0138: mutations require the safety features to be enabled
        // (a human-accepted disclaimer file); reads do not.
        HazardCmd::Add(a) => {
            super::safety_gov::ensure_enabled(file)?;
            hazard_add(a, file)
        }
        HazardCmd::Assess(a) => {
            super::safety_gov::ensure_enabled(file)?;
            hazard_assess(a, file)
        }
        HazardCmd::Update(a) => {
            super::safety_gov::ensure_enabled(file)?;
            hazard_update(a, file)
        }
        HazardCmd::Adequacy(a) => {
            super::safety_gov::ensure_enabled(file)?;
            run_hazard_adequacy(a, file)
        }
        HazardCmd::Confirm(a) => {
            super::safety_gov::ensure_enabled(file)?;
            hazard_confirm(a, file)
        }
        HazardCmd::List(a) => hazard_list(a, file),
        HazardCmd::Show(a) => hazard_show(a, file),
    }
}

fn run_hazard_adequacy(cmd: HazardAdequacyCmd, file: &Option<PathBuf>) -> Result<()> {
    match cmd {
        HazardAdequacyCmd::Plan(a) => hazard_adequacy_plan(a, file),
        HazardAdequacyCmd::Cover(a) => hazard_adequacy_cover(a, file),
        HazardAdequacyCmd::Conclude(a) => hazard_adequacy_conclude(a, file),
    }
}

// SF-0007 / SR-0008 / REQ-0204: the hard chain gate behind a hazard's adequacy.
// Returns the chain anchor over the mitigating safety functions when every live
// one is BOTH covered by a walk-through note AND itself Verified; otherwise an
// error naming the offenders. This is what forces "adequately mitigated by the
// VERIFIED safety functions" to be literally true before the hazard can conclude
// or be co-signed.
fn hazard_adequacy_gate(
    project: &Project,
    haz_id: &str,
    coverage: &[crate::model::CoverageNote],
) -> Result<String> {
    use std::collections::HashSet;
    let sfs = project.mitigating_sfs(haz_id);
    if sfs.is_empty() {
        return Err(anyhow!(
            "{} has no live mitigating safety function — nothing to argue adequacy over. Link one \
             with `req sf mitigate SF-NNNN {}`.",
            haz_id,
            haz_id
        ));
    }
    let covered: HashSet<&str> = coverage.iter().map(|c| c.target.as_str()).collect();
    let mut uncovered = Vec::new();
    let mut unverified = Vec::new();
    let mut tokens = Vec::new();
    for sf in &sfs {
        if !covered.contains(sf.id.as_str()) {
            uncovered.push(sf.id.clone());
        }
        let verified = matches!(sf.status, SafetyFunctionStatus::Verified);
        if !verified {
            unverified.push(format!("{} ({})", sf.id, sf.status.as_str()));
        }
        let ch = sf
            .verification
            .as_ref()
            .and_then(|v| v.content_hash.as_deref());
        tokens.push(crate::model::chain_token(&sf.id, verified, ch));
    }
    if !uncovered.is_empty() {
        return Err(anyhow!(
            "{} cannot conclude adequacy — these mitigating safety functions have no walk-through \
             note: {}. Record one with `req hazard adequacy cover {} --sf SF-NNNN --note \"...\"`.",
            haz_id,
            uncovered.join(", "),
            haz_id
        ));
    }
    if !unverified.is_empty() {
        return Err(anyhow!(
            "{} cannot be argued adequately mitigated by VERIFIED safety functions — these are not \
             Verified: {}. Verify them first (their dossier + human co-sign) so the chain is sound \
             bottom-up.",
            haz_id,
            unverified.join(", ")
        ));
    }
    Ok(crate::model::chain_anchor(&tokens))
}

// REQ-0204: stage 1 — open (or re-open) the staged adequacy dossier.
fn hazard_adequacy_plan(args: HazAdqPlanArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_haz(&project, &args.id)?;
    if args.plan.trim().is_empty() {
        return Err(anyhow!("--plan must not be empty"));
    }
    let now = Utc::now();
    let commit = crate::commands::test_cmd::current_head_sha_opt().unwrap_or_default();
    {
        let h = project.hazards.get_mut(&id).unwrap();
        if let Some(a) = &h.adequacy {
            if a.verdict.is_some() && !args.reopen {
                return Err(anyhow!(
                    "{} already has a concluded adequacy dossier — pass --reopen to re-argue it \
                     (clears the prior verdict and co-sign).",
                    id
                ));
            }
        }
        // Opening (or re-opening) starts a fresh walk-through and clears any
        // prior conclusion / human co-sign.
        h.adequacy = Some(crate::model::AdequacyArgument {
            plan: args.plan.clone(),
            coverage: Vec::new(),
            statement: String::new(),
            credited_external_measures: None,
            verdict: None,
            chain_anchor: None,
            actor: super::current_actor(),
            at: now,
            commit,
            human_confirmation: None,
        });
        h.updated = now;
        h.history.push(super::history(
            if args.reopen {
                "adequacy dossier re-opened (plan recorded)"
            } else {
                "adequacy dossier opened (plan recorded)"
            },
            None,
        ));
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&project.hazards[&id])?);
    } else {
        println!("Opened adequacy dossier for {}.", id);
        let sfs = project.mitigating_sfs(&id);
        println!(
            "Walk through each mitigating safety function ({}): `req hazard adequacy cover {} --sf SF-NNNN --note \"...\"`",
            sfs.iter().map(|s| s.id.as_str()).collect::<Vec<_>>().join(", "),
            id
        );
    }
    Ok(())
}

// REQ-0204: stage 2 — record why one mitigating SF covers the hazard.
fn hazard_adequacy_cover(args: HazAdqCoverArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_haz(&project, &args.id)?;
    let sf_id = resolve_sf(&project, &args.sf)?;
    if args.note.trim().is_empty() {
        return Err(anyhow!("--note must not be empty"));
    }
    // The SF must actually be a live mitigation of this hazard.
    if !project.mitigating_sfs(&id).iter().any(|s| s.id == sf_id) {
        return Err(anyhow!(
            "{} does not live-mitigate {} — only a mitigating safety function can be covered here.",
            sf_id,
            id
        ));
    }
    let now = Utc::now();
    let actor = super::current_actor();
    {
        let h = project.hazards.get_mut(&id).unwrap();
        let adq = h.adequacy.as_mut().ok_or_else(|| {
            anyhow!(
                "{} has no open adequacy dossier — run `req hazard adequacy plan {} --plan \"...\"` first.",
                id, id
            )
        })?;
        if adq.verdict.is_some() {
            return Err(anyhow!(
                "{}'s adequacy dossier is already concluded — re-open it with `req hazard adequacy plan {} --reopen` to revise.",
                id, id
            ));
        }
        // Replace any prior note for this SF (re-covering revises it).
        adq.coverage.retain(|c| c.target != sf_id);
        adq.coverage.push(crate::model::CoverageNote {
            target: sf_id.clone(),
            note: args.note.clone(),
            at: now,
            actor,
        });
        h.updated = now;
        h.history.push(super::history(
            format!("adequacy coverage recorded for {}", sf_id),
            None,
        ));
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&project.hazards[&id])?);
    } else {
        println!("Recorded adequacy coverage of {} for {}.", sf_id, id);
    }
    Ok(())
}

// REQ-0204: stage 3 — conclude. Hard-gated: every live mitigating SF must be
// covered AND Verified. Records the residual-risk statement, derives the
// verdict, and anchors the chain. The hazard stays Mitigated until a human
// co-signs (`req hazard confirm`).
fn hazard_adequacy_conclude(args: HazAdqConcludeArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_haz(&project, &args.id)?;
    if args.statement.trim().is_empty() {
        return Err(anyhow!(
            "--statement (the residual-risk argument) must not be empty"
        ));
    }
    // Read-only gate before any mutation.
    let coverage = project
        .hazards
        .get(&id)
        .and_then(|h| h.adequacy.as_ref())
        .map(|a| a.coverage.clone())
        .ok_or_else(|| {
            anyhow!(
                "{} has no open adequacy dossier — run `req hazard adequacy plan {} --plan \"...\"` first.",
                id, id
            )
        })?;
    let anchor = hazard_adequacy_gate(&project, &id, &coverage)?;
    let now = Utc::now();
    let commit = crate::commands::test_cmd::current_head_sha_opt().unwrap_or_default();
    {
        let h = project.hazards.get_mut(&id).unwrap();
        let adq = h.adequacy.as_mut().unwrap();
        adq.statement = args.statement.clone();
        adq.credited_external_measures = args.external.clone();
        adq.verdict = Some(crate::model::AdequacyVerdict::Adequate);
        adq.chain_anchor = Some(anchor);
        adq.commit = commit;
        adq.at = now;
        // Conclusion clears any stale prior co-sign — a re-argued dossier needs
        // a fresh human confirmation.
        adq.human_confirmation = None;
        h.updated = now;
        h.history.push(super::history(
            "adequacy dossier concluded (adequate) — awaiting human co-sign",
            None,
        ));
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&project.hazards[&id])?);
    } else {
        println!(
            "Concluded adequacy for {} — verdict ADEQUATE (every mitigating SF covered and Verified).",
            id
        );
        println!(
            "Next: a human runs `req hazard confirm {}` to co-sign it and promote to Verified.",
            id
        );
    }
    Ok(())
}

// REQ-0202 / REQ-0204: a human co-signs the concluded adequacy dossier and
// promotes a Mitigated hazard to Verified. Refuses an agent actor; re-checks the
// hard chain gate at co-sign time so a chain that drifted since conclude cannot
// be silently signed off.
fn hazard_confirm(args: HazardConfirmArgs, file: &Option<PathBuf>) -> Result<()> {
    if matches!(super::current_actor_kind(), crate::model::ActorKind::Agent) {
        return Err(anyhow!(
            "co-signing a hazard's adequacy argument must be done by a human, but \
             REQ_ACTOR_KIND=agent. A person must run `req hazard confirm`."
        ));
    }
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_haz(&project, &args.id)?;
    // Read-only preconditions + gate re-check.
    {
        let adq = project
            .hazards
            .get(&id)
            .and_then(|h| h.adequacy.as_ref())
            .ok_or_else(|| {
                anyhow!(
                    "{} has no adequacy dossier to co-sign — run `req hazard adequacy plan {} --plan \"...\"` first.",
                    id, id
                )
            })?;
        if !matches!(adq.verdict, Some(crate::model::AdequacyVerdict::Adequate)) {
            return Err(anyhow!(
                "{} has no concluded ADEQUATE verdict to co-sign — run `req hazard adequacy conclude {} --statement \"...\"` first.",
                id, id
            ));
        }
        let coverage = adq.coverage.clone();
        // Re-apply the hard gate: the chain must still be sound at co-sign time.
        hazard_adequacy_gate(&project, &id, &coverage)?;
    }
    let now = Utc::now();
    {
        let h = project.hazards.get_mut(&id).unwrap();
        if !matches!(h.status, HazardStatus::Mitigated | HazardStatus::Verified) {
            return Err(anyhow!(
                "{} is {} — only a Mitigated hazard can be promoted to Verified.",
                id,
                h.status.as_str()
            ));
        }
        let adequacy = h.adequacy.as_mut().unwrap();
        adequacy.human_confirmation = Some(crate::model::VerificationActivity {
            summary: if args.note.is_empty() {
                "human co-sign of the mitigation-adequacy dossier".to_string()
            } else {
                args.note.clone()
            },
            outcome: TestOutcome::Pass,
            references: Vec::new(),
            at: now,
            actor: super::current_actor(),
        });
        h.status = HazardStatus::Verified;
        h.updated = now;
        h.history.push(super::history(
            "adequacy dossier co-signed by human — promoted to Verified",
            None,
        ));
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&project.hazards[&id])?);
    } else {
        println!(
            "Co-signed adequacy dossier for {} — promoted to Verified.",
            id
        );
    }
    Ok(())
}

fn hazard_add(args: HazardAddArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let now = Utc::now();

    let consequence = args.consequence.map(Into::into);
    let frequency = args.frequency.map(Into::into);
    let avoidance = args.avoidance.map(Into::into);
    let probability = args.probability.map(Into::into);
    let fully_assessed = consequence.is_some()
        && frequency.is_some()
        && avoidance.is_some()
        && probability.is_some();
    let status = if fully_assessed {
        HazardStatus::Assessed
    } else {
        HazardStatus::Identified
    };

    let id = project.allocate_haz_id();
    let hazard = Hazard {
        id: id.clone(),
        title: args.title,
        description: args.description,
        operating_context: args.context,
        harm: args.harm,
        consequence,
        frequency,
        avoidance,
        probability,
        status,
        tags: args.tag,
        links: Vec::new(),
        created: now,
        updated: now,
        history: vec![super::history("created", None)],
        // REQ-0202: no adequacy argument until one is recorded.
        adequacy: None,
        // REQ-0140: forward-compat catch-all preserves unknown fields.
        extra: Default::default(),
    };
    project.hazards.insert(id.clone(), hazard.clone());
    project.updated = now;
    storage::save(&path, &project)?;

    if args.json {
        println!("{}", serde_json::to_string_pretty(&hazard)?);
    } else {
        println!("Added {}", id);
        match project.required_sil(&hazard) {
            Some(s) => println!("Assessed: required {}", s.as_str()),
            None => println!(
                "Status: identified (run `req hazard assess {} -C .. -F .. -P .. -W ..` to derive a SIL)",
                id
            ),
        }
    }
    Ok(())
}

// REQ-0134: list hazards with their derived required SIL.
fn hazard_list(args: HazardListArgs, file: &Option<PathBuf>) -> Result<()> {
    let (_path, project) = load_resolved(file)?;
    let status_filter: Option<HazardStatus> = args.status.map(Into::into);
    let sil_filter = args.sil.as_deref().map(|s| s.to_uppercase());

    let mut rows: Vec<&Hazard> = project
        .hazards
        .values()
        .filter(|h| status_filter.map(|s| h.status == s).unwrap_or(true))
        .filter(|h| {
            sil_filter
                .as_ref()
                .map(|want| {
                    project
                        .required_sil(h)
                        .map(|s| s.as_str().to_uppercase() == *want)
                        .unwrap_or(false)
                })
                .unwrap_or(true)
        })
        .filter(|h| {
            if !args.unmitigated {
                return true;
            }
            !project
                .safety_functions
                .values()
                .any(|sf| mitigates(sf, &h.id))
        })
        .collect();
    rows.sort_by(|a, b| a.id.cmp(&b.id));

    if args.json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(());
    }
    if rows.is_empty() {
        println!("No hazards.");
        return Ok(());
    }
    println!("{:<9}  {:<6}  {:<11}  TITLE", "ID", "SIL", "STATUS");
    for h in rows {
        println!(
            "{:<9}  {:<6}  {:<11}  {}",
            h.id,
            sil_str(project.required_sil(h)),
            h.status.as_str(),
            h.title
        );
    }
    Ok(())
}

fn hazard_show(args: HazardShowArgs, file: &Option<PathBuf>) -> Result<()> {
    let (_path, project) = load_resolved(file)?;
    let id = resolve_haz(&project, &args.id)?;
    let h = &project.hazards[&id];
    if args.json {
        println!("{}", serde_json::to_string_pretty(h)?);
        return Ok(());
    }
    println!("{}  {}", h.id, h.title);
    println!("  status:      {}", h.status.as_str());
    if !h.description.is_empty() {
        println!("  description: {}", h.description);
    }
    if !h.operating_context.is_empty() {
        println!("  context:     {}", h.operating_context);
    }
    println!("  harm:        {}", h.harm);
    match (h.consequence, h.frequency, h.avoidance, h.probability) {
        (Some(c), Some(f), Some(p), Some(w)) => {
            println!(
                "  risk:        {} · {} · {} · {}  ──►  required {}",
                c.as_str(),
                f.as_str(),
                p.as_str(),
                w.as_str(),
                sil_str(project.required_sil(h))
            );
        }
        _ => println!("  risk:        not yet assessed"),
    }
    let sfs: Vec<&SafetyFunction> = project
        .safety_functions
        .values()
        .filter(|sf| mitigates(sf, &h.id))
        .collect();
    if sfs.is_empty() {
        println!("  mitigated by: (none)");
    } else {
        println!("  mitigated by:");
        for sf in sfs {
            println!("    {}{} [{}]", sf.id, sf.title, sf.status.as_str());
        }
    }
    if !h.tags.is_empty() {
        println!("  tags:        {}", h.tags.join(", "));
    }
    // REQ-0204: the staged mitigation-adequacy dossier standing.
    match &h.adequacy {
        None => println!(
            "  adequacy:    (none — `req hazard adequacy plan {} --plan \"...\"` to open the \
             mitigation-adequacy dossier)",
            h.id
        ),
        Some(a) => {
            let standing = match (a.verdict, a.human_confirmation.is_some()) {
                (Some(v), true) => format!("{} (human co-signed)", v.as_str()),
                (Some(v), false) => format!("{} (awaiting human co-sign)", v.as_str()),
                (None, _) => "in progress (not concluded)".to_string(),
            };
            println!("  adequacy:    {}", standing);
            if !a.plan.is_empty() {
                println!("    plan:      {}", a.plan);
            }
            for c in &a.coverage {
                println!("    covers {}: {}", c.target, c.note);
            }
            if !a.statement.is_empty() {
                println!("    residual:  {}", a.statement);
            }
            if let Some(ext) = &a.credited_external_measures {
                println!("    ext.credit: {}", ext);
            }
        }
    }
    // REQ-0206: the derived sign-off basis — what the tool guarantees about the
    // chain, and whether the hazard is ready for a human co-sign.
    for line in hazard_signoff_lines(&project, h) {
        println!("{}", line);
    }
    println!("\nRun `req trace {}` for the full safety case.", h.id);
    Ok(())
}

// REQ-0134: set C/F/P/W and derive the required SIL.
fn hazard_assess(args: HazardAssessArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_haz(&project, &args.id)?;
    let now = Utc::now();
    {
        let h = project.hazards.get_mut(&id).unwrap();
        h.consequence = Some(args.consequence.into());
        h.frequency = Some(args.frequency.into());
        h.avoidance = Some(args.avoidance.into());
        h.probability = Some(args.probability.into());
        if matches!(h.status, HazardStatus::Identified) {
            h.status = HazardStatus::Assessed;
        }
        h.updated = now;
        h.history
            .push(super::history("assessed", args.reason.clone()));
    }
    project.updated = now;
    let derived = project.required_sil(&project.hazards[&id]);
    storage::save(&path, &project)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&project.hazards[&id])?);
    } else {
        println!("Assessed {} ──► required {}", id, sil_str(derived));
    }
    Ok(())
}

// REQ-0134: edit a hazard's fields / lifecycle status.
fn hazard_update(args: HazardUpdateArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_haz(&project, &args.id)?;
    let now = Utc::now();
    {
        let h = project.hazards.get_mut(&id).unwrap();
        if let Some(t) = args.title {
            h.title = t;
        }
        if let Some(d) = args.description {
            h.description = d;
        }
        if let Some(c) = args.context {
            h.operating_context = c;
        }
        if let Some(harm) = args.harm {
            h.harm = harm;
        }
        if let Some(s) = args.status {
            let next: HazardStatus = s.into();
            // REQ-0202: Verified is EARNED, not typed. A hazard reaches Verified
            // only when a recorded mitigation-adequacy argument has been
            // co-signed by a human (`req hazard confirm`); blocking the direct
            // set stops Verified being an unbacked label. Stepping the status
            // back, or retiring it, is still allowed directly.
            if matches!(next, HazardStatus::Verified) {
                return Err(anyhow!(
                    "{} cannot be set to verified directly — record a mitigation-adequacy argument \
                     with `req hazard adequacy {} --statement \"...\"`, then a human runs \
                     `req hazard confirm {}` to co-sign it and promote the hazard to Verified.",
                    id,
                    id,
                    id
                ));
            }
            h.status = next;
        }
        for t in &args.add_tag {
            if !h.tags.contains(t) {
                h.tags.push(t.clone());
            }
        }
        h.tags.retain(|t| !args.remove_tag.contains(t));
        h.updated = now;
        // SR-0003: record append-only reasoned history for safety mutations.
        h.history
            .push(super::history("updated", args.reason.clone()));
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&project.hazards[&id])?);
    } else {
        println!("Updated {}", id);
    }
    Ok(())
}

fn mitigates(sf: &SafetyFunction, haz_id: &str) -> bool {
    sf.links
        .iter()
        .any(|l| l.kind == LinkKind::Mitigates && l.target == haz_id)
}

fn realizes(sr: &SafetyRequirement, sf_id: &str) -> bool {
    sr.links
        .iter()
        .any(|l| l.kind == LinkKind::Realizes && l.target == sf_id)
}

// REQ-0206: the derived sign-off basis for a SAFETY FUNCTION — the
// machine-checked spine of its verification argument ("this group of safety
// requirements implements the function, and they are all Verified"). The
// adequacy JUDGEMENT (do these SRs adequately implement the *intent*) is the
// agent's coverage notes + statement, shown above; this block reports the part
// the tool can guarantee, and whether the function is ready for a human co-sign.
pub fn sf_signoff_lines(project: &Project, sf: &SafetyFunction) -> Vec<String> {
    let srs = project.realizing_srs(&sf.id);
    let mut out = Vec::new();
    if srs.is_empty() {
        out.push(
            "  sign-off basis: no realizing safety requirement — nothing to implement the function"
                .into(),
        );
        return out;
    }
    let total = srs.len();
    let verified: Vec<&str> = srs
        .iter()
        .filter(|sr| matches!(sr.status, Status::Verified))
        .map(|sr| sr.id.as_str())
        .collect();
    let pending: Vec<&str> = srs
        .iter()
        .filter(|sr| !matches!(sr.status, Status::Verified))
        .map(|sr| sr.id.as_str())
        .collect();
    let ids: Vec<&str> = srs.iter().map(|sr| sr.id.as_str()).collect();
    out.push("  sign-off basis:".into());
    out.push(format!(
        "    implemented by {} safety requirement(s): {}",
        total,
        ids.join(", ")
    ));
    out.push(format!(
        "    safety requirements Verified: {}/{}",
        verified.len(),
        total
    ));
    let concluded = sf
        .verification
        .as_ref()
        .map(|v| v.verdict.is_some())
        .unwrap_or(false);
    if !pending.is_empty() {
        out.push(format!(
            "    \u{21d2} NOT yet signable — these safety requirements are not Verified: {}",
            pending.join(", ")
        ));
    } else if concluded {
        out.push(
            "    \u{21d2} the realizing safety requirements adequately implement this function and are all"
                .into(),
        );
        out.push(
            "      Verified; with the concluded dossier above, the function is ready for human co-sign."
                .into(),
        );
    } else {
        out.push(
            "    \u{21d2} the realizing safety requirements are all Verified — conclude the dossier".into(),
        );
        out.push(format!(
            "      (`req verification conclude {} --statement \"...\" --promote`), then co-sign.",
            sf.id
        ));
    }
    out
}

// REQ-0206: the derived sign-off basis for a HAZARD — the machine-checked spine
// of the adequacy argument ("the specified safety functions mitigate the hazard,
// each is implemented by its Verified safety requirements, and all are
// Verified"). Completeness ("the *right* set of SFs is specified") and residual
// risk are the agent's judgement, shown above as the plan / coverage / residual
// statement; this block reports what the tool guarantees and whether the hazard
// is ready for a human co-sign.
pub fn hazard_signoff_lines(project: &Project, hz: &Hazard) -> Vec<String> {
    let sfs = project.mitigating_sfs(&hz.id);
    let mut out = Vec::new();
    if sfs.is_empty() {
        return out;
    }
    let sf_total = sfs.len();
    let sf_verified = sfs
        .iter()
        .filter(|sf| matches!(sf.status, SafetyFunctionStatus::Verified))
        .count();
    let mut sr_total = 0usize;
    let mut sr_verified = 0usize;
    let mut pending: Vec<&str> = Vec::new();
    for sf in &sfs {
        let srs = project.realizing_srs(&sf.id);
        sr_total += srs.len();
        sr_verified += srs
            .iter()
            .filter(|sr| matches!(sr.status, Status::Verified))
            .count();
        if !matches!(sf.status, SafetyFunctionStatus::Verified) {
            pending.push(sf.id.as_str());
        }
    }
    let ids: Vec<&str> = sfs.iter().map(|sf| sf.id.as_str()).collect();
    out.push("  sign-off basis:".into());
    out.push(format!(
        "    mitigated by {} safety function(s): {}",
        sf_total,
        ids.join(", ")
    ));
    out.push(format!(
        "    safety functions Verified: {}/{}   (each implemented by its realizing SRs)",
        sf_verified, sf_total
    ));
    out.push(format!(
        "    realizing SRs Verified:    {}/{}",
        sr_verified, sr_total
    ));
    let concluded = hz
        .adequacy
        .as_ref()
        .map(|a| matches!(a.verdict, Some(crate::model::AdequacyVerdict::Adequate)))
        .unwrap_or(false);
    if !pending.is_empty() {
        out.push(format!(
            "    \u{21d2} NOT yet signable — these mitigations are not Verified: {}",
            pending.join(", ")
        ));
    } else if concluded {
        out.push(
            "    \u{21d2} every specified safety function is Verified and implemented by Verified safety"
                .into(),
        );
        out.push(
            "      requirements; with the residual-risk argument above, the hazard is ready for human co-sign."
                .into(),
        );
    } else {
        out.push(
            "    \u{21d2} every mitigating safety function is Verified — conclude the adequacy dossier".into(),
        );
        out.push(format!(
            "      (`req hazard adequacy conclude {} --statement \"...\"`), then co-sign.",
            hz.id
        ));
    }
    out
}

// ---------------------------------------------------------------------------
// safety function
// ---------------------------------------------------------------------------

pub fn run_sf(cmd: SfCmd, file: &Option<PathBuf>) -> Result<()> {
    match cmd {
        SfCmd::Add(a) => {
            super::safety_gov::ensure_enabled(file)?;
            sf_add(a, file)
        }
        SfCmd::Update(a) => {
            super::safety_gov::ensure_enabled(file)?;
            sf_update(a, file)
        }
        SfCmd::Mitigate(a) => {
            super::safety_gov::ensure_enabled(file)?;
            sf_mitigate(a, file)
        }
        SfCmd::List(a) => sf_list(a, file),
        SfCmd::Show(a) => sf_show(a, file),
    }
}

fn sf_add(args: SfAddArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let now = Utc::now();

    let mut links = Vec::new();
    for raw in &args.mitigates {
        let hid = resolve_haz(&project, raw)?;
        links.push(Link {
            kind: LinkKind::Mitigates,
            target: hid,
        });
    }
    let status = if links.is_empty() {
        SafetyFunctionStatus::Proposed
    } else {
        SafetyFunctionStatus::Allocated
    };

    let id = project.allocate_sf_id();
    let sf = SafetyFunction {
        id: id.clone(),
        title: args.title,
        description: args.description,
        safe_state: args.safe_state,
        status,
        tags: args.tag,
        links: links.clone(),
        created: now,
        updated: now,
        history: vec![super::history("created", None)],
        // REQ-0201: no verification dossier until one is opened.
        verification: None,
        // REQ-0140: forward-compat catch-all preserves unknown fields.
        extra: Default::default(),
    };
    project.safety_functions.insert(id.clone(), sf.clone());
    // A hazard that just gained a mitigation advances to Mitigated.
    for l in &links {
        if let Some(h) = project.hazards.get_mut(&l.target) {
            if matches!(h.status, HazardStatus::Identified | HazardStatus::Assessed) {
                h.status = HazardStatus::Mitigated;
                h.updated = now;
                h.history
                    .push(super::history(format!("mitigated by {}", id), None));
            }
        }
    }
    project.updated = now;
    let alloc = project.allocated_sil(&sf);
    storage::save(&path, &project)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&sf)?);
    } else {
        println!("Added {}", id);
        println!("  allocated SIL: {}", sil_str(alloc));
    }
    Ok(())
}

fn sf_list(args: SfListArgs, file: &Option<PathBuf>) -> Result<()> {
    let (_path, project) = load_resolved(file)?;
    let status_filter: Option<SafetyFunctionStatus> = args.status.map(Into::into);
    let sil_filter = args.sil.as_deref().map(|s| s.to_uppercase());

    let mut rows: Vec<&SafetyFunction> = project
        .safety_functions
        .values()
        .filter(|sf| status_filter.map(|s| sf.status == s).unwrap_or(true))
        .filter(|sf| {
            sil_filter
                .as_ref()
                .map(|want| {
                    project
                        .allocated_sil(sf)
                        .map(|s| s.as_str().to_uppercase() == *want)
                        .unwrap_or(false)
                })
                .unwrap_or(true)
        })
        .filter(|sf| {
            if !args.unrealized {
                return true;
            }
            !project
                .safety_requirements
                .values()
                .any(|sr| realizes(sr, &sf.id))
        })
        .collect();
    rows.sort_by(|a, b| a.id.cmp(&b.id));

    if args.json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(());
    }
    if rows.is_empty() {
        println!("No safety functions.");
        return Ok(());
    }
    println!("{:<8}  {:<6}  {:<12}  TITLE", "ID", "SIL", "STATUS");
    for sf in rows {
        println!(
            "{:<8}  {:<6}  {:<12}  {}",
            sf.id,
            sil_str(project.allocated_sil(sf)),
            sf.status.as_str(),
            sf.title
        );
    }
    Ok(())
}

fn sf_show(args: SfShowArgs, file: &Option<PathBuf>) -> Result<()> {
    let (_path, project) = load_resolved(file)?;
    let id = resolve_sf(&project, &args.id)?;
    let sf = &project.safety_functions[&id];
    if args.json {
        println!("{}", serde_json::to_string_pretty(sf)?);
        return Ok(());
    }
    println!("{}  {}", sf.id, sf.title);
    println!("  status:        {}", sf.status.as_str());
    if !sf.description.is_empty() {
        println!("  description:   {}", sf.description);
    }
    if !sf.safe_state.is_empty() {
        println!("  safe state:    {}", sf.safe_state);
    }
    println!("  allocated SIL: {}", sil_str(project.allocated_sil(sf)));
    let hazards: Vec<&Link> = sf
        .links
        .iter()
        .filter(|l| l.kind == LinkKind::Mitigates)
        .collect();
    if hazards.is_empty() {
        println!("  mitigates:     (no hazard)");
    } else {
        println!("  mitigates:");
        for l in hazards {
            let title = project
                .hazards
                .get(&l.target)
                .map(|h| h.title.as_str())
                .unwrap_or("<missing>");
            println!("    {}{}", l.target, title);
        }
    }
    let srs: Vec<&SafetyRequirement> = project
        .safety_requirements
        .values()
        .filter(|sr| realizes(sr, &sf.id))
        .collect();
    if srs.is_empty() {
        println!("  realized by:   (none)");
    } else {
        println!("  realized by:");
        for sr in srs {
            println!("    {}{} [{}]", sr.id, sr.title, sr.status.as_str());
        }
    }
    // REQ-0201: the verification dossier standing — does a recorded argument
    // back this function achieving its safe state, and is it co-signed?
    match &sf.verification {
        None => println!(
            "  verification:  (none — `req verification plan {}` to record how this function \
             achieves its safe state)",
            sf.id
        ),
        Some(v) => {
            let verdict = v
                .verdict
                .map(|o| o.as_str().to_uppercase())
                .unwrap_or_else(|| "pending".to_string());
            let cosign = if v.human_confirmation.is_some() {
                "human co-signed"
            } else {
                "awaiting human co-sign"
            };
            println!("  verification:  verdict {} ({})", verdict, cosign);
            if !v.plan.is_empty() {
                println!("    plan:        {}", v.plan);
            }
            if let Some(a) = &v.analysis {
                println!("    analysis:    {}{}", a.outcome.as_str(), a.summary);
            }
            if let Some(t) = &v.testing {
                println!("    testing:     {}{}", t.outcome.as_str(), t.summary);
            }
            // REQ-0204/REQ-0206: the realizing-SR adequacy walk-through — the
            // agent's argument that each SR implements the function's intent.
            for c in &v.coverage {
                let sb = project
                    .safety_requirements
                    .get(&c.target)
                    .map(|sr| sr.status.as_str())
                    .unwrap_or("?");
                println!("    covers {} [{}]: {}", c.target, sb, c.note);
            }
            if let Some(s) = &v.statement {
                println!("    statement:   {}", s);
            }
        }
    }
    // REQ-0206: the derived sign-off basis — the realizing SRs and whether they
    // are all Verified, ending in whether the function is ready for co-sign.
    for line in sf_signoff_lines(&project, sf) {
        println!("{}", line);
    }
    // REQ-0203: make the achieved-integrity boundary visible on the artifact.
    println!("  scope:         {}", ACHIEVED_INTEGRITY_STAMP);
    println!("\nRun `req trace {}` for the full safety case.", sf.id);
    Ok(())
}

// REQ-0134: edit a safety function's fields / lifecycle status.
fn sf_update(args: SfUpdateArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_sf(&project, &args.id)?;
    let now = Utc::now();
    {
        let sf = project.safety_functions.get_mut(&id).unwrap();
        if let Some(t) = args.title {
            sf.title = t;
        }
        if let Some(d) = args.description {
            sf.description = d;
        }
        if let Some(s) = args.safe_state {
            sf.safe_state = s;
        }
        if let Some(s) = args.status {
            let next: SafetyFunctionStatus = s.into();
            // SR-0007: a safety function's Verified status is earned through a
            // genuine human-co-signed dossier, never typed.
            // REQ-0201: Implemented and Verified are EARNED through the
            // verification dossier, never typed. A safety function reaches
            // Implemented by concluding a passing dossier, and Verified by the
            // subsequent human co-sign — the same discipline a safety
            // requirement is held to. Block the shortcut so `Verified` can no
            // longer be an unbacked label. Stepping back (to Proposed/Allocated)
            // or retiring (Obsolete) is still allowed directly.
            if matches!(
                next,
                SafetyFunctionStatus::Implemented | SafetyFunctionStatus::Verified
            ) {
                return Err(anyhow!(
                    "{} cannot be set to {} directly — a safety function earns these through its \
                     verification dossier: `req verification plan {} ...` → analysis → test → \
                     conclude --promote (reaches Implemented), then a human runs \
                     `req verification confirm {}` to co-sign it to Verified.",
                    id,
                    next.as_str(),
                    id,
                    id
                ));
            }
            sf.status = next;
        }
        for t in &args.add_tag {
            if !sf.tags.contains(t) {
                sf.tags.push(t.clone());
            }
        }
        sf.tags.retain(|t| !args.remove_tag.contains(t));
        sf.updated = now;
        // SR-0003: record append-only reasoned history for safety mutations.
        sf.history
            .push(super::history("updated", args.reason.clone()));
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&project.safety_functions[&id])?
        );
    } else {
        println!("Updated {}", id);
    }
    Ok(())
}

// REQ-0134: link/unlink a safety function to a hazard it mitigates.
fn sf_mitigate(args: SfMitigateArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let sf_id = resolve_sf(&project, &args.sf)?;
    let haz_id = resolve_haz(&project, &args.hazard)?;
    let now = Utc::now();
    {
        let sf = project.safety_functions.get_mut(&sf_id).unwrap();
        if args.remove {
            sf.links
                .retain(|l| !(l.kind == LinkKind::Mitigates && l.target == haz_id));
            sf.history.push(super::history(
                format!("unlinked mitigates {}", haz_id),
                None,
            ));
        } else if mitigates(sf, &haz_id) {
            return Err(anyhow!("{} already mitigates {}", sf_id, haz_id));
        } else {
            sf.links.push(Link {
                kind: LinkKind::Mitigates,
                target: haz_id.clone(),
            });
            if matches!(sf.status, SafetyFunctionStatus::Proposed) {
                sf.status = SafetyFunctionStatus::Allocated;
            }
            sf.history
                .push(super::history(format!("mitigates {}", haz_id), None));
        }
        sf.updated = now;
    }
    // Advance the hazard to Mitigated when it first acquires a mitigation.
    if !args.remove {
        if let Some(h) = project.hazards.get_mut(&haz_id) {
            if matches!(h.status, HazardStatus::Identified | HazardStatus::Assessed) {
                h.status = HazardStatus::Mitigated;
                h.updated = now;
                h.history
                    .push(super::history(format!("mitigated by {}", sf_id), None));
            }
        }
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&project.safety_functions[&sf_id])?
        );
    } else if args.remove {
        println!("{} no longer mitigates {}", sf_id, haz_id);
    } else {
        println!("{} mitigates {}", sf_id, haz_id);
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// safety requirement
// ---------------------------------------------------------------------------

pub fn run_sreq(cmd: SreqCmd, file: &Option<PathBuf>) -> Result<()> {
    match cmd {
        SreqCmd::Add(a) => {
            super::safety_gov::ensure_enabled(file)?;
            sreq_add(a, file)
        }
        SreqCmd::Update(a) => {
            super::safety_gov::ensure_enabled(file)?;
            sreq_update(a, file)
        }
        SreqCmd::Realize(a) => {
            super::safety_gov::ensure_enabled(file)?;
            sreq_realize(a, file)
        }
        SreqCmd::Verify(a) => {
            super::safety_gov::ensure_enabled(file)?;
            sreq_verify(a, file)
        }
        SreqCmd::List(a) => sreq_list(a, file),
        SreqCmd::Show(a) => sreq_show(a, file),
    }
}

fn sreq_add(args: SreqAddArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let now = Utc::now();

    let mut links = Vec::new();
    for raw in &args.realizes {
        let sfid = resolve_sf(&project, raw)?;
        links.push(Link {
            kind: LinkKind::Realizes,
            target: sfid,
        });
    }

    let id = project.allocate_sr_id();
    let sr = SafetyRequirement {
        id: id.clone(),
        title: args.title,
        statement: args.statement,
        rationale: args.rationale,
        acceptance: args.acceptance,
        priority: args.priority.into(),
        status: Status::Draft,
        tags: args.tag,
        links,
        created: now,
        updated: now,
        history: vec![super::history("created", None)],
        tests: Vec::new(),
        // REQ-0139: a new safety requirement starts without a verification dossier.
        verification: None,
        // REQ-0171: no walkthrough acknowledgement yet.
        walkthrough: None,
        // REQ-0140: forward-compat catch-all preserves unknown fields.
        extra: Default::default(),
    };
    project.safety_requirements.insert(id.clone(), sr.clone());
    project.updated = now;
    let sil = project.inherited_sil(&sr);
    storage::save(&path, &project)?;
    if args.json {
        println!("{}", serde_json::to_string_pretty(&sr)?);
    } else {
        println!("Added {}", id);
        println!("  inherits SIL: {}", sil_str(sil));
        println!(
            "Next: add `// {}:` to the source that implements this, then \
             `req sreq verify {} --by automated ...`.",
            id, id
        );
    }
    Ok(())
}

fn sreq_list(args: SreqListArgs, file: &Option<PathBuf>) -> Result<()> {
    let (_path, project) = load_resolved(file)?;
    let status_filter: Option<Status> = args.status.map(Into::into);
    let sil_filter = args.sil.as_deref().map(|s| s.to_uppercase());

    let mut rows: Vec<&SafetyRequirement> = project
        .safety_requirements
        .values()
        .filter(|sr| status_filter.map(|s| sr.status == s).unwrap_or(true))
        .filter(|sr| {
            sil_filter
                .as_ref()
                .map(|want| {
                    project
                        .inherited_sil(sr)
                        .map(|s| s.as_str().to_uppercase() == *want)
                        .unwrap_or(false)
                })
                .unwrap_or(true)
        })
        .filter(|sr| !args.unverified || !matches!(sr.status, Status::Verified))
        .collect();
    rows.sort_by(|a, b| a.id.cmp(&b.id));

    if args.json {
        println!("{}", serde_json::to_string_pretty(&rows)?);
        return Ok(());
    }
    if rows.is_empty() {
        println!("No safety requirements.");
        return Ok(());
    }
    println!("{:<8}  {:<6}  {:<14}  TITLE", "ID", "SIL", "STATUS");
    for sr in rows {
        // REQ-0188: an awaiting-co-sign requirement reads as such, never as a
        // plain "implemented" that a reviewer might mistake for done.
        let status = if super::provenance::sr_awaiting_cosign(sr) {
            "awaiting-cosign"
        } else {
            sr.status.as_str()
        };
        println!(
            "{:<8}  {:<6}  {:<14}  {}",
            sr.id,
            sil_str(project.inherited_sil(sr)),
            status,
            sr.title
        );
    }
    Ok(())
}

// REQ-0134: show a safety requirement with its inherited SIL and evidence.
fn sreq_show(args: SreqShowArgs, file: &Option<PathBuf>) -> Result<()> {
    let (_path, project) = load_resolved(file)?;
    let id = resolve_sr(&project, &args.id)?;
    let sr = &project.safety_requirements[&id];
    if args.json {
        println!("{}", serde_json::to_string_pretty(sr)?);
        return Ok(());
    }
    println!("{}  {}", sr.id, sr.title);
    // REQ-0188: surface the awaiting-co-sign state explicitly.
    if super::provenance::sr_awaiting_cosign(sr) {
        println!(
            "  status:       {} (awaiting human co-sign — `req verification confirm {}`)",
            sr.status.as_str(),
            sr.id
        );
    } else {
        println!("  status:       {}", sr.status.as_str());
    }
    println!("  priority:     {}", sr.priority.as_str());
    println!("  inherits SIL: {}", sil_str(project.inherited_sil(sr)));
    println!("  statement:    {}", sr.statement);
    println!("  rationale:    {}", sr.rationale);
    if !sr.acceptance.is_empty() {
        println!("  acceptance:");
        for (i, a) in sr.acceptance.iter().enumerate() {
            println!("    {}. {}", i + 1, a);
        }
    }
    let sfs: Vec<&Link> = sr
        .links
        .iter()
        .filter(|l| l.kind == LinkKind::Realizes)
        .collect();
    if sfs.is_empty() {
        println!("  realizes:     (no safety function)");
    } else {
        println!("  realizes:");
        for l in sfs {
            let title = project
                .safety_functions
                .get(&l.target)
                .map(|sf| sf.title.as_str())
                .unwrap_or("<missing>");
            println!("    {}{}", l.target, title);
        }
    }
    match sr.tests.last() {
        Some(t) => {
            println!(
                "  evidence:     {} · {} · {}",
                t.kind.as_str(),
                if t.commit.is_empty() {
                    ""
                } else {
                    &t.commit[..t.commit.len().min(8)]
                },
                t.outcome.as_str()
            );
            // REQ-0154: show the SIL this evidence was justified against next
            // to the current inherited SIL, so escalation is visible here.
            let current = project.inherited_sil(sr);
            if let Some(at) = t.sil_at_verification {
                let cur = current.map(|s| s.as_str()).unwrap_or("");
                let flag = match current {
                    Some(c) if c.rank() > at.rank() => "  ⚠ inherited SIL rose since verification",
                    _ => "",
                };
                println!(
                    "  evidence SIL: {} (verified at) · {} (current){}",
                    at.as_str(),
                    cur,
                    flag
                );
            }
        }
        None => println!("  evidence:     none"),
    }
    // REQ-0203: make the achieved-integrity boundary visible on the artifact.
    println!("  scope:        {}", ACHIEVED_INTEGRITY_STAMP);
    println!("\nRun `req trace {}` for the full safety case.", sr.id);
    Ok(())
}

// REQ-0134: edit a safety requirement's fields / lifecycle status.
fn sreq_update(args: SreqUpdateArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_sr(&project, &args.id)?;
    let now = Utc::now();
    // REQ-0161: capture the force-reason floor before the mutable borrow.
    let min_force_reason_len = project.min_force_reason_len();
    {
        let sr = project.safety_requirements.get_mut(&id).unwrap();
        if let Some(t) = args.title {
            sr.title = t;
        }
        if let Some(s) = args.statement {
            sr.statement = s;
        }
        if let Some(r) = args.rationale {
            sr.rationale = r;
        }
        if let Some(a) = args.acceptance {
            sr.acceptance = a;
        }
        for a in &args.add_acceptance {
            sr.acceptance.push(a.clone());
        }
        if let Some(p) = args.priority {
            sr.priority = p.into();
        }
        if let Some(s) = args.status {
            // REQ-0158: safety requirements obey the same lifecycle ladder as
            // ordinary requirements — an irregular transition (backward, a
            // skip, or leaving Verified for anything but Obsolete) needs an
            // explicit --force, so a Verified SR cannot be quietly demoted.
            let to: crate::model::Status = s.into();
            if sr.status != to {
                if !crate::model::is_natural_transition(sr.status, to) && !args.force {
                    return Err(anyhow!(
                        "{} -> {} is an irregular transition for {}; pass --force \
                         --reason \"...\" to record an explicit override.",
                        sr.status.as_str(),
                        to.as_str(),
                        id
                    ));
                }
                // REQ-0161: a forced irregular transition needs a substantive reason.
                if !crate::model::is_natural_transition(sr.status, to) {
                    super::ensure_force_reason(&args.reason, min_force_reason_len)?;
                }
                sr.status = to;
            }
        }
        for t in &args.add_tag {
            if !sr.tags.contains(t) {
                sr.tags.push(t.clone());
            }
        }
        sr.tags.retain(|t| !args.remove_tag.contains(t));
        sr.updated = now;
        // SR-0003: record append-only reasoned history for safety mutations.
        sr.history
            .push(super::history("updated", args.reason.clone()));
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&project.safety_requirements[&id])?
        );
    } else {
        println!("Updated {}", id);
    }
    Ok(())
}

fn sreq_realize(args: SreqRealizeArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let sr_id = resolve_sr(&project, &args.sreq)?;
    let sf_id = resolve_sf(&project, &args.sf)?;
    let now = Utc::now();
    {
        let sr = project.safety_requirements.get_mut(&sr_id).unwrap();
        if args.remove {
            sr.links
                .retain(|l| !(l.kind == LinkKind::Realizes && l.target == sf_id));
            sr.history
                .push(super::history(format!("unlinked realizes {}", sf_id), None));
        } else if realizes(sr, &sf_id) {
            return Err(anyhow!("{} already realizes {}", sr_id, sf_id));
        } else {
            sr.links.push(Link {
                kind: LinkKind::Realizes,
                target: sf_id.clone(),
            });
            sr.history
                .push(super::history(format!("realizes {}", sf_id), None));
        }
        sr.updated = now;
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&project.safety_requirements[&sr_id])?
        );
    } else if args.remove {
        println!("{} no longer realizes {}", sr_id, sf_id);
    } else {
        println!("{} realizes {}", sr_id, sf_id);
    }
    Ok(())
}

fn sreq_verify(args: SreqVerifyArgs, file: &Option<PathBuf>) -> Result<()> {
    let (path, mut project, _lock) = load_for_mutation(file)?;
    let id = resolve_sr(&project, &args.id)?;
    let kind: EvidenceKind = args.by.into();
    let inherited = project.inherited_sil(&project.safety_requirements[&id]);
    let status = project.safety_requirements[&id].status;

    // REQ-0135: the gates only bite on PROMOTION — recording evidence
    // for context is always allowed. `--force` (which requires --reason)
    // overrides them and records a structured, audited exception.
    let mut gate_exception = false;
    if args.promote {
        // REQ-0139: a passing verification dossier is the precondition for a
        // safety requirement to reach Verified. There is no tag exemption
        // for safety (only an audited `req verification backfill`).
        super::verification::gate_safety_requirement(&project.safety_requirements[&id])?;
        // Status-ladder guard, mirroring ordinary `req verify`: promote
        // only from Implemented (or re-affirming Verified); never resurrect
        // an Obsolete requirement, except under an explicit --force.
        let ladder_ok = matches!(status, Status::Implemented | Status::Verified);
        if !ladder_ok && !args.force {
            return Err(anyhow!(
                "{} is {} — promoting straight to Verified is irregular. Advance it to \
                 Implemented first, or pass --force --reason \"...\" to record the override.",
                id,
                status.as_str()
            ));
        }
        // SIL-rigour gate: a SIL 3/4 requirement cannot be VERIFIED on
        // inspection-only evidence.
        // SR-0002: gate Verified on SIL-adequate evidence.
        if let Some(sil) = inherited {
            if sil.rank() >= Sil::Sil3.rank() && matches!(kind, EvidenceKind::Inspection) {
                if args.force {
                    gate_exception = true;
                } else {
                    return Err(anyhow!(
                        "SIL-rigour gate: {} inherits {} — it cannot be verified on \
                         inspection-only evidence. Provide automated or composition \
                         evidence, or pass --force --reason \"...\" to record an audited \
                         exception.",
                        id,
                        sil.as_str()
                    ));
                }
            }
        }
    }

    let now = Utc::now();
    let mut notes = args.notes.clone();
    if !args.cites.is_empty() {
        notes = format!("cites {}{}", args.cites.join(", "), notes);
    }
    if let Some(reason) = args.reason.as_deref().filter(|_| args.force) {
        notes = format!("[override: {}] {}", reason, notes);
    }
    let record = TestRecord {
        at: now,
        actor: super::current_actor(),
        commit: git_head(),
        outcome: TestOutcome::Pass,
        notes,
        kind,
        content_hash: None,
        linked_files: None,
        sil_gate_exception: gate_exception,
        // REQ-0154: snapshot the SIL this evidence was justified against.
        sil_at_verification: inherited,
        external: None,
    };
    {
        let sr = project.safety_requirements.get_mut(&id).unwrap();
        sr.tests.push(record);
        if args.promote {
            sr.status = Status::Verified;
        }
        sr.updated = now;
        sr.history.push(super::history(
            if args.promote {
                "verified (promoted)"
            } else {
                "evidence recorded"
            },
            args.reason.clone(),
        ));
    }
    project.updated = now;
    storage::save(&path, &project)?;
    if args.json {
        println!(
            "{}",
            serde_json::to_string_pretty(&project.safety_requirements[&id])?
        );
    } else {
        println!(
            "Recorded {} evidence for {}{}",
            kind.as_str(),
            id,
            if args.promote { " → Verified" } else { "" }
        );
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// trace — end-to-end safety case
// ---------------------------------------------------------------------------

pub fn run_trace(args: TraceArgs, file: &Option<PathBuf>) -> Result<()> {
    let (_path, project) = load_resolved(file)?;
    let raw = args.id.trim().to_uppercase();
    if raw.starts_with("HAZ") {
        let id = resolve_haz(&project, &args.id)?;
        trace_hazard(&project, &id, args.json)
    } else if raw.starts_with("SF") {
        let id = resolve_sf(&project, &args.id)?;
        // Trace each hazard the SF mitigates; if none, trace the SF alone.
        trace_from_sf(&project, &id, args.json)
    } else if raw.starts_with("SR") {
        let id = resolve_sr(&project, &args.id)?;
        trace_from_sr(&project, &id, args.json)
    } else {
        Err(anyhow!("trace expects a HAZ-/SF-/SR- id; got {}", args.id))
    }
}

/// Verdict for a single hazard's safety case.
struct Verdict {
    required: Option<Sil>,
    allocated: Option<Sil>,
    sr_total: usize,
    sr_verified: usize,
    adequate: bool,
    complete: bool,
    blocking: Vec<String>,
}

// REQ-0136: roll up a hazard's safety case for `req trace`.
fn assess_hazard(project: &Project, haz_id: &str) -> Verdict {
    let h = &project.hazards[haz_id];
    let required = project.required_sil(h);
    let sfs: Vec<&SafetyFunction> = project
        .safety_functions
        .values()
        .filter(|sf| mitigates(sf, haz_id))
        .collect();
    let allocated = sfs
        .iter()
        .filter_map(|sf| project.allocated_sil(sf))
        .max_by_key(|s| s.rank());
    let adequate = match (required, allocated) {
        (Some(r), Some(a)) => a.rank() >= r.rank(),
        (Some(_), None) => false,
        (None, _) => true, // not assessed: adequacy undecided, treat as not-blocking
    };
    let mut sr_total = 0;
    let mut sr_verified = 0;
    let mut blocking = Vec::new();
    // REQ-0189: a realizing safety requirement counts toward completeness only
    // when the conformance checker also considers it done — genuinely verified,
    // human co-signed, and not stale — so `req trace` can never claim a hazard's
    // safety case complete while `req conform` reports findings on the same
    // requirements. Staleness is judged against the working tree (root "."),
    // matching how `req conform` (REQ-V-0035) checks it.
    use crate::commands::provenance::{classify, sr_awaiting_cosign, Provenance};
    let root = std::path::Path::new(".");
    for sf in &sfs {
        for sr in project
            .safety_requirements
            .values()
            .filter(|sr| realizes(sr, &sf.id))
        {
            sr_total += 1;
            let standing = classify(sr.verification.as_ref(), Some(root), &sr.id);
            let confirmed = sr
                .verification
                .as_ref()
                .and_then(|v| v.human_confirmation.as_ref())
                .is_some();
            let clean = matches!(sr.status, Status::Verified)
                && confirmed
                && standing == Provenance::Genuine;
            if clean {
                sr_verified += 1;
            } else {
                let why = if sr_awaiting_cosign(sr)
                    || (matches!(sr.status, Status::Verified) && !confirmed)
                {
                    "awaiting human co-sign"
                } else if standing == Provenance::Stale {
                    "stale"
                } else if !matches!(sr.status, Status::Verified) {
                    "not verified"
                } else {
                    "not genuinely verified"
                };
                blocking.push(format!("{} {}", sr.id, why));
            }
        }
    }
    if sfs.is_empty() {
        blocking.push("no mitigating safety function".to_string());
    } else if sr_total == 0 {
        blocking.push("no realizing safety requirement".to_string());
    }
    let complete = adequate && blocking.is_empty();
    Verdict {
        required,
        allocated,
        sr_total,
        sr_verified,
        adequate,
        complete,
        blocking,
    }
}

// REQ-0136: print the end-to-end safety case for a hazard.
fn trace_hazard(project: &Project, haz_id: &str, json: bool) -> Result<()> {
    let h = &project.hazards[haz_id];
    let v = assess_hazard(project, haz_id);
    if json {
        // REQ-0146: include the full safety-function → safety-requirement chain
        // with each SR's verification dossier so --json carries the same chain
        // the human view renders, not just roll-up counts.
        let chain: Vec<_> = project
            .safety_functions
            .values()
            .filter(|sf| mitigates(sf, haz_id))
            .map(|sf| {
                let srs: Vec<_> = project
                    .safety_requirements
                    .values()
                    .filter(|sr| realizes(sr, &sf.id))
                    .map(|sr| {
                        serde_json::json!({
                            "id": sr.id,
                            "title": sr.title,
                            "status": sr.status.as_str(),
                            "inherited_sil": project.inherited_sil(sr).map(|s| s.as_str()),
                            "verification": sr.verification,
                            // REQ-0171: walkthrough acknowledgement state in trace JSON.
                            "walkthrough": sr.walkthrough,
                        })
                    })
                    .collect();
                serde_json::json!({
                    "id": sf.id,
                    "title": sf.title,
                    "status": sf.status.as_str(),
                    "allocated_sil": project.allocated_sil(sf).map(|s| s.as_str()),
                    "safety_requirements": srs,
                })
            })
            .collect();
        let out = serde_json::json!({
            "hazard": h,
            "required_sil": v.required.map(|s| s.as_str()),
            "allocated_sil": v.allocated.map(|s| s.as_str()),
            "adequate": v.adequate,
            "complete": v.complete,
            "chain": chain,
            "safety_requirements": { "total": v.sr_total, "verified": v.sr_verified },
            "blocking": v.blocking,
        });
        println!("{}", serde_json::to_string_pretty(&out)?);
        return Ok(());
    }

    println!("{}  {}  [{}]", h.id, h.title, h.status.as_str());
    println!("  harm:     {}", h.harm);
    if !h.operating_context.is_empty() {
        println!("  context:  {}", h.operating_context);
    }
    // REQ-0136: render the hazard's risk and its mitigating safety-function
    // → safety-requirement chain (the end-to-end safety case).
    match (h.consequence, h.frequency, h.avoidance, h.probability) {
        (Some(c), Some(f), Some(p), Some(w)) => println!(
            "  risk:     {} · {} · {} · {}  ──►  required {}",
            c.as_str(),
            f.as_str(),
            p.as_str(),
            w.as_str(),
            sil_str(v.required)
        ),
        _ => println!("  risk:     not yet assessed"),
    }
    // REQ-0204: the staged mitigation-adequacy dossier — why the hazard is
    // adequately mitigated by its verified safety functions.
    if let Some(a) = &h.adequacy {
        let standing = match (a.verdict, a.human_confirmation.is_some()) {
            (Some(vd), true) => format!("{} (human co-signed)", vd.as_str()),
            (Some(vd), false) => format!("{} (awaiting human co-sign)", vd.as_str()),
            (None, _) => "in progress (not concluded)".to_string(),
        };
        println!("  adequacy: {}", standing);
        for c in &a.coverage {
            let sb = project
                .safety_functions
                .get(&c.target)
                .map(|sf| sf.status.as_str())
                .unwrap_or("?");
            println!("    covers {} [{}]: {}", c.target, sb, c.note);
        }
        if !a.statement.is_empty() {
            println!("    residual: {}", a.statement);
        }
    }

    let sfs: Vec<&SafetyFunction> = project
        .safety_functions
        .values()
        .filter(|sf| mitigates(sf, haz_id))
        .collect();
    if sfs.is_empty() {
        println!("");
        println!("  └─ mitigated by ── (none)");
    }
    for sf in &sfs {
        let alloc = project.allocated_sil(sf);
        let meets = match (v.required, alloc) {
            (Some(r), Some(a)) => {
                if a.rank() >= r.rank() {
                    "✓ meets required"
                } else {
                    "✗ below required"
                }
            }
            _ => "",
        };
        println!("");
        println!("  └─ mitigated by ─────────────────────────────────");
        println!("     {}  {}  [{}]", sf.id, sf.title, sf.status.as_str());
        if !sf.safe_state.is_empty() {
            println!("       safe state:    {}", sf.safe_state);
        }
        println!("       allocated SIL: {}   {}", sil_str(alloc), meets);
        // REQ-0204: the safety function's adequacy walk-through — why each
        // realizing SR implements it (and whether that SR is Verified).
        if let Some(sfv) = &sf.verification {
            for c in &sfv.coverage {
                let sb = project
                    .safety_requirements
                    .get(&c.target)
                    .map(|sr| sr.status.as_str())
                    .unwrap_or("?");
                println!("       covers {} [{}]: {}", c.target, sb, c.note);
            }
        }
        let srs: Vec<&SafetyRequirement> = project
            .safety_requirements
            .values()
            .filter(|sr| realizes(sr, &sf.id))
            .collect();
        if srs.is_empty() {
            println!("       └─ realized by ── (none)");
        } else {
            println!("       └─ realized by ───────────────────────");
        }
        for sr in srs {
            let mark = if matches!(sr.status, Status::Verified) {
                ""
            } else {
                ""
            };
            println!(
                "          {}  {}  [{}] {}",
                sr.id,
                sr.title,
                sr.status.as_str(),
                mark
            );
            println!(
                "            inherits SIL {}",
                sil_str(project.inherited_sil(sr))
            );
            match sr.tests.last() {
                Some(t) => println!(
                    "            evidence: {} · {}",
                    t.kind.as_str(),
                    if t.commit.is_empty() {
                        "".to_string()
                    } else {
                        t.commit[..t.commit.len().min(8)].to_string()
                    }
                ),
                None => println!("            evidence: none                       ✗ unverified"),
            }
            // REQ-0146: inline the verification dossier so a reviewer sees how
            // each safety requirement was verified within the chain, not just
            // its status.
            match &sr.verification {
                Some(val) => {
                    let verdict = val.verdict.map(|o| o.as_str()).unwrap_or("open");
                    let a = val
                        .analysis
                        .as_ref()
                        .map(|x| x.outcome.as_str())
                        .unwrap_or("");
                    let t = val
                        .testing
                        .as_ref()
                        .map(|x| x.outcome.as_str())
                        .unwrap_or("");
                    println!("            dossier: verdict {verdict} (analysis {a}, testing {t})");
                    match &val.human_confirmation {
                        Some(hc) => println!(
                            "            human-confirmed: {} @ {}",
                            hc.actor,
                            hc.at.format("%Y-%m-%d %H:%M UTC")
                        ),
                        None => println!(
                            "            human-confirmed: ⚠ awaiting human confirmation (REQ-V-0034)"
                        ),
                    }
                    if let Some(st) = &val.statement {
                        println!("            statement: {st}");
                    }
                }
                None => println!("            dossier: (none recorded)"),
            }
            // REQ-0171: surface the human walkthrough acknowledgement state in
            // the trace, so a reviewer sees whether the chain was signed off.
            match &sr.walkthrough {
                Some(a) if a.objected => {
                    println!("            walkthrough: ✗ objection by {}", a.reviewer)
                }
                Some(a) => println!(
                    "            walkthrough: ✓ acknowledged by {} at {} (commit {})",
                    a.reviewer,
                    a.at.format("%Y-%m-%d %H:%M UTC"),
                    if a.commit.is_empty() {
                        "".to_string()
                    } else {
                        a.commit[..a.commit.len().min(8)].to_string()
                    }
                ),
                None => println!("            walkthrough: ▷ not yet acknowledged"),
            }
        }
    }

    println!();
    // REQ-0135: this is a TRACEABILITY roll-up, not a safety-adequacy
    // verdict. "Complete" means every link in the chain is present and
    // every realizing requirement is verified to the rigour its SIL
    // demands — NOT that the residual risk is acceptable. The SIL
    // comparison below is an *allocation* check (allocated ≥ required),
    // which says nothing about whether the function *achieves* that
    // integrity. The wording is deliberately modest; see the disclaimer.
    // REQ-0160: state the scope explicitly. A complete chain means every
    // link is present and every realizing requirement is verified to its
    // SIL's rigour — it is "linked and verified", NOT a judgement that the
    // residual risk is acceptable or that the system is validated.
    let verdict = if v.complete {
        "✓ chain linked and verified"
    } else {
        "⚠ chain incomplete"
    };
    println!("  TRACE STATUS:  {}", verdict);
    println!("    scope: traceability + verification only — NOT a residual-risk verification");
    println!(
        "    SIL allocation: required {} — allocated {}    {}",
        sil_str(v.required),
        sil_str(v.allocated),
        if v.adequate {
            "✓ allocation ≥ required"
        } else {
            "✗ allocation below required"
        }
    );
    println!(
        "    safety requirements: {} verified of {}",
        v.sr_verified, v.sr_total
    );
    if !v.blocking.is_empty() {
        println!("    blocking: {}", v.blocking.join("; "));
    }
    // REQ-0135: the risk-graph 'b' outcome is not just "very high SIL" —
    // it means a single E/E/PE safety-related system is NOT sufficient.
    // That is an architectural finding the verification gate can't speak
    // to, so call it out explicitly.
    if matches!(v.required, Some(Sil::B)) || matches!(v.allocated, Some(Sil::B)) {
        println!(
            "    ⚠ SIL 'b': a single E/E/PE safety-related system is not sufficient for this \
             risk — independent/additional risk-reduction measures are required (an \
             architecture decision, beyond what req's verification gate checks)."
        );
    }
    println!();
    println!("{}", SAFETY_DISCLAIMER_LINE);
    Ok(())
}

/// REQ-0135: a one-line honesty footer shown under every `req trace` and
/// HARA export. req computes a *candidate* classification and checks
/// *traceability*; it is not a qualified safety tool and does not
/// discharge the user's assessment responsibility.
pub const SAFETY_DISCLAIMER_LINE: &str =
    "  ⚠ req computes a candidate SIL from your inputs and checks traceability only. \
It is not qualified per IEC 61508-3 §7.4.4 and does not assure risk reduction — \
the safety determination remains yours. See `req help safety`.";

fn trace_from_sf(project: &Project, sf_id: &str, json: bool) -> Result<()> {
    let sf = &project.safety_functions[sf_id];
    let hazards: Vec<String> = sf
        .links
        .iter()
        .filter(|l| l.kind == LinkKind::Mitigates)
        .map(|l| l.target.clone())
        .filter(|t| project.hazards.contains_key(t))
        .collect();
    if hazards.is_empty() {
        if json {
            println!("{}", serde_json::to_string_pretty(sf)?);
        } else {
            println!(
                "{} mitigates no hazard yet — nothing to trace upward.",
                sf_id
            );
            println!(
                "Run `req sf show {}` for its realizing requirements.",
                sf_id
            );
        }
        return Ok(());
    }
    for (i, hid) in hazards.iter().enumerate() {
        if i > 0 {
            println!();
        }
        trace_hazard(project, hid, json)?;
    }
    Ok(())
}

fn trace_from_sr(project: &Project, sr_id: &str, json: bool) -> Result<()> {
    let sr = &project.safety_requirements[sr_id];
    let sfs: Vec<String> = sr
        .links
        .iter()
        .filter(|l| l.kind == LinkKind::Realizes)
        .map(|l| l.target.clone())
        .filter(|t| project.safety_functions.contains_key(t))
        .collect();
    if sfs.is_empty() {
        if json {
            println!("{}", serde_json::to_string_pretty(sr)?);
        } else {
            println!(
                "{} realizes no safety function yet — nothing to trace upward.",
                sr_id
            );
        }
        return Ok(());
    }
    for (i, sfid) in sfs.iter().enumerate() {
        if i > 0 {
            println!();
        }
        trace_from_sf(project, sfid, json)?;
    }
    Ok(())
}