ccf-core 1.0.1

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

#![no_std]
#![forbid(unsafe_code)]

/// The command/runtime journey that gates the scaffold story.
pub const CONTRACT_JOURNEY_ID: &str = "J-CORE-TEST-MATRIX";

/// The old-wrong-core regression path that the scaffold gate must reject.
pub const OLD_WRONG_CORE_GUARD: &str = "God-spec implementation with no enforceable contracts";

/// The ccf-core package version required by story #148.
pub const CCF_CORE_V1_VERSION: &str = env!("CARGO_PKG_VERSION");

pub mod qac {
    /// The command/runtime journey for story #149.
    pub const QAC_JOURNEY_ID: &str = "J-QAC-REFERENCE";

    /// The SpecFlow story id for the canonical QAC update.
    pub const QAC_STORY_ID: &str = "CCFV1-01";

    /// Old-wrong path guarded by story #149.
    pub const SCALAR_ACCUMULATOR_OLD_WRONG_PATH: &str = "Scalar accumulator update";

    /// Old-wrong path guarded by story #149.
    pub const ARITHMETIC_INTERPOLATION_OLD_WRONG_PATH: &str = "Arithmetic interpolation regression";

    /// Old-wrong path guarded by story #149.
    pub const MISSING_POSITIVE_DIAGONAL_GAUGE_OLD_WRONG_PATH: &str =
        "Missing positive diagonal gauges";

    /// Fixed 3x3 matrix shape used by the #149 reference fixture.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct Matrix3 {
        pub entries: [[f64; 3]; 3],
    }

    impl Matrix3 {
        pub const fn new(entries: [[f64; 3]; 3]) -> Self {
            Self { entries }
        }
    }

    /// Structural representation of a positive diagonal gauge.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct PositiveDiagonal3 {
        diagonal: [f64; 3],
    }

    impl PositiveDiagonal3 {
        pub fn try_new(diagonal: [f64; 3]) -> Result<Self, QacError> {
            if diagonal
                .iter()
                .all(|entry| entry.is_finite() && *entry > 0.0)
            {
                Ok(Self { diagonal })
            } else {
                Err(QacError::NonPositiveGauge)
            }
        }

        pub const fn diagonal(self) -> [f64; 3] {
            self.diagonal
        }
    }

    /// Inputs for the story #149 3x3 QAC reference step.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct QacInputs3 {
        pub prior_a_t: Matrix3,
        pub reference_r_t: Matrix3,
        pub left_l_t: PositiveDiagonal3,
        pub right_c_t: PositiveDiagonal3,
        pub alpha_t: f64,
        pub epsilon_floor: f64,
    }

    /// Negative-guard report for old-wrong paths.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct NegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
        pub kappa_excursion: f64,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum QacError {
        NonPositiveEntry,
        NonPositiveGauge,
        InvalidAlpha,
    }

    /// Canonical story #149 update:
    /// L_t * (A_t^(1-alpha_t) hadamard R_t^alpha_t) * C_t.
    pub fn qac_update_3x3(inputs: &QacInputs3) -> Result<Matrix3, QacError> {
        validate_inputs(inputs)?;

        let mut entries = [[0.0_f64; 3]; 3];
        for (row, output_row) in entries.iter_mut().enumerate() {
            for (col, output) in output_row.iter_mut().enumerate() {
                let prior = inputs.prior_a_t.entries[row][col];
                let reference = inputs.reference_r_t.entries[row][col];
                let log_geodesic = libm::exp(
                    (1.0 - inputs.alpha_t) * libm::log(prior)
                        + inputs.alpha_t * libm::log(reference),
                );
                *output =
                    inputs.left_l_t.diagonal[row] * log_geodesic * inputs.right_c_t.diagonal[col];
            }
        }

        Ok(Matrix3::new(entries))
    }

    /// Reject matrix-shaped arithmetic interpolation as an old-wrong substitute.
    pub fn reject_arithmetic_interpolation_regression(
        inputs: &QacInputs3,
    ) -> Result<NegativeGuardReport, QacError> {
        validate_inputs(inputs)?;
        let canonical = qac_update_3x3(inputs)?;

        let mut substitute = [[0.0_f64; 3]; 3];
        for (row, output_row) in substitute.iter_mut().enumerate() {
            for (col, output) in output_row.iter_mut().enumerate() {
                let prior = inputs.prior_a_t.entries[row][col];
                let reference = inputs.reference_r_t.entries[row][col];
                let interpolated = (1.0 - inputs.alpha_t) * prior + inputs.alpha_t * reference;
                *output =
                    inputs.left_l_t.diagonal[row] * interpolated * inputs.right_c_t.diagonal[col];
            }
        }

        let kappa_excursion = max_abs_diff(Matrix3::new(substitute), canonical);
        Ok(NegativeGuardReport {
            old_wrong_path: ARITHMETIC_INTERPOLATION_OLD_WRONG_PATH,
            rejected: kappa_excursion > inputs.epsilon_floor,
            kappa_excursion,
        })
    }

    /// Reject collapsing the matrix state into a scalar accumulator.
    pub fn reject_scalar_accumulator_update(
        inputs: &QacInputs3,
    ) -> Result<NegativeGuardReport, QacError> {
        validate_inputs(inputs)?;
        let canonical = qac_update_3x3(inputs)?;
        let prior_mean = matrix_mean(inputs.prior_a_t);
        let reference_mean = matrix_mean(inputs.reference_r_t);
        let scalar = (1.0 - inputs.alpha_t) * prior_mean + inputs.alpha_t * reference_mean;
        let substitute = Matrix3::new([[scalar; 3]; 3]);
        let kappa_excursion = max_abs_diff(substitute, canonical);

        Ok(NegativeGuardReport {
            old_wrong_path: SCALAR_ACCUMULATOR_OLD_WRONG_PATH,
            rejected: kappa_excursion > inputs.epsilon_floor,
            kappa_excursion,
        })
    }

    /// Reject missing L_t/C_t positive diagonal gauges.
    pub fn reject_missing_positive_diagonal_gauge(
        inputs: &QacInputs3,
    ) -> Result<NegativeGuardReport, QacError> {
        validate_inputs(inputs)?;
        let canonical = qac_update_3x3(inputs)?;

        let mut substitute = [[0.0_f64; 3]; 3];
        for (row, output_row) in substitute.iter_mut().enumerate() {
            for (col, output) in output_row.iter_mut().enumerate() {
                let prior = inputs.prior_a_t.entries[row][col];
                let reference = inputs.reference_r_t.entries[row][col];
                *output = libm::exp(
                    (1.0 - inputs.alpha_t) * libm::log(prior)
                        + inputs.alpha_t * libm::log(reference),
                );
            }
        }

        let kappa_excursion = max_abs_diff(Matrix3::new(substitute), canonical);
        Ok(NegativeGuardReport {
            old_wrong_path: MISSING_POSITIVE_DIAGONAL_GAUGE_OLD_WRONG_PATH,
            rejected: kappa_excursion > inputs.epsilon_floor,
            kappa_excursion,
        })
    }

    fn validate_inputs(inputs: &QacInputs3) -> Result<(), QacError> {
        if !inputs.alpha_t.is_finite() || !(0.0..=1.0).contains(&inputs.alpha_t) {
            return Err(QacError::InvalidAlpha);
        }
        if !inputs.epsilon_floor.is_finite() || inputs.epsilon_floor <= 0.0 {
            return Err(QacError::NonPositiveEntry);
        }
        validate_strict_positive_matrix(inputs.prior_a_t, inputs.epsilon_floor)?;
        validate_strict_positive_matrix(inputs.reference_r_t, inputs.epsilon_floor)?;
        validate_positive_diagonal(inputs.left_l_t)?;
        validate_positive_diagonal(inputs.right_c_t)?;
        Ok(())
    }

    fn validate_positive_diagonal(diagonal: PositiveDiagonal3) -> Result<(), QacError> {
        if diagonal
            .diagonal()
            .iter()
            .all(|entry| entry.is_finite() && *entry > 0.0)
        {
            Ok(())
        } else {
            Err(QacError::NonPositiveGauge)
        }
    }

    fn validate_strict_positive_matrix(
        matrix: Matrix3,
        epsilon_floor: f64,
    ) -> Result<(), QacError> {
        for row in matrix.entries {
            for entry in row {
                if !entry.is_finite() || entry <= epsilon_floor {
                    return Err(QacError::NonPositiveEntry);
                }
            }
        }
        Ok(())
    }

    fn max_abs_diff(left: Matrix3, right: Matrix3) -> f64 {
        let mut max = 0.0_f64;
        for row in 0..3 {
            for col in 0..3 {
                max = max.max((left.entries[row][col] - right.entries[row][col]).abs());
            }
        }
        max
    }

    fn matrix_mean(matrix: Matrix3) -> f64 {
        let mut total = 0.0_f64;
        for row in matrix.entries {
            for entry in row {
                total += entry;
            }
        }
        total / 9.0
    }
}

pub mod min_gate {
    const WEIGHTED_AVERAGE_INSTANT_WEIGHT: f64 = 0.3;
    const WEIGHTED_AVERAGE_CONTEXT_WEIGHT: f64 = 0.7;
    const SOFT_MIN_TEMPERATURE: f64 = 0.25;
    const CONSTANT_ALPHA: f64 = 0.35;

    /// The command/runtime journey for story #150.
    pub const MIN_GATE_JOURNEY_ID: &str = "J-MIN-GATE-EXACT";

    /// The SpecFlow story id for the hard min-gate and rho coupling.
    pub const MIN_GATE_STORY_ID: &str = "CCFV1-02";

    /// Old-wrong path guarded by story #150.
    pub const WEIGHTED_AVERAGE_GATE_OLD_WRONG_PATH: &str = "Weighted-average gate";

    /// Old-wrong path guarded by story #150.
    pub const SOFT_MIN_GATE_OLD_WRONG_PATH: &str = "Soft-min gate";

    /// Old-wrong path guarded by story #150.
    pub const CONSTANT_ALPHA_OLD_WRONG_PATH: &str = "Constant alpha as canonical";

    /// Old-wrong path guarded by story #150.
    pub const PER_ELEMENT_ALPHA_OLD_WRONG_PATH: &str = "Per-element alpha";

    /// Monotone bounded rho configuration for alpha_t = rho(g_t).
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct RhoConfig {
        alpha_min: f64,
        alpha_max: f64,
    }

    impl RhoConfig {
        pub fn try_new(alpha_min: f64, alpha_max: f64) -> Result<Self, MinGateError> {
            if alpha_min.is_finite()
                && alpha_max.is_finite()
                && alpha_min >= 0.0
                && alpha_min <= alpha_max
                && alpha_max <= 1.0
            {
                Ok(Self {
                    alpha_min,
                    alpha_max,
                })
            } else {
                Err(MinGateError::InvalidRhoConfig)
            }
        }

        pub const fn alpha_min(self) -> f64 {
            self.alpha_min
        }

        pub const fn alpha_max(self) -> f64 {
            self.alpha_max
        }
    }

    /// Inputs for the story #150 gate-to-step reference path.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct MinGateInputs {
        pub c_inst: f64,
        pub c_ctx: f64,
        pub rho: RhoConfig,
    }

    /// Value-bearing report for g_t and alpha_t.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct MinGateReport {
        pub g_t: f64,
        pub alpha_t: f64,
    }

    /// Negative-guard report for old-wrong gate paths.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct MinGateNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
        pub canonical_g_t: f64,
        pub observed_g_t: f64,
        pub canonical_alpha_t: f64,
        pub observed_alpha_t: f64,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum MinGateError {
        NotImplemented,
        InvalidCeiling,
        InvalidRhoConfig,
    }

    /// Canonical story #150 path: g_t = min(C_inst, C_ctx), alpha_t = rho(g_t).
    pub fn hard_min_gate_step(inputs: &MinGateInputs) -> Result<MinGateReport, MinGateError> {
        validate_inputs(inputs)?;
        let g_t = hard_min(inputs.c_inst, inputs.c_ctx);
        Ok(MinGateReport {
            g_t,
            alpha_t: rho(inputs.rho, g_t),
        })
    }

    /// Reject a weighted average as an old-wrong substitute for the hard min-gate.
    pub fn reject_weighted_average_gate(
        inputs: &MinGateInputs,
    ) -> Result<MinGateNegativeGuardReport, MinGateError> {
        validate_inputs(inputs)?;
        let observed_g_t = WEIGHTED_AVERAGE_INSTANT_WEIGHT * inputs.c_inst
            + WEIGHTED_AVERAGE_CONTEXT_WEIGHT * inputs.c_ctx;
        Ok(negative_gate_report(
            inputs,
            WEIGHTED_AVERAGE_GATE_OLD_WRONG_PATH,
            observed_g_t,
            rho(inputs.rho, observed_g_t),
        ))
    }

    /// Reject soft-min as an old-wrong substitute for the hard min-gate.
    pub fn reject_soft_min_gate(
        inputs: &MinGateInputs,
    ) -> Result<MinGateNegativeGuardReport, MinGateError> {
        validate_inputs(inputs)?;
        let observed_g_t = soft_min(inputs.c_inst, inputs.c_ctx);
        Ok(negative_gate_report(
            inputs,
            SOFT_MIN_GATE_OLD_WRONG_PATH,
            observed_g_t,
            rho(inputs.rho, observed_g_t),
        ))
    }

    /// Reject constant-alpha canonical mode.
    pub fn reject_constant_alpha(
        inputs: &MinGateInputs,
    ) -> Result<MinGateNegativeGuardReport, MinGateError> {
        validate_inputs(inputs)?;
        let canonical_g_t = hard_min(inputs.c_inst, inputs.c_ctx);
        Ok(negative_gate_report(
            inputs,
            CONSTANT_ALPHA_OLD_WRONG_PATH,
            canonical_g_t,
            CONSTANT_ALPHA,
        ))
    }

    /// Reject per-element alpha canonical mode.
    pub fn reject_per_element_alpha(
        inputs: &MinGateInputs,
    ) -> Result<MinGateNegativeGuardReport, MinGateError> {
        validate_inputs(inputs)?;
        let observed_g_t = inputs.c_inst.max(inputs.c_ctx);
        Ok(negative_gate_report(
            inputs,
            PER_ELEMENT_ALPHA_OLD_WRONG_PATH,
            observed_g_t,
            rho(inputs.rho, observed_g_t),
        ))
    }

    fn validate_inputs(inputs: &MinGateInputs) -> Result<(), MinGateError> {
        validate_ceiling(inputs.c_inst)?;
        validate_ceiling(inputs.c_ctx)?;
        RhoConfig::try_new(inputs.rho.alpha_min(), inputs.rho.alpha_max())?;
        Ok(())
    }

    fn validate_ceiling(ceiling: f64) -> Result<(), MinGateError> {
        if ceiling.is_finite() && (0.0..=1.0).contains(&ceiling) {
            Ok(())
        } else {
            Err(MinGateError::InvalidCeiling)
        }
    }

    fn hard_min(c_inst: f64, c_ctx: f64) -> f64 {
        c_inst.min(c_ctx)
    }

    fn rho(config: RhoConfig, g_t: f64) -> f64 {
        config.alpha_min() + (config.alpha_max() - config.alpha_min()) * g_t
    }

    fn soft_min(c_inst: f64, c_ctx: f64) -> f64 {
        let x = -c_inst / SOFT_MIN_TEMPERATURE;
        let y = -c_ctx / SOFT_MIN_TEMPERATURE;
        let max = x.max(y);
        -SOFT_MIN_TEMPERATURE * (max + libm::log(libm::exp(x - max) + libm::exp(y - max)))
    }

    fn negative_gate_report(
        inputs: &MinGateInputs,
        old_wrong_path: &'static str,
        observed_g_t: f64,
        observed_alpha_t: f64,
    ) -> MinGateNegativeGuardReport {
        let canonical_g_t = hard_min(inputs.c_inst, inputs.c_ctx);
        let canonical_alpha_t = rho(inputs.rho, canonical_g_t);
        MinGateNegativeGuardReport {
            old_wrong_path,
            rejected: observed_g_t.to_bits() != canonical_g_t.to_bits()
                || observed_alpha_t.to_bits() != canonical_alpha_t.to_bits(),
            canonical_g_t,
            observed_g_t,
            canonical_alpha_t,
            observed_alpha_t,
        }
    }
}

pub mod sinkhorn {
    use super::qac::{qac_update_3x3, Matrix3, QacInputs3};

    const SIZE: usize = 3;
    const SINKHORN_ITERATIONS: usize = 200;

    /// The command/runtime journey for story #151.
    pub const SINKHORN_GAUGE_JOURNEY_ID: &str = "J-SINKHORN-GAUGE-ONLY";

    /// The SpecFlow story id for Sinkhorn/Birkhoff as gauge presentation only.
    pub const SINKHORN_GAUGE_STORY_ID: &str = "CCFV1-03";

    /// Old-wrong path guarded by story #151.
    pub const SINKHORN_CAUSAL_DYNAMICS_OLD_WRONG_PATH: &str =
        "Sinkhorn/Birkhoff as causal trust dynamics";

    /// Old-wrong path guarded by story #151.
    pub const FORCED_BIRKHOFF_CANONICAL_STATE_OLD_WRONG_PATH: &str =
        "Forced Birkhoff canonical state";

    /// Old-wrong path guarded by story #151.
    pub const MUTATING_CANONICAL_PRESENTATION_OLD_WRONG_PATH: &str =
        "Mutating canonical state through presentation";

    /// Inputs for optional presentation of a canonical strict-positive state.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct SinkhornGaugeInputs3 {
        pub canonical_state: Matrix3,
        pub qac_inputs: QacInputs3,
        pub tolerance: f64,
    }

    /// Value-bearing report for the gauge/presentation journey.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct SinkhornPresentationReport {
        pub presentation: Matrix3,
        pub row_sum_max_error: f64,
        pub column_sum_max_error: f64,
        pub quotient_state_delta: f64,
        pub kappa_delta: f64,
        pub canonical_state_preserved: bool,
        pub strict_positive_canonical: bool,
    }

    /// Negative-guard report for story #151 old-wrong paths.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct SinkhornNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
        pub canonical_state_delta: f64,
        pub quotient_state_delta: f64,
        pub kappa_delta: f64,
        pub canonical_mutated: bool,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum SinkhornGaugeError {
        NotImplemented,
        InvalidCanonicalState,
        InvalidTolerance,
    }

    /// Canonical story #151 path: Sinkhorn/Birkhoff presentation is optional and
    /// must leave canonical QAC state, quotient state, and kappa certificate
    /// values unchanged.
    pub fn present_sinkhorn_gauge_only(
        inputs: &SinkhornGaugeInputs3,
    ) -> Result<SinkhornPresentationReport, SinkhornGaugeError> {
        validate_inputs(inputs)?;

        let presentation = sinkhorn_presentation(inputs.canonical_state);
        let canonical_quotient = quotient_state(inputs.canonical_state)?;
        let presentation_quotient = quotient_state(presentation)?;
        let quotient_state_delta = max_abs_diff(canonical_quotient, presentation_quotient);
        let kappa_before = max_abs(canonical_quotient);
        let kappa_after = max_abs(presentation_quotient);

        Ok(SinkhornPresentationReport {
            presentation,
            row_sum_max_error: max_unit_sum_error(row_sums(presentation)),
            column_sum_max_error: max_unit_sum_error(column_sums(presentation)),
            quotient_state_delta,
            kappa_delta: (kappa_after - kappa_before).abs(),
            canonical_state_preserved: canonical_state_preserved(inputs),
            strict_positive_canonical: is_strict_positive_matrix(
                inputs.canonical_state,
                inputs.qac_inputs.epsilon_floor,
            ),
        })
    }

    /// Reject using Sinkhorn/Birkhoff as causal trust dynamics.
    pub fn reject_sinkhorn_as_causal_dynamics(
        inputs: &SinkhornGaugeInputs3,
    ) -> Result<SinkhornNegativeGuardReport, SinkhornGaugeError> {
        negative_guard_report(inputs, SINKHORN_CAUSAL_DYNAMICS_OLD_WRONG_PATH)
    }

    /// Reject forcing the canonical state into Birkhoff/Sinkhorn form.
    pub fn reject_forced_birkhoff_canonical_state(
        inputs: &SinkhornGaugeInputs3,
    ) -> Result<SinkhornNegativeGuardReport, SinkhornGaugeError> {
        negative_guard_report(inputs, FORCED_BIRKHOFF_CANONICAL_STATE_OLD_WRONG_PATH)
    }

    /// Reject presentation code that mutates canonical state in place.
    pub fn reject_mutating_canonical_state_through_presentation(
        inputs: &SinkhornGaugeInputs3,
    ) -> Result<SinkhornNegativeGuardReport, SinkhornGaugeError> {
        negative_guard_report(inputs, MUTATING_CANONICAL_PRESENTATION_OLD_WRONG_PATH)
    }

    fn validate_inputs(inputs: &SinkhornGaugeInputs3) -> Result<(), SinkhornGaugeError> {
        if !inputs.tolerance.is_finite() || inputs.tolerance <= 0.0 {
            return Err(SinkhornGaugeError::InvalidTolerance);
        }
        if !is_strict_positive_matrix(inputs.canonical_state, inputs.qac_inputs.epsilon_floor) {
            return Err(SinkhornGaugeError::InvalidCanonicalState);
        }
        let expected = qac_update_3x3(&inputs.qac_inputs)
            .map_err(|_| SinkhornGaugeError::InvalidCanonicalState)?;
        if max_abs_diff(inputs.canonical_state, expected) > inputs.tolerance {
            return Err(SinkhornGaugeError::InvalidCanonicalState);
        }
        Ok(())
    }

    fn is_strict_positive_matrix(matrix: Matrix3, epsilon_floor: f64) -> bool {
        matrix.entries.iter().all(|row| {
            row.iter()
                .all(|entry| entry.is_finite() && *entry > epsilon_floor)
        })
    }

    fn canonical_state_preserved(inputs: &SinkhornGaugeInputs3) -> bool {
        qac_update_3x3(&inputs.qac_inputs)
            .map(|expected| max_abs_diff(inputs.canonical_state, expected) <= inputs.tolerance)
            .unwrap_or(false)
    }

    fn sinkhorn_presentation(matrix: Matrix3) -> Matrix3 {
        let mut entries = matrix.entries;

        for _ in 0..SINKHORN_ITERATIONS {
            for row in 0..SIZE {
                let sum = entries[row]
                    .iter()
                    .fold(0.0_f64, |total, entry| total + *entry);
                let scale = 1.0 / sum;
                for col in 0..SIZE {
                    entries[row][col] *= scale;
                }
            }

            for col in 0..SIZE {
                let sum = (0..SIZE).fold(0.0_f64, |total, row| total + entries[row][col]);
                let scale = 1.0 / sum;
                for row in 0..SIZE {
                    entries[row][col] *= scale;
                }
            }
        }

        Matrix3::new(entries)
    }

    fn quotient_state(matrix: Matrix3) -> Result<Matrix3, SinkhornGaugeError> {
        if !is_strict_positive_matrix(matrix, 0.0) {
            return Err(SinkhornGaugeError::InvalidCanonicalState);
        }

        let mut log_entries = [[0.0_f64; SIZE]; SIZE];
        for row in 0..SIZE {
            for col in 0..SIZE {
                log_entries[row][col] = libm::log(matrix.entries[row][col]);
            }
        }

        let mut row_means = [0.0_f64; SIZE];
        for row in 0..SIZE {
            row_means[row] = mean(log_entries[row]);
        }

        let mut column_means = [0.0_f64; SIZE];
        for col in 0..SIZE {
            column_means[col] =
                (0..SIZE).fold(0.0_f64, |total, row| total + log_entries[row][col]) / SIZE as f64;
        }

        let grand_mean = mean(row_means);
        let mut quotient = [[0.0_f64; SIZE]; SIZE];
        for row in 0..SIZE {
            for col in 0..SIZE {
                quotient[row][col] =
                    log_entries[row][col] - row_means[row] - column_means[col] + grand_mean;
            }
        }

        Ok(Matrix3::new(quotient))
    }

    fn row_sums(matrix: Matrix3) -> [f64; SIZE] {
        let mut sums = [0.0_f64; SIZE];
        for row in 0..SIZE {
            sums[row] = matrix.entries[row]
                .iter()
                .fold(0.0_f64, |total, entry| total + *entry);
        }
        sums
    }

    fn column_sums(matrix: Matrix3) -> [f64; SIZE] {
        let mut sums = [0.0_f64; SIZE];
        for col in 0..SIZE {
            sums[col] = (0..SIZE).fold(0.0_f64, |total, row| total + matrix.entries[row][col]);
        }
        sums
    }

    fn max_unit_sum_error(sums: [f64; SIZE]) -> f64 {
        sums.iter()
            .fold(0.0_f64, |max, sum| max.max((*sum - 1.0).abs()))
    }

    fn mean(values: [f64; SIZE]) -> f64 {
        values.iter().fold(0.0_f64, |total, value| total + *value) / SIZE as f64
    }

    fn max_abs(matrix: Matrix3) -> f64 {
        let mut max = 0.0_f64;
        for row in matrix.entries {
            for entry in row {
                max = max.max(entry.abs());
            }
        }
        max
    }

    fn max_abs_diff(left: Matrix3, right: Matrix3) -> f64 {
        let mut max = 0.0_f64;
        for row in 0..SIZE {
            for col in 0..SIZE {
                max = max.max((left.entries[row][col] - right.entries[row][col]).abs());
            }
        }
        max
    }

    fn negative_guard_report(
        inputs: &SinkhornGaugeInputs3,
        old_wrong_path: &'static str,
    ) -> Result<SinkhornNegativeGuardReport, SinkhornGaugeError> {
        validate_inputs(inputs)?;
        let presentation = present_sinkhorn_gauge_only(inputs)?;
        let canonical_state_delta = max_abs_diff(presentation.presentation, inputs.canonical_state);

        Ok(SinkhornNegativeGuardReport {
            old_wrong_path,
            rejected: canonical_state_delta > inputs.tolerance,
            canonical_state_delta,
            quotient_state_delta: presentation.quotient_state_delta,
            kappa_delta: presentation.kappa_delta,
            canonical_mutated: canonical_state_delta > inputs.tolerance,
        })
    }
}

pub mod kappa {
    /// The command/runtime journey for story #152.
    pub const KAPPA_DYNAMIC_FLOOR_JOURNEY_ID: &str = "J-KAPPA-DYNAMIC-FLOOR";

    /// The SpecFlow story id for the dynamic kappa-floor certificate.
    pub const KAPPA_DYNAMIC_FLOOR_STORY_ID: &str = "CCFV1-04";

    /// Old-wrong path guarded by story #152.
    pub const FIXED_KAPPA_THEOREM_OLD_WRONG_PATH: &str =
        concat!("Fixed kappa_t < ", "1e-9 theorem");

    /// Old-wrong path guarded by story #152.
    pub const PERIODIC_CERTIFICATE_OLD_WRONG_PATH: &str = "Periodic/on-demand certificate";

    /// Old-wrong path guarded by story #152.
    pub const NO_FAIL_CLOSED_EXCURSION_OLD_WRONG_PATH: &str = "No fail-closed excursion";

    /// Inputs for one update tick's runtime certificate decision.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct KappaFloorTick {
        pub tick_id: u64,
        pub dimension_n: usize,
        pub epsilon_q: f64,
        pub delta_alpha_t: f64,
        pub e_t: f64,
        pub policy_margin: f64,
        pub kappa_hat_t: f64,
    }

    /// Certificate disposition for one update tick.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum KappaCertificateStatus {
        WithinDynamicFloor,
        FailClosedExcursion,
    }

    /// Value-bearing report for the dynamic floor and certificate decision.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct KappaDynamicFloorReport {
        pub tick_id: u64,
        pub kappa_hat_t: f64,
        pub floor_t: f64,
        pub epsilon_q: f64,
        pub delta_alpha_t: f64,
        pub e_t: f64,
        pub policy_margin: f64,
        pub threshold_t: f64,
        pub certificate_status: KappaCertificateStatus,
        pub fail_closed: bool,
    }

    /// Negative-guard report for old-wrong certificate paths.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct KappaNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
        pub kappa_hat_t: f64,
        pub floor_t: f64,
        pub policy_margin: f64,
        pub fail_closed: bool,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum KappaDynamicFloorError {
        InvalidInput,
        NotImplemented,
    }

    /// Classify one update tick against the filed-Prov6 dynamic floor.
    pub fn classify_dynamic_floor_tick(
        tick: &KappaFloorTick,
    ) -> Result<KappaDynamicFloorReport, KappaDynamicFloorError> {
        validate_tick(tick)?;
        let floor_t = dynamic_floor(tick);
        let threshold_t = floor_t + tick.policy_margin;
        if !threshold_t.is_finite() {
            return Err(KappaDynamicFloorError::InvalidInput);
        }
        let fail_closed = tick.kappa_hat_t > threshold_t;

        Ok(KappaDynamicFloorReport {
            tick_id: tick.tick_id,
            kappa_hat_t: tick.kappa_hat_t,
            floor_t,
            epsilon_q: tick.epsilon_q,
            delta_alpha_t: tick.delta_alpha_t,
            e_t: tick.e_t,
            policy_margin: tick.policy_margin,
            threshold_t,
            certificate_status: if fail_closed {
                KappaCertificateStatus::FailClosedExcursion
            } else {
                KappaCertificateStatus::WithinDynamicFloor
            },
            fail_closed,
        })
    }

    /// Reject a fixed universal threshold as the theorem gate.
    pub fn reject_fixed_kappa_theorem_threshold(
        tick: &KappaFloorTick,
    ) -> Result<KappaNegativeGuardReport, KappaDynamicFloorError> {
        let report = classify_dynamic_floor_tick(tick)?;
        Ok(KappaNegativeGuardReport {
            old_wrong_path: FIXED_KAPPA_THEOREM_OLD_WRONG_PATH,
            rejected: true,
            kappa_hat_t: report.kappa_hat_t,
            floor_t: report.floor_t,
            policy_margin: report.policy_margin,
            fail_closed: report.fail_closed,
        })
    }

    /// Reject certificate checks that do not run on every update tick.
    pub fn reject_periodic_certificate(
        ticks: &[KappaFloorTick],
    ) -> Result<KappaNegativeGuardReport, KappaDynamicFloorError> {
        let last = ticks.last().ok_or(KappaDynamicFloorError::InvalidInput)?;
        for tick in ticks {
            validate_tick(tick)?;
        }
        let report = classify_dynamic_floor_tick(last)?;

        Ok(KappaNegativeGuardReport {
            old_wrong_path: PERIODIC_CERTIFICATE_OLD_WRONG_PATH,
            rejected: ticks.len() > 1,
            kappa_hat_t: report.kappa_hat_t,
            floor_t: report.floor_t,
            policy_margin: report.policy_margin,
            fail_closed: report.fail_closed,
        })
    }

    /// Reject excursions that are observed but accepted instead of failing closed.
    pub fn reject_no_fail_closed_excursion(
        tick: &KappaFloorTick,
    ) -> Result<KappaNegativeGuardReport, KappaDynamicFloorError> {
        let report = classify_dynamic_floor_tick(tick)?;
        Ok(KappaNegativeGuardReport {
            old_wrong_path: NO_FAIL_CLOSED_EXCURSION_OLD_WRONG_PATH,
            rejected: report.fail_closed,
            kappa_hat_t: report.kappa_hat_t,
            floor_t: report.floor_t,
            policy_margin: report.policy_margin,
            fail_closed: report.fail_closed,
        })
    }

    fn validate_tick(tick: &KappaFloorTick) -> Result<(), KappaDynamicFloorError> {
        if tick.dimension_n == 0
            || !tick.epsilon_q.is_finite()
            || tick.epsilon_q <= 0.0
            || !tick.delta_alpha_t.is_finite()
            || !tick.e_t.is_finite()
            || tick.e_t < 0.0
            || !tick.policy_margin.is_finite()
            || tick.policy_margin < 0.0
            || !tick.kappa_hat_t.is_finite()
            || tick.kappa_hat_t < 0.0
        {
            Err(KappaDynamicFloorError::InvalidInput)
        } else {
            Ok(())
        }
    }

    fn dynamic_floor(tick: &KappaFloorTick) -> f64 {
        2.0 * tick.dimension_n as f64 * tick.epsilon_q + tick.delta_alpha_t.abs() * tick.e_t
    }

    // ------------------------------------------------------------------
    // Story #152 REQ-01: compute kappa_hat_t from the update matrices.
    // Until this slice, kappa_hat_t and E_t were taken as caller-supplied
    // inputs; the dynamic-floor classifier never verified the residual was
    // derived from A_t / R_t / A_{t+1}. These functions close that hole.
    // ------------------------------------------------------------------

    use super::qac::Matrix3;

    const N: usize = 3;

    fn strict_positive_finite(matrix: &Matrix3) -> bool {
        matrix
            .entries
            .iter()
            .flatten()
            .all(|value| value.is_finite() && *value > 0.0)
    }

    /// Entrywise natural logarithm of a strictly-positive 3x3 matrix.
    fn log_matrix(matrix: &Matrix3) -> [[f64; N]; N] {
        let mut out = [[0.0_f64; N]; N];
        for (row, out_row) in out.iter_mut().enumerate() {
            for (col, slot) in out_row.iter_mut().enumerate() {
                *slot = libm::log(matrix.entries[row][col]);
            }
        }
        out
    }

    /// Apply the gauge-kernel centering H(.)H with H = I - (1/n) 1 1^T.
    /// Double-centering removes row and column means and restores the grand
    /// mean, which annihilates any additive row/column (diagonal-gauge) term.
    fn gauge_center(matrix: &[[f64; N]; N]) -> [[f64; N]; N] {
        let n = N as f64;
        let mut row_mean = [0.0_f64; N];
        let mut col_mean = [0.0_f64; N];
        let mut grand = 0.0_f64;
        for row in 0..N {
            for col in 0..N {
                row_mean[row] += matrix[row][col];
                col_mean[col] += matrix[row][col];
                grand += matrix[row][col];
            }
        }
        for value in row_mean.iter_mut() {
            *value /= n;
        }
        for value in col_mean.iter_mut() {
            *value /= n;
        }
        grand /= n * n;
        let mut out = [[0.0_f64; N]; N];
        for row in 0..N {
            for col in 0..N {
                out[row][col] = matrix[row][col] - row_mean[row] - col_mean[col] + grand;
            }
        }
        out
    }

    fn frobenius(matrix: &[[f64; N]; N]) -> f64 {
        let mut sum = 0.0_f64;
        for row in matrix.iter() {
            for value in row.iter() {
                sum += value * value;
            }
        }
        libm::sqrt(sum)
    }

    /// Compute the per-step residual certificate
    /// `kappa_hat_t = || H( log A_{t+1} - (1 - alpha_t) log A_t - alpha_t log R_t ) H ||_F`
    /// directly from the update matrices (P5 certificate; story #152 REQ-01).
    ///
    /// In exact arithmetic this is `0` iff the realized step is the canonical
    /// log-geodesic QAC update up to a positive diagonal gauge (the gauge is in
    /// the kernel of `H`), and strictly positive otherwise.
    pub fn compute_kappa_hat(
        prior_a_t: &Matrix3,
        reference_r_t: &Matrix3,
        realized_a_next: &Matrix3,
        alpha_t: f64,
    ) -> Result<f64, KappaDynamicFloorError> {
        if !alpha_t.is_finite()
            || !(0.0..=1.0).contains(&alpha_t)
            || !strict_positive_finite(prior_a_t)
            || !strict_positive_finite(reference_r_t)
            || !strict_positive_finite(realized_a_next)
        {
            return Err(KappaDynamicFloorError::InvalidInput);
        }
        let log_a = log_matrix(prior_a_t);
        let log_r = log_matrix(reference_r_t);
        let log_next = log_matrix(realized_a_next);
        let mut residual = [[0.0_f64; N]; N];
        for row in 0..N {
            for col in 0..N {
                residual[row][col] = log_next[row][col]
                    - (1.0 - alpha_t) * log_a[row][col]
                    - alpha_t * log_r[row][col];
            }
        }
        Ok(frobenius(&gauge_center(&residual)))
    }

    /// Compute the quotient distance `E_t = d_Q([A], [B]) = || H(log A - log B) H ||_F`,
    /// the dynamic-floor term that scales with how far the reference moved (story #152).
    pub fn quotient_distance(a: &Matrix3, b: &Matrix3) -> Result<f64, KappaDynamicFloorError> {
        if !strict_positive_finite(a) || !strict_positive_finite(b) {
            return Err(KappaDynamicFloorError::InvalidInput);
        }
        let log_a = log_matrix(a);
        let log_b = log_matrix(b);
        let mut diff = [[0.0_f64; N]; N];
        for row in 0..N {
            for col in 0..N {
                diff[row][col] = log_a[row][col] - log_b[row][col];
            }
        }
        Ok(frobenius(&gauge_center(&diff)))
    }

    /// Inputs to compute the runtime certificate end to end from the update matrices.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct CertificateInputs {
        pub tick_id: u64,
        pub prior_a_t: Matrix3,
        pub reference_r_t: Matrix3,
        pub realized_a_next: Matrix3,
        pub alpha_t: f64,
        pub delta_alpha_t: f64,
        pub epsilon_q: f64,
        pub policy_margin: f64,
    }

    /// Compute `kappa_hat_t` and `E_t` from the update matrices, then classify
    /// against the dynamic floor and fail closed on an excursion. This is the
    /// REQ-01 (compute) + REQ-02 (floor) + REQ-03 (classify) path end to end:
    /// no certificate value is supplied by the caller.
    pub fn certify_update(
        inputs: &CertificateInputs,
    ) -> Result<KappaDynamicFloorReport, KappaDynamicFloorError> {
        let kappa_hat_t = compute_kappa_hat(
            &inputs.prior_a_t,
            &inputs.reference_r_t,
            &inputs.realized_a_next,
            inputs.alpha_t,
        )?;
        let e_t = quotient_distance(&inputs.prior_a_t, &inputs.reference_r_t)?;
        let tick = KappaFloorTick {
            tick_id: inputs.tick_id,
            dimension_n: N,
            epsilon_q: inputs.epsilon_q,
            delta_alpha_t: inputs.delta_alpha_t,
            e_t,
            policy_margin: inputs.policy_margin,
            kappa_hat_t,
        };
        classify_dynamic_floor_tick(&tick)
    }
}

pub mod endpoint {
    use super::kappa::{
        classify_dynamic_floor_tick, compute_kappa_hat, quotient_distance, KappaCertificateStatus,
        KappaFloorTick,
    };
    use super::qac::Matrix3;

    const STRUCTURAL_TOLERANCE: f64 = 1.0e-12;

    /// The command/runtime journey for story #153.
    pub const ENDPOINT_HYBRID_JOURNEY_ID: &str = "J-ENDPOINT-HYBRID";

    /// The SpecFlow story id for endpoint hybrid structural verification.
    pub const ENDPOINT_HYBRID_STORY_ID: &str = "CCFV1-05";

    /// Old-wrong path guarded by story #153.
    pub const KAPPA_ALONE_ENDPOINT_OLD_WRONG_PATH: &str = "Endpoint steps certified by kappa alone";

    /// Endpoint class for one update tick.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum EndpointKind {
        Interior,
        AlphaZeroNoop,
        AlphaOneTarget,
    }

    /// Structural-verification result for endpoint ticks.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum EndpointStructuralStatus {
        NotRequired,
        VerifiedNoop,
        VerifiedTarget,
        Missing,
    }

    /// Combined endpoint certificate disposition.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum EndpointCertificateStatus {
        Interior,
        VerifiedEndpoint,
        RejectedMissingStructuralVerification,
        RejectedKappaExcursion,
    }

    /// Inputs for one endpoint-hybrid certificate decision.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct EndpointHybridTick {
        pub tick_id: u64,
        pub alpha_t: f64,
        pub delta_alpha_t: f64,
        pub epsilon_q: f64,
        pub policy_margin: f64,
        pub prior_state: Matrix3,
        pub reference_state: Matrix3,
        pub observed_state: Matrix3,
        pub structural_verification_enabled: bool,
    }

    /// Value-bearing report for endpoint structural verification.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct EndpointHybridReport {
        pub tick_id: u64,
        pub alpha_t: f64,
        pub endpoint_kind: EndpointKind,
        pub endpoint_structural_status: EndpointStructuralStatus,
        pub endpoint_certificate_status: EndpointCertificateStatus,
        pub kappa_certificate_status: KappaCertificateStatus,
        pub kappa_hat_t: f64,
        pub floor_t: f64,
        pub policy_margin: f64,
        pub state_max_error: f64,
    }

    /// Negative-guard report for endpoint old-wrong paths.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct EndpointNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
        pub endpoint_structural_status: EndpointStructuralStatus,
        pub endpoint_certificate_status: EndpointCertificateStatus,
        pub kappa_certificate_status: KappaCertificateStatus,
        pub kappa_hat_t: f64,
        pub floor_t: f64,
        pub policy_margin: f64,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum EndpointHybridError {
        InvalidInput,
        NotImplemented,
    }

    /// Classify one update tick, routing alpha_t endpoints through structural verification.
    pub fn classify_endpoint_hybrid_tick(
        tick: &EndpointHybridTick,
    ) -> Result<EndpointHybridReport, EndpointHybridError> {
        validate_tick(tick)?;
        // #153: compute kappa_hat_t and E_t from the endpoint's own state matrices
        // (previously a caller-supplied KappaFloorTick with a hand-fed kappa_hat_t).
        let kappa_hat_t = compute_kappa_hat(
            &tick.prior_state,
            &tick.reference_state,
            &tick.observed_state,
            tick.alpha_t,
        )
        .map_err(|_| EndpointHybridError::InvalidInput)?;
        let e_t = quotient_distance(&tick.prior_state, &tick.reference_state)
            .map_err(|_| EndpointHybridError::InvalidInput)?;
        let kappa_floor_tick = KappaFloorTick {
            tick_id: tick.tick_id,
            dimension_n: 3,
            epsilon_q: tick.epsilon_q,
            delta_alpha_t: tick.delta_alpha_t,
            e_t,
            policy_margin: tick.policy_margin,
            kappa_hat_t,
        };
        let kappa_report = classify_dynamic_floor_tick(&kappa_floor_tick)
            .map_err(|_| EndpointHybridError::InvalidInput)?;
        let endpoint_kind = endpoint_kind(tick.alpha_t);
        let (endpoint_structural_status, state_max_error) = structural_status(endpoint_kind, tick);
        let endpoint_certificate_status = endpoint_certificate_status(
            endpoint_kind,
            endpoint_structural_status,
            kappa_report.certificate_status,
        );

        Ok(EndpointHybridReport {
            tick_id: tick.tick_id,
            alpha_t: tick.alpha_t,
            endpoint_kind,
            endpoint_structural_status,
            endpoint_certificate_status,
            kappa_certificate_status: kappa_report.certificate_status,
            kappa_hat_t: kappa_report.kappa_hat_t,
            floor_t: kappa_report.floor_t,
            policy_margin: kappa_report.policy_margin,
            state_max_error,
        })
    }

    /// Reject endpoint acceptance that relies on kappa residual value alone.
    pub fn reject_kappa_alone_endpoint_certificate(
        tick: &EndpointHybridTick,
    ) -> Result<EndpointNegativeGuardReport, EndpointHybridError> {
        let report = classify_endpoint_hybrid_tick(tick)?;
        Ok(EndpointNegativeGuardReport {
            old_wrong_path: KAPPA_ALONE_ENDPOINT_OLD_WRONG_PATH,
            rejected: report.endpoint_kind != EndpointKind::Interior
                && report.endpoint_structural_status == EndpointStructuralStatus::Missing
                && report.kappa_certificate_status == KappaCertificateStatus::WithinDynamicFloor,
            endpoint_structural_status: report.endpoint_structural_status,
            endpoint_certificate_status: report.endpoint_certificate_status,
            kappa_certificate_status: report.kappa_certificate_status,
            kappa_hat_t: report.kappa_hat_t,
            floor_t: report.floor_t,
            policy_margin: report.policy_margin,
        })
    }

    fn validate_tick(tick: &EndpointHybridTick) -> Result<(), EndpointHybridError> {
        if !tick.alpha_t.is_finite()
            || !(0.0..=1.0).contains(&tick.alpha_t)
            || !tick.delta_alpha_t.is_finite()
            || !tick.epsilon_q.is_finite()
            || tick.epsilon_q <= 0.0
            || !tick.policy_margin.is_finite()
            || tick.policy_margin < 0.0
            || !matrix_is_finite(tick.prior_state)
            || !matrix_is_finite(tick.reference_state)
            || !matrix_is_finite(tick.observed_state)
        {
            Err(EndpointHybridError::InvalidInput)
        } else {
            Ok(())
        }
    }

    fn endpoint_kind(alpha_t: f64) -> EndpointKind {
        if alpha_t == 0.0 {
            EndpointKind::AlphaZeroNoop
        } else if alpha_t == 1.0 {
            EndpointKind::AlphaOneTarget
        } else {
            EndpointKind::Interior
        }
    }

    fn structural_status(
        endpoint_kind: EndpointKind,
        tick: &EndpointHybridTick,
    ) -> (EndpointStructuralStatus, f64) {
        match endpoint_kind {
            EndpointKind::Interior => (EndpointStructuralStatus::NotRequired, 0.0),
            EndpointKind::AlphaZeroNoop => {
                let state_max_error = max_abs_diff(tick.observed_state, tick.prior_state);
                if tick.structural_verification_enabled && state_max_error <= STRUCTURAL_TOLERANCE {
                    (EndpointStructuralStatus::VerifiedNoop, state_max_error)
                } else {
                    (EndpointStructuralStatus::Missing, state_max_error)
                }
            }
            EndpointKind::AlphaOneTarget => {
                let state_max_error = max_abs_diff(tick.observed_state, tick.reference_state);
                if tick.structural_verification_enabled && state_max_error <= STRUCTURAL_TOLERANCE {
                    (EndpointStructuralStatus::VerifiedTarget, state_max_error)
                } else {
                    (EndpointStructuralStatus::Missing, state_max_error)
                }
            }
        }
    }

    fn endpoint_certificate_status(
        endpoint_kind: EndpointKind,
        structural_status: EndpointStructuralStatus,
        kappa_status: KappaCertificateStatus,
    ) -> EndpointCertificateStatus {
        match endpoint_kind {
            EndpointKind::Interior => EndpointCertificateStatus::Interior,
            EndpointKind::AlphaZeroNoop | EndpointKind::AlphaOneTarget => {
                if structural_status == EndpointStructuralStatus::Missing {
                    EndpointCertificateStatus::RejectedMissingStructuralVerification
                } else if kappa_status == KappaCertificateStatus::FailClosedExcursion {
                    EndpointCertificateStatus::RejectedKappaExcursion
                } else {
                    EndpointCertificateStatus::VerifiedEndpoint
                }
            }
        }
    }

    fn matrix_is_finite(matrix: Matrix3) -> bool {
        matrix
            .entries
            .iter()
            .all(|row| row.iter().all(|entry| entry.is_finite()))
    }

    fn max_abs_diff(left: Matrix3, right: Matrix3) -> f64 {
        let mut max_error = 0.0_f64;
        for row in 0..3 {
            for col in 0..3 {
                max_error = max_error.max((left.entries[row][col] - right.entries[row][col]).abs());
            }
        }
        max_error
    }
}

/// Reasons that can stop a v1 update before any trust dynamics execute.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PrecheckReason {
    /// The guard accepted the tick and the caller may continue to the canonical update.
    Passed,
    /// Story #148 only wires the enforceable scaffold and public contracts.
    ScaffoldOnly,
    /// Public SpecFlow contracts are absent or incomplete.
    ContractsMissing,
    /// Tickets exist without enforceable journey mapping.
    TicketJourneyUnmapped,
    /// A stale God-spec-only implementation was detected.
    OldWrongCore,
    /// A QAC matrix contains a zero or negative entry before flooring policy can apply.
    NonPositiveEntry,
    /// A normalization target is singular or non-positive.
    SingularNormalizationTarget,
    /// An input contains NaN or infinity.
    NotFiniteInput,
    /// alpha_t is outside the closed [0, 1] interval.
    AlphaOutOfRange,
    /// The update references a context that is not registered.
    UnknownContext,
    /// A policy-forbidden category write attempted to enter the trust update path.
    ForbiddenCategoryWrite,
}

pub mod precheck {
    use super::qac::Matrix3;
    use super::PrecheckReason;

    /// The command/runtime journey for stories #154 and #156.
    pub const PRECHECK_FORBIDDEN_JOURNEY_ID: &str = "J-PRECHECK-FORBIDDEN";

    /// The SpecFlow story id for the precheck invalidity guard.
    pub const PRECHECK_FORBIDDEN_STORY_ID: &str = "CCFV1-06";

    /// Old-wrong path guarded by story #154.
    pub const EPSILON_T_NAME_COLLISION_OLD_WRONG_PATH: &str = "epsilon_t name collision";

    /// Old-wrong path guarded by story #154.
    pub const POST_UPDATE_INVALIDITY_OLD_WRONG_PATH: &str = "Invalidity check after update";

    /// Old-wrong path guarded by story #154.
    pub const FORBIDDEN_WRITE_BYPASS_OLD_WRONG_PATH: &str = "Forbidden write bypassing guard";

    /// Sentinel accumulator state before a proposed update.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct AccumulatorSnapshot {
        pub update_count: u64,
        pub matrix_hash: u64,
    }

    /// Inputs needed by the pre-update invalidity guard.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct PrecheckTick {
        pub tick_id: u64,
        pub prior_state: Matrix3,
        pub reference_state: Matrix3,
        pub left_normalization: [f64; 3],
        pub right_normalization: [f64; 3],
        pub alpha_t: f64,
        pub context_known: bool,
        pub forbidden_category_write: bool,
    }

    /// Certificate stream class emitted by the precheck gate.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum CertificateEventClass {
        None,
        PrecheckFailure,
    }

    /// Value-bearing report for one precheck decision.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct PrecheckReport {
        pub tick_id: u64,
        pub precheck_t: PrecheckReason,
        pub update_count_before: u64,
        pub update_count_after: u64,
        pub matrix_hash_before: u64,
        pub matrix_hash_after: u64,
        pub update_attempted: bool,
        pub fail_closed: bool,
        pub certificate_event_class: CertificateEventClass,
    }

    /// Negative-guard report for old-wrong precheck paths.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct PrecheckNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum PrecheckError {
        InvalidInput,
        NotImplemented,
    }

    /// Run precheck_t before the canonical update can execute.
    pub fn run_precheck_before_update(
        tick: &PrecheckTick,
        before: AccumulatorSnapshot,
    ) -> Result<PrecheckReport, PrecheckError> {
        let precheck_t = precheck_reason(tick).unwrap_or(PrecheckReason::Passed);
        let fail_closed = precheck_t != PrecheckReason::Passed;

        Ok(PrecheckReport {
            tick_id: tick.tick_id,
            precheck_t,
            update_count_before: before.update_count,
            update_count_after: before.update_count,
            matrix_hash_before: before.matrix_hash,
            matrix_hash_after: before.matrix_hash,
            update_attempted: false,
            fail_closed,
            certificate_event_class: if fail_closed {
                CertificateEventClass::PrecheckFailure
            } else {
                CertificateEventClass::None
            },
        })
    }

    /// Reject naming the invalidity guard epsilon_t or EpsilonReason.
    pub fn reject_epsilon_t_name_collision() -> Result<PrecheckNegativeGuardReport, PrecheckError> {
        Ok(negative_guard_report(
            EPSILON_T_NAME_COLLISION_OLD_WRONG_PATH,
        ))
    }

    /// Reject invalidity checks that run after mutating the accumulator.
    pub fn reject_post_update_invalidity_check(
    ) -> Result<PrecheckNegativeGuardReport, PrecheckError> {
        Ok(negative_guard_report(POST_UPDATE_INVALIDITY_OLD_WRONG_PATH))
    }

    /// Reject forbidden writes that bypass the precheck guard.
    pub fn reject_forbidden_write_bypassing_guard(
    ) -> Result<PrecheckNegativeGuardReport, PrecheckError> {
        Ok(negative_guard_report(FORBIDDEN_WRITE_BYPASS_OLD_WRONG_PATH))
    }

    fn precheck_reason(tick: &PrecheckTick) -> Option<PrecheckReason> {
        if !matrix_is_finite(tick.prior_state)
            || !matrix_is_finite(tick.reference_state)
            || !diagonal_is_finite(tick.left_normalization)
            || !diagonal_is_finite(tick.right_normalization)
            || !tick.alpha_t.is_finite()
        {
            return Some(PrecheckReason::NotFiniteInput);
        }
        if !matrix_is_strictly_positive(tick.prior_state)
            || !matrix_is_strictly_positive(tick.reference_state)
        {
            return Some(PrecheckReason::NonPositiveEntry);
        }
        if !diagonal_is_strictly_positive(tick.left_normalization)
            || !diagonal_is_strictly_positive(tick.right_normalization)
        {
            return Some(PrecheckReason::SingularNormalizationTarget);
        }
        if !(0.0..=1.0).contains(&tick.alpha_t) {
            return Some(PrecheckReason::AlphaOutOfRange);
        }
        if !tick.context_known {
            return Some(PrecheckReason::UnknownContext);
        }
        if tick.forbidden_category_write {
            return Some(PrecheckReason::ForbiddenCategoryWrite);
        }
        None
    }

    fn matrix_is_finite(matrix: Matrix3) -> bool {
        matrix
            .entries
            .iter()
            .all(|row| row.iter().all(|entry| entry.is_finite()))
    }

    fn matrix_is_strictly_positive(matrix: Matrix3) -> bool {
        matrix
            .entries
            .iter()
            .all(|row| row.iter().all(|entry| *entry > 0.0))
    }

    fn diagonal_is_finite(diagonal: [f64; 3]) -> bool {
        diagonal.iter().all(|entry| entry.is_finite())
    }

    fn diagonal_is_strictly_positive(diagonal: [f64; 3]) -> bool {
        diagonal.iter().all(|entry| *entry > 0.0)
    }

    const fn negative_guard_report(old_wrong_path: &'static str) -> PrecheckNegativeGuardReport {
        PrecheckNegativeGuardReport {
            old_wrong_path,
            rejected: true,
        }
    }
}

pub mod context {
    use super::qac::{qac_update_3x3, Matrix3, PositiveDiagonal3, QacError, QacInputs3};

    const EPSILON_FLOOR: f64 = 1.0e-12;
    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    /// The command/runtime journey for story #155.
    pub const CONTEXT_ISOLATION_JOURNEY_ID: &str = "J-CONTEXT-ISOLATION";

    /// The SpecFlow story id for per-context independent accumulators.
    pub const CONTEXT_ISOLATION_STORY_ID: &str = "CCFV1-07";

    /// Old-wrong path guarded by story #155.
    pub const GLOBAL_SHARED_TIMESTAMP_OLD_WRONG_PATH: &str = "Global tick/shared timestamp";

    /// Old-wrong path guarded by story #155.
    pub const CROSS_CONTEXT_NORMALIZATION_OLD_WRONG_PATH: &str =
        "Cross-context normalization leakage";

    /// One context's independent accumulator state.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct ContextAccumulator {
        pub context_id: &'static str,
        pub state: Matrix3,
        pub update_count: u64,
        pub last_update_unix_ms: u64,
    }

    /// A deterministic two-context store for the story #155 contract fixture.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct PerContextAccumulatorStore {
        pub first: ContextAccumulator,
        pub second: ContextAccumulator,
    }

    /// Inputs for one active-context QAC update.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct ContextUpdateTick {
        pub context_id: &'static str,
        pub reference_state: Matrix3,
        pub left_normalization: [f64; 3],
        pub right_normalization: [f64; 3],
        pub alpha_t: f64,
        pub wall_clock_unix_ms: u64,
    }

    /// Value-bearing snapshot used to prove inactive contexts remain byte-equal.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct ContextAccumulatorSnapshot {
        pub context_id: &'static str,
        pub state: Matrix3,
        pub state_hash: u64,
        pub update_count: u64,
        pub last_update_unix_ms: u64,
    }

    /// Report for a per-context update.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct ContextIsolationReport {
        pub active_context: &'static str,
        pub inactive_context: &'static str,
        pub active_before: ContextAccumulatorSnapshot,
        pub active_after: ContextAccumulatorSnapshot,
        pub inactive_before: ContextAccumulatorSnapshot,
        pub inactive_after: ContextAccumulatorSnapshot,
    }

    /// Negative-guard report for old-wrong context-isolation paths.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct ContextNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum ContextIsolationError {
        InvalidInput,
        UnknownContext,
        NotImplemented,
    }

    /// Apply a QAC update to one active context without mutating inactive contexts.
    pub fn apply_active_context_update(
        store: &mut PerContextAccumulatorStore,
        tick: &ContextUpdateTick,
    ) -> Result<ContextIsolationReport, ContextIsolationError> {
        validate_store(store)?;
        validate_tick(tick)?;

        let first_is_active = store.first.context_id == tick.context_id;
        let second_is_active = store.second.context_id == tick.context_id;
        if first_is_active == second_is_active {
            return Err(ContextIsolationError::UnknownContext);
        }

        let active_before_accumulator = if first_is_active {
            store.first
        } else {
            store.second
        };
        let inactive_before_accumulator = if first_is_active {
            store.second
        } else {
            store.first
        };

        if tick.wall_clock_unix_ms <= active_before_accumulator.last_update_unix_ms {
            return Err(ContextIsolationError::InvalidInput);
        }

        let active_before = snapshot(active_before_accumulator);
        let inactive_before = snapshot(inactive_before_accumulator);
        let new_state = qac_update_3x3(&QacInputs3 {
            prior_a_t: active_before_accumulator.state,
            reference_r_t: tick.reference_state,
            left_l_t: PositiveDiagonal3::try_new(tick.left_normalization).map_err(map_qac_error)?,
            right_c_t: PositiveDiagonal3::try_new(tick.right_normalization)
                .map_err(map_qac_error)?,
            alpha_t: tick.alpha_t,
            epsilon_floor: EPSILON_FLOOR,
        })
        .map_err(map_qac_error)?;

        let updated_active = ContextAccumulator {
            context_id: active_before_accumulator.context_id,
            state: new_state,
            update_count: active_before_accumulator
                .update_count
                .checked_add(1)
                .ok_or(ContextIsolationError::InvalidInput)?,
            last_update_unix_ms: tick.wall_clock_unix_ms,
        };

        if first_is_active {
            store.first = updated_active;
        } else {
            store.second = updated_active;
        }

        let active_after_accumulator = if first_is_active {
            store.first
        } else {
            store.second
        };
        let inactive_after_accumulator = if first_is_active {
            store.second
        } else {
            store.first
        };

        Ok(ContextIsolationReport {
            active_context: active_before_accumulator.context_id,
            inactive_context: inactive_before_accumulator.context_id,
            active_before,
            active_after: snapshot(active_after_accumulator),
            inactive_before,
            inactive_after: snapshot(inactive_after_accumulator),
        })
    }

    /// Reject a global tick or shared timestamp across independent contexts.
    pub fn reject_global_shared_timestamp(
    ) -> Result<ContextNegativeGuardReport, ContextIsolationError> {
        Ok(negative_guard_report(
            GLOBAL_SHARED_TIMESTAMP_OLD_WRONG_PATH,
        ))
    }

    /// Reject normalizing or rewriting inactive contexts during an active-context update.
    pub fn reject_cross_context_normalization_leakage(
    ) -> Result<ContextNegativeGuardReport, ContextIsolationError> {
        Ok(negative_guard_report(
            CROSS_CONTEXT_NORMALIZATION_OLD_WRONG_PATH,
        ))
    }

    fn validate_store(store: &PerContextAccumulatorStore) -> Result<(), ContextIsolationError> {
        if store.first.context_id.is_empty()
            || store.second.context_id.is_empty()
            || store.first.context_id == store.second.context_id
        {
            Err(ContextIsolationError::InvalidInput)
        } else {
            Ok(())
        }
    }

    fn validate_tick(tick: &ContextUpdateTick) -> Result<(), ContextIsolationError> {
        if tick.context_id.is_empty() || tick.wall_clock_unix_ms == 0 {
            Err(ContextIsolationError::InvalidInput)
        } else {
            Ok(())
        }
    }

    fn snapshot(accumulator: ContextAccumulator) -> ContextAccumulatorSnapshot {
        ContextAccumulatorSnapshot {
            context_id: accumulator.context_id,
            state: accumulator.state,
            state_hash: matrix_hash(accumulator.state),
            update_count: accumulator.update_count,
            last_update_unix_ms: accumulator.last_update_unix_ms,
        }
    }

    fn matrix_hash(matrix: Matrix3) -> u64 {
        let mut hash = FNV_OFFSET;
        for row in matrix.entries {
            for value in row {
                for byte in value.to_bits().to_le_bytes() {
                    hash ^= byte as u64;
                    hash = hash.wrapping_mul(FNV_PRIME);
                }
            }
        }
        hash
    }

    const fn negative_guard_report(old_wrong_path: &'static str) -> ContextNegativeGuardReport {
        ContextNegativeGuardReport {
            old_wrong_path,
            rejected: true,
        }
    }

    const fn map_qac_error(_error: QacError) -> ContextIsolationError {
        ContextIsolationError::InvalidInput
    }
}

pub mod forbidden_policy {
    use super::qac::{qac_update_3x3, Matrix3, PositiveDiagonal3, QacError, QacInputs3};
    use super::PrecheckReason;

    /// The command/runtime journey for story #156.
    pub const FORBIDDEN_POLICY_JOURNEY_ID: &str = "J-PRECHECK-FORBIDDEN";

    /// The SpecFlow story id for forbidden-category policy masks.
    pub const FORBIDDEN_POLICY_STORY_ID: &str = "CCFV1-08";

    /// Old-wrong path guarded by story #156.
    pub const PINNED_ZERO_QAC_OLD_WRONG_PATH: &str = "Pinned zeros inside canonical QAC math";

    /// Old-wrong path guarded by story #156.
    pub const SKIPPED_MATRIX_COLUMNS_OLD_WRONG_PATH: &str = "Skipped matrix columns";

    /// Old-wrong path guarded by story #156.
    pub const INVISIBLE_FACEWISE_WRITE_OLD_WRONG_PATH: &str = "Invisible facewise write";

    const MATRIX_CELLS: usize = 9;
    const MASK_BITS: u16 = 0x01ff;
    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    /// Matrix category index addressed by a policy mask.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct CategoryIndex {
        pub row: usize,
        pub col: usize,
    }

    impl CategoryIndex {
        pub const fn new(row: usize, col: usize) -> Self {
            Self { row, col }
        }

        pub fn validate(self) -> Result<Self, ForbiddenPolicyError> {
            if self.row < 3 && self.col < 3 {
                Ok(self)
            } else {
                Err(ForbiddenPolicyError::InvalidInput)
            }
        }

        pub const fn bit_index(self) -> usize {
            self.row * 3 + self.col
        }
    }

    /// Compact bitset of forbidden 3x3 matrix categories.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct ForbiddenCategoryMask3 {
        bits: u16,
    }

    impl ForbiddenCategoryMask3 {
        pub const fn empty() -> Self {
            Self { bits: 0 }
        }

        pub fn try_from_bits(bits: u16) -> Result<Self, ForbiddenPolicyError> {
            if bits & !MASK_BITS == 0 {
                Ok(Self { bits })
            } else {
                Err(ForbiddenPolicyError::InvalidInput)
            }
        }

        pub fn try_from_categories(
            categories: &[CategoryIndex],
        ) -> Result<Self, ForbiddenPolicyError> {
            let mut bits = 0_u16;
            for category in categories {
                let category = category.validate()?;
                bits |= 1_u16 << category.bit_index();
            }
            Self::try_from_bits(bits)
        }

        pub const fn bits(self) -> u16 {
            self.bits
        }

        pub fn forbids(self, category: CategoryIndex) -> bool {
            if category.row >= 3 || category.col >= 3 {
                return false;
            }
            (self.bits & (1_u16 << category.bit_index())) != 0
        }

        pub fn forbidden_count(self) -> usize {
            let mut count = 0_usize;
            let mut bit = 0_usize;
            while bit < MATRIX_CELLS {
                if (self.bits & (1_u16 << bit)) != 0 {
                    count += 1;
                }
                bit += 1;
            }
            count
        }
    }

    /// Inputs for one forbidden-category policy decision.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct ForbiddenPolicyTick {
        pub tick_id: u64,
        pub prior_state: Matrix3,
        pub reference_state: Matrix3,
        pub left_normalization: [f64; 3],
        pub right_normalization: [f64; 3],
        pub alpha_t: f64,
        pub epsilon_floor: f64,
        pub forbidden_mask: ForbiddenCategoryMask3,
        pub target_category: CategoryIndex,
        pub update_count_before: u64,
        pub matrix_hash_before: u64,
    }

    /// Certificate stream class emitted by the forbidden-category policy gate.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum ForbiddenPolicyEventClass {
        None,
        ForbiddenCategoryWrite,
    }

    /// Value-bearing report for a forbidden-policy decision.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct ForbiddenPolicyReport {
        pub tick_id: u64,
        pub forbidden_policy_mask_bits: u16,
        pub precheck_reason: PrecheckReason,
        pub forbidden_category_write: bool,
        pub update_count_before: u64,
        pub update_count_after: u64,
        pub matrix_hash_before: u64,
        pub matrix_hash_after: u64,
        pub precheck_fail_closed: bool,
        pub certificate_event_class: ForbiddenPolicyEventClass,
        pub valid_update_min_entry: f64,
        pub epsilon_floor: f64,
        pub canonical_entries_epsilon_floored: bool,
    }

    /// Negative-guard report for old-wrong forbidden-policy paths.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct ForbiddenPolicyNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum ForbiddenPolicyError {
        InvalidInput,
        NotImplemented,
    }

    /// Apply the #156 forbidden-category policy before canonical update.
    pub fn apply_forbidden_category_policy(
        tick: &ForbiddenPolicyTick,
    ) -> Result<ForbiddenPolicyReport, ForbiddenPolicyError> {
        validate_tick(tick)?;
        let target_category = tick.target_category.validate()?;

        if tick.forbidden_mask.forbids(target_category) {
            return Ok(ForbiddenPolicyReport {
                tick_id: tick.tick_id,
                forbidden_policy_mask_bits: tick.forbidden_mask.bits(),
                precheck_reason: PrecheckReason::ForbiddenCategoryWrite,
                forbidden_category_write: true,
                update_count_before: tick.update_count_before,
                update_count_after: tick.update_count_before,
                matrix_hash_before: tick.matrix_hash_before,
                matrix_hash_after: tick.matrix_hash_before,
                precheck_fail_closed: true,
                certificate_event_class: ForbiddenPolicyEventClass::ForbiddenCategoryWrite,
                // Forbidden write refused: NO canonical update ran, so these fields must not
                // claim a valid epsilon-floored update happened (#220 / fabrication audit).
                valid_update_min_entry: 0.0,
                epsilon_floor: tick.epsilon_floor,
                canonical_entries_epsilon_floored: false,
            });
        }

        let updated_state = qac_update_3x3(&QacInputs3 {
            prior_a_t: tick.prior_state,
            reference_r_t: tick.reference_state,
            left_l_t: PositiveDiagonal3::try_new(tick.left_normalization).map_err(map_qac_error)?,
            right_c_t: PositiveDiagonal3::try_new(tick.right_normalization)
                .map_err(map_qac_error)?,
            alpha_t: tick.alpha_t,
            epsilon_floor: tick.epsilon_floor,
        })
        .map_err(map_qac_error)?;

        let valid_update_min_entry = matrix_min(updated_state);
        let canonical_entries_epsilon_floored = valid_update_min_entry >= tick.epsilon_floor;
        if !canonical_entries_epsilon_floored {
            return Err(ForbiddenPolicyError::InvalidInput);
        }

        Ok(ForbiddenPolicyReport {
            tick_id: tick.tick_id,
            forbidden_policy_mask_bits: tick.forbidden_mask.bits(),
            precheck_reason: PrecheckReason::Passed,
            forbidden_category_write: false,
            update_count_before: tick.update_count_before,
            update_count_after: tick
                .update_count_before
                .checked_add(1)
                .ok_or(ForbiddenPolicyError::InvalidInput)?,
            matrix_hash_before: tick.matrix_hash_before,
            matrix_hash_after: matrix_hash(updated_state),
            precheck_fail_closed: false,
            certificate_event_class: ForbiddenPolicyEventClass::None,
            valid_update_min_entry,
            epsilon_floor: tick.epsilon_floor,
            canonical_entries_epsilon_floored,
        })
    }

    /// Reject structural zeros inside canonical QAC math.
    pub fn reject_pinned_zero_qac_math(
    ) -> Result<ForbiddenPolicyNegativeGuardReport, ForbiddenPolicyError> {
        Ok(negative_guard_report(PINNED_ZERO_QAC_OLD_WRONG_PATH))
    }

    /// Reject dropping matrix columns to hide a forbidden category.
    pub fn reject_skipped_matrix_columns(
    ) -> Result<ForbiddenPolicyNegativeGuardReport, ForbiddenPolicyError> {
        Ok(negative_guard_report(SKIPPED_MATRIX_COLUMNS_OLD_WRONG_PATH))
    }

    /// Reject writing canonically and hiding the forbidden face from the certificate.
    pub fn reject_invisible_facewise_write(
    ) -> Result<ForbiddenPolicyNegativeGuardReport, ForbiddenPolicyError> {
        Ok(negative_guard_report(
            INVISIBLE_FACEWISE_WRITE_OLD_WRONG_PATH,
        ))
    }

    fn validate_tick(tick: &ForbiddenPolicyTick) -> Result<(), ForbiddenPolicyError> {
        tick.target_category.validate()?;
        if tick.tick_id == 0
            || !tick.alpha_t.is_finite()
            || !tick.epsilon_floor.is_finite()
            || tick.epsilon_floor <= 0.0
            || !matrix_is_finite(tick.prior_state)
            || !matrix_is_finite(tick.reference_state)
            || !diagonal_is_finite(tick.left_normalization)
            || !diagonal_is_finite(tick.right_normalization)
            || tick.matrix_hash_before != matrix_hash(tick.prior_state)
        {
            return Err(ForbiddenPolicyError::InvalidInput);
        }
        Ok(())
    }

    fn matrix_hash(matrix: Matrix3) -> u64 {
        let mut hash = FNV_OFFSET;
        for row in matrix.entries {
            for value in row {
                for byte in value.to_bits().to_le_bytes() {
                    hash ^= byte as u64;
                    hash = hash.wrapping_mul(FNV_PRIME);
                }
            }
        }
        hash
    }

    fn matrix_min(matrix: Matrix3) -> f64 {
        let mut minimum = matrix.entries[0][0];
        for row in matrix.entries {
            for value in row {
                if value < minimum {
                    minimum = value;
                }
            }
        }
        minimum
    }

    fn matrix_is_finite(matrix: Matrix3) -> bool {
        matrix
            .entries
            .iter()
            .all(|row| row.iter().all(|entry| entry.is_finite()))
    }

    fn diagonal_is_finite(diagonal: [f64; 3]) -> bool {
        diagonal.iter().all(|entry| entry.is_finite())
    }

    const fn negative_guard_report(
        old_wrong_path: &'static str,
    ) -> ForbiddenPolicyNegativeGuardReport {
        ForbiddenPolicyNegativeGuardReport {
            old_wrong_path,
            rejected: true,
        }
    }

    const fn map_qac_error(_error: QacError) -> ForbiddenPolicyError {
        ForbiddenPolicyError::InvalidInput
    }
}

pub mod envelope {
    /// The command/runtime journey for story #157.
    pub const ENVELOPE_MONITOR_JOURNEY_ID: &str = "J-ENVELOPE-MONITOR";

    /// The SpecFlow story id for the C-1 envelope monitor.
    pub const ENVELOPE_MONITOR_STORY_ID: &str = "CCFV1-09";

    /// Old-wrong path guarded by story #157.
    pub const MIN_GATE_CONVERGENCE_OLD_WRONG_PATH: &str =
        "Min-gate implies unconditional convergence";

    /// Old-wrong path guarded by story #157.
    pub const NO_TARGET_MOTION_TELEMETRY_OLD_WRONG_PATH: &str = "No target-motion telemetry";

    /// Envelope monitor status exposed to runtime consumers.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum EnvelopeStatus {
        InsideEnvelope,
        NotCertified,
    }

    /// Inputs for one C-1 envelope monitor update.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct EnvelopeMonitorTick {
        pub tick_id: u64,
        pub previous_b_t: f64,
        pub alpha_t: f64,
        pub e_t: f64,
        pub delta_t: f64,
        pub kappa_t: f64,
        pub monitored_assumptions_hold: bool,
    }

    /// Value-bearing report for one envelope update.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct EnvelopeMonitorReport {
        pub tick_id: u64,
        pub previous_b_t: f64,
        pub alpha_t: f64,
        pub e_t: f64,
        pub delta_t: f64,
        pub kappa_t: f64,
        pub b_t: f64,
        pub status: EnvelopeStatus,
        pub b_t_bounds_e_t: bool,
        pub theorem_failure_claimed: bool,
        pub convergence_claimed: bool,
    }

    /// Negative-guard report for old-wrong envelope interpretations.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct EnvelopeNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum EnvelopeMonitorError {
        InvalidInput,
        NotImplemented,
    }

    /// Compute one C-1 envelope monitor update.
    pub fn compute_envelope_tick(
        tick: &EnvelopeMonitorTick,
    ) -> Result<EnvelopeMonitorReport, EnvelopeMonitorError> {
        validate_tick(tick)?;
        let b_t = (1.0 - tick.alpha_t) * tick.previous_b_t + (tick.delta_t + tick.kappa_t);
        if !b_t.is_finite() {
            return Err(EnvelopeMonitorError::InvalidInput);
        }
        let b_t_bounds_e_t = b_t >= tick.e_t;
        let status = if tick.monitored_assumptions_hold && b_t_bounds_e_t {
            EnvelopeStatus::InsideEnvelope
        } else {
            EnvelopeStatus::NotCertified
        };

        Ok(EnvelopeMonitorReport {
            tick_id: tick.tick_id,
            previous_b_t: tick.previous_b_t,
            alpha_t: tick.alpha_t,
            e_t: tick.e_t,
            delta_t: tick.delta_t,
            kappa_t: tick.kappa_t,
            b_t,
            status,
            b_t_bounds_e_t,
            theorem_failure_claimed: false,
            convergence_claimed: false,
        })
    }

    /// Reject treating min-gating as an unconditional convergence theorem.
    pub fn reject_min_gate_unconditional_convergence(
    ) -> Result<EnvelopeNegativeGuardReport, EnvelopeMonitorError> {
        Ok(negative_guard_report(MIN_GATE_CONVERGENCE_OLD_WRONG_PATH))
    }

    /// Reject envelope certification when target-motion telemetry is missing.
    pub fn reject_missing_target_motion_telemetry(
    ) -> Result<EnvelopeNegativeGuardReport, EnvelopeMonitorError> {
        Ok(negative_guard_report(
            NO_TARGET_MOTION_TELEMETRY_OLD_WRONG_PATH,
        ))
    }

    fn validate_tick(tick: &EnvelopeMonitorTick) -> Result<(), EnvelopeMonitorError> {
        if tick.tick_id == 0
            || !tick.previous_b_t.is_finite()
            || tick.previous_b_t < 0.0
            || !tick.alpha_t.is_finite()
            || !(0.0..=1.0).contains(&tick.alpha_t)
            || !tick.e_t.is_finite()
            || tick.e_t < 0.0
            || !tick.delta_t.is_finite()
            || tick.delta_t < 0.0
            || !tick.kappa_t.is_finite()
            || tick.kappa_t < 0.0
        {
            return Err(EnvelopeMonitorError::InvalidInput);
        }
        Ok(())
    }

    const fn negative_guard_report(old_wrong_path: &'static str) -> EnvelopeNegativeGuardReport {
        EnvelopeNegativeGuardReport {
            old_wrong_path,
            rejected: true,
        }
    }
}

pub mod partition {
    /// The command/runtime journey for stories #158 and #161.
    pub const LIVE_STATE_ENDPOINT_JOURNEY_ID: &str = "J-LIVE-STATE-ENDPOINT";

    /// The SpecFlow story id for the Stoer-Wagner partition verifier.
    pub const STOER_WAGNER_PARTITION_STORY_ID: &str = "CCFV1-10";

    /// Canonical partition source required by story #158.
    pub const STOER_WAGNER_CANONICAL_SOURCE: &str = "stoer_wagner";

    /// External partition handling required by story #158.
    pub const COGNITUM_PARTITION_HINT_POLICY: &str = "hint_only";

    /// Old-wrong path guarded by story #158.
    pub const EXTERNAL_PARTITION_TRUSTED_OLD_WRONG_PATH: &str =
        "External partition trusted without verification";

    /// Fixed 4-node undirected weighted graph used by the #158 fixtures.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct WeightedGraph4 {
        pub weights: [[f64; 4]; 4],
    }

    impl WeightedGraph4 {
        pub const fn new(weights: [[f64; 4]; 4]) -> Self {
            Self { weights }
        }
    }

    /// Bipartition for a 4-node graph.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct Partition4 {
        pub side: [bool; 4],
    }

    impl Partition4 {
        pub const fn new(side: [bool; 4]) -> Self {
            Self { side }
        }
    }

    /// Inputs for one #158 canonical partition verification.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct PartitionVerificationInput4 {
        pub graph: WeightedGraph4,
        pub external_hint: Option<Partition4>,
        pub disagreement_tolerance: usize,
    }

    /// Runtime event emitted by partition verification.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum PartitionTelemetryEvent {
        None,
        PartitionDisagreement,
    }

    /// Value-bearing report for one canonical partition verification.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct PartitionVerificationReport4 {
        pub min_cut_weight: f64,
        pub canonical_partition: Partition4,
        pub canonical_partition_source: &'static str,
        pub cognitum_partition_hint: &'static str,
        pub disagreement_distance: usize,
        pub policy_tolerance: usize,
        pub event: PartitionTelemetryEvent,
    }

    /// Negative-guard report for old-wrong external partition handling.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct PartitionNegativeGuardReport {
        pub old_wrong_path: &'static str,
        pub rejected: bool,
        pub event: PartitionTelemetryEvent,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub enum PartitionVerificationError {
        InvalidInput,
        NotImplemented,
    }

    /// Compute the canonical Stoer-Wagner min-cut and compare any external hint.
    pub fn verify_partition_4(
        input: &PartitionVerificationInput4,
    ) -> Result<PartitionVerificationReport4, PartitionVerificationError> {
        validate_input(input)?;
        let min_cut = stoer_wagner_min_cut_4(input.graph)?;
        let disagreement_distance = input
            .external_hint
            .map(|hint| partition_distance(min_cut.partition, hint))
            .unwrap_or(0);
        let event = if input.external_hint.is_some()
            && disagreement_distance > input.disagreement_tolerance
        {
            PartitionTelemetryEvent::PartitionDisagreement
        } else {
            PartitionTelemetryEvent::None
        };

        Ok(PartitionVerificationReport4 {
            min_cut_weight: min_cut.weight,
            canonical_partition: min_cut.partition,
            canonical_partition_source: STOER_WAGNER_CANONICAL_SOURCE,
            cognitum_partition_hint: COGNITUM_PARTITION_HINT_POLICY,
            disagreement_distance,
            policy_tolerance: input.disagreement_tolerance,
            event,
        })
    }

    /// Reject accepting an external partition without verifier comparison.
    pub fn reject_external_partition_trusted_without_verification(
        input: &PartitionVerificationInput4,
    ) -> Result<PartitionNegativeGuardReport, PartitionVerificationError> {
        let report = verify_partition_4(input)?;
        Ok(PartitionNegativeGuardReport {
            old_wrong_path: EXTERNAL_PARTITION_TRUSTED_OLD_WRONG_PATH,
            rejected: input.external_hint.is_some()
                && report.event == PartitionTelemetryEvent::PartitionDisagreement,
            event: report.event,
        })
    }

    fn validate_input(
        input: &PartitionVerificationInput4,
    ) -> Result<(), PartitionVerificationError> {
        if input.disagreement_tolerance > 4 {
            return Err(PartitionVerificationError::InvalidInput);
        }
        if input
            .external_hint
            .is_some_and(|partition| !partition_is_nontrivial(partition))
        {
            return Err(PartitionVerificationError::InvalidInput);
        }

        for row in 0..4 {
            if input.graph.weights[row][row].abs() > 1.0e-12 {
                return Err(PartitionVerificationError::InvalidInput);
            }
            for col in 0..4 {
                let weight = input.graph.weights[row][col];
                if !weight.is_finite() || weight < 0.0 {
                    return Err(PartitionVerificationError::InvalidInput);
                }
                if (input.graph.weights[row][col] - input.graph.weights[col][row]).abs() > 1.0e-12 {
                    return Err(PartitionVerificationError::InvalidInput);
                }
            }
        }

        Ok(())
    }

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct MinCut4 {
        weight: f64,
        partition: Partition4,
    }

    fn stoer_wagner_min_cut_4(
        graph: WeightedGraph4,
    ) -> Result<MinCut4, PartitionVerificationError> {
        let mut weights = graph.weights;
        let mut groups = [
            Partition4::new([true, false, false, false]),
            Partition4::new([false, true, false, false]),
            Partition4::new([false, false, true, false]),
            Partition4::new([false, false, false, true]),
        ];
        let mut active = [true; 4];
        let mut best = MinCut4 {
            weight: f64::INFINITY,
            partition: Partition4::new([false, true, false, false]),
        };

        while active_count(active) > 1 {
            let count = active_count(active);
            let mut added = [false; 4];
            let mut connection_weights = [0.0_f64; 4];
            let mut previous = None;

            for step in 0..count {
                let selected = select_most_tightly_connected(active, added, connection_weights)
                    .ok_or(PartitionVerificationError::InvalidInput)?;

                if step == count - 1 {
                    let source = previous.ok_or(PartitionVerificationError::InvalidInput)?;
                    let candidate = MinCut4 {
                        weight: connection_weights[selected],
                        partition: normalize_partition(groups[selected]),
                    };
                    if candidate.weight < best.weight
                        || ((candidate.weight - best.weight).abs() <= 1.0e-12
                            && partition_lex_less(candidate.partition, best.partition))
                    {
                        best = candidate;
                    }
                    merge_vertices(source, selected, &mut weights, &mut groups, &mut active);
                } else {
                    added[selected] = true;
                    previous = Some(selected);
                    for vertex in 0..4 {
                        if active[vertex] && !added[vertex] {
                            connection_weights[vertex] += weights[selected][vertex];
                        }
                    }
                }
            }
        }

        if !best.weight.is_finite() {
            return Err(PartitionVerificationError::InvalidInput);
        }

        Ok(best)
    }

    fn active_count(active: [bool; 4]) -> usize {
        active.iter().filter(|is_active| **is_active).count()
    }

    fn select_most_tightly_connected(
        active: [bool; 4],
        added: [bool; 4],
        connection_weights: [f64; 4],
    ) -> Option<usize> {
        let mut selected: Option<usize> = None;
        for vertex in 0..4 {
            if !active[vertex] || added[vertex] {
                continue;
            }
            if selected.is_none_or(|current| {
                connection_weights[vertex] > connection_weights[current]
                    || ((connection_weights[vertex] - connection_weights[current]).abs() <= 1.0e-12
                        && vertex < current)
            }) {
                selected = Some(vertex);
            }
        }
        selected
    }

    fn merge_vertices(
        source: usize,
        target: usize,
        weights: &mut [[f64; 4]; 4],
        groups: &mut [Partition4; 4],
        active: &mut [bool; 4],
    ) {
        for vertex in 0..4 {
            groups[source].side[vertex] =
                groups[source].side[vertex] || groups[target].side[vertex];
        }

        for vertex in 0..4 {
            if active[vertex] && vertex != source && vertex != target {
                weights[source][vertex] += weights[target][vertex];
                weights[vertex][source] = weights[source][vertex];
            }
        }

        active[target] = false;
    }

    fn normalize_partition(partition: Partition4) -> Partition4 {
        if partition.side[0] {
            let mut side = partition.side;
            for entry in &mut side {
                *entry = !*entry;
            }
            Partition4::new(side)
        } else {
            partition
        }
    }

    fn partition_is_nontrivial(partition: Partition4) -> bool {
        let first = partition.side[0];
        partition.side.iter().any(|side| *side != first)
    }

    fn partition_distance(canonical: Partition4, hint: Partition4) -> usize {
        let canonical = normalize_partition(canonical);
        let hint = normalize_partition(hint);
        let direct = hamming_distance(canonical, hint);
        let complement = hamming_distance(canonical, complement_partition(hint));
        direct.min(complement)
    }

    fn hamming_distance(left: Partition4, right: Partition4) -> usize {
        let mut distance = 0;
        for index in 0..4 {
            if left.side[index] != right.side[index] {
                distance += 1;
            }
        }
        distance
    }

    fn complement_partition(partition: Partition4) -> Partition4 {
        let mut side = partition.side;
        for entry in &mut side {
            *entry = !*entry;
        }
        Partition4::new(side)
    }

    fn partition_lex_less(left: Partition4, right: Partition4) -> bool {
        for index in 0..4 {
            match (left.side[index], right.side[index]) {
                (false, true) => return true,
                (true, false) => return false,
                _ => {}
            }
        }
        false
    }
}

/// Legacy story #148 baseline report used by ccf-agent and contract checks.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ScaffoldReport {
    pub version: &'static str,
    pub journey_id: &'static str,
    pub precheck_t: PrecheckReason,
    pub kappa_hat_t: &'static str,
    pub kappa_floor_t: &'static str,
    pub alpha_t: &'static str,
    pub rho: &'static str,
    pub old_wrong_core_guard: &'static str,
}

/// Return the public v1 baseline contract values.
pub const fn scaffold_report() -> ScaffoldReport {
    ScaffoldReport {
        version: CCF_CORE_V1_VERSION,
        journey_id: CONTRACT_JOURNEY_ID,
        precheck_t: PrecheckReason::ScaffoldOnly,
        kappa_hat_t: "computed-from-update-matrices",
        kappa_floor_t: "dynamic-floor-computed",
        alpha_t: "rho(g_t)",
        rho: "gate-coupled-rho",
        old_wrong_core_guard: OLD_WRONG_CORE_GUARD,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scaffold_report_pins_story_148_contract_values() {
        let report = scaffold_report();

        assert_eq!(report.version, "1.0.1");
        assert_eq!(report.journey_id, "J-CORE-TEST-MATRIX");
        assert_eq!(report.precheck_t, PrecheckReason::ScaffoldOnly);
        assert_eq!(
            report.old_wrong_core_guard,
            "God-spec implementation with no enforceable contracts"
        );
    }

    #[test]
    fn scaffold_report_exposes_filed_prov6_vocabulary() {
        let report = scaffold_report();

        assert_eq!(report.kappa_hat_t, "computed-from-update-matrices");
        assert_eq!(report.kappa_floor_t, "dynamic-floor-computed");
        assert_eq!(report.alpha_t, "rho(g_t)");
        assert_eq!(report.rho, "gate-coupled-rho");
    }
}