vela-protocol 0.940.9

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

use std::collections::HashMap;

use serde_json::Value;

use crate::bundle::{Annotation, ConfidenceMethod};
use crate::events::{self, EventKind, StateEvent};
use crate::project::{self, Project};

/// v0.105: per-replay finding-id index. Keys are content-addressed
/// finding ids; values are positions into `state.findings`. Replay
/// builds this once from genesis state and updates it in lockstep
/// with `finding.asserted` pushes. Per-kind apply functions look up
/// their target via `idx.get(...)` instead of an O(N) linear scan.
/// findings are append-only in the substrate (no removals), so the
/// index never goes stale; positions remain valid for the life of
/// a replay.
pub type FindingIndex = HashMap<String, usize>;

/// Build the finding-id index from the current state. O(N) once.
#[must_use]
pub fn build_finding_index(state: &Project) -> FindingIndex {
    state
        .findings
        .iter()
        .enumerate()
        .map(|(i, f)| (f.id.clone(), i))
        .collect()
}

/// Single source of truth for the event kinds whose mutations the
/// reducer enforces. The no-op anchor `frontier.created` is excluded
/// because it does not mutate state. Used by:
///   - the dispatch table in `apply_event` (validated by
///     `dispatch_handles_every_declared_kind` below)
///   - the cross-implementation fixture coverage assertion in
///     `crates/vela-protocol/tests/cross_impl_reducer_fixtures.rs`
///
/// If you add a new reducer arm, add it here too. CI will fail if the
/// dispatch table and this constant disagree, and the cross-impl
/// fixture coverage test will fail if the new kind isn't exercised by
/// at least one fixture builder. The hand-maintained mirror is gone.
pub const REDUCER_MUTATION_KINDS: &[&str] = &[
    "finding.asserted",
    "finding.reviewed",
    "finding.noted",
    "finding.caveated",
    "finding.confidence_revised",
    "finding.rejected",
    "finding.retracted",
    "finding.contribution.recorded",
    "finding.dependency_invalidated",
    // Generic artifacts: protocol files, trial registry records, source
    // files, notebooks, and other byte or pointer commitments.
    "artifact.asserted",
    "artifact.reviewed",
    "artifact.retracted",
    // v0.51: tier.set re-classifies the access_tier on a finding
    // or artifact. Mutates the matched object's
    // access_tier field. Replay reproduces the current tier from the
    // canonical event log alone, no out-of-band classification
    // table.
    "tier.set",
    // v0.56: evidence_atom.locator_repaired sets `locator` on a single
    // evidence atom and clears the "missing evidence locator" caveat.
    // Mutates `state.evidence_atoms[i].locator` only. Cross-impl
    // reducer fixtures whose post-replay digest covers `findings[]`
    // only treat this as a no-op on finding state. The Rust reducer
    // still has an explicit arm because skipping unknown kinds would
    // silently drop the repair from a fresh replay.
    "evidence_atom.locator_repaired",
    // v0.57: finding.span_repaired appends one `{section, text}` span
    // to `state.findings[i].evidence.evidence_spans`. Idempotent under
    // identical re-application (refuses to append an equal span twice).
    "finding.span_repaired",
    // v0.213: Released Diff Pack tracking. Both arms mutate
    // `state.released_diff_packs`:
    //   * `diff_pack.released` appends a new ReleasedDiffPackRecord
    //     (idempotent on pack_id).
    //   * `diff_pack.reviewed` updates the matching record's verdict
    //     + verdict_event_id + applied_members + sdk_only_members.
    "diff_pack.released",
    "diff_pack.reviewed",
    // v0.218: Verdict Conflict Resolution. Appends a VerdictConflict
    // to state.verdict_conflicts (idempotent on conflict_id). T32
    // pins the accumulation algebra.
    "verdict_conflict.resolved",
    // T7: a reviewer's decision on a Contradiction object. Upserts the
    // resolved Contradiction into state.contradictions (latest per id).
    "contradiction.resolved",
    // Supersession flips `flags.superseded` on the *old* finding (the
    // replacement enters via genesis seeding from the accepted proposal's
    // payload — the event itself is thin).
    "finding.superseded",
    // Causal re-grading replays `assertion.causal_claim` /
    // `causal_evidence_grade` from the event's `payload.after`.
    "assertion.reinterpreted_causal",
    // Statement-faithfulness attestation: upserts a signed vsa_ record
    // into state.statement_attestations (idempotent by id; the record's
    // own Ed25519 signature is re-verified on apply).
    "statement.attested",
    // Obligation lease: one live lease per obligation; a second claim
    // while a prior is unexpired is a reducer error. Expiry is computed
    // against the NEW event's timestamp (the log's own clock), never
    // wall time — replay stays deterministic.
    "attempt.claimed",
    // Priority registration: append a content-addressed statement hash
    // (idempotent on hash).
    "statement.registered",
    // Math-atlas anchor link: upsert/remove a signed val_ record into
    // state.anchor_links (idempotent by id; signature re-verified on apply).
    "anchor.attached",
    "anchor.retracted",
];

/// Apply one canonical event to `state`, mutating it in place.
///
/// The function dispatches on `event.kind` and performs the same
/// mutations that `proposals::apply_*` performs when constructing the
/// event. Two implementations of the reducer must therefore agree on the
/// mutation rules per kind. Those rules are documented in
/// `docs/PROTOCOL.md` §6 and pinned via canonical hashing.
pub fn apply_event(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let mut idx = build_finding_index(state);
    apply_event_indexed(state, event, &mut idx)
}

/// v0.105: indexed dispatch. Used by `replay_from_genesis` so the
/// finding-id index gets built once and reused across every event.
/// `apply_event` builds the index lazily for one-off callers.
pub fn apply_event_indexed(
    state: &mut Project,
    event: &StateEvent,
    idx: &mut FindingIndex,
) -> Result<(), String> {
    match &event.kind {
        // Phase J: `frontier.created` is the genesis event. It carries
        // identity (its canonical hash IS the frontier_id) but does not
        // mutate finding state. Replay treats it as a structural
        // anchor — the chain begins here.
        EventKind::FrontierCreated => Ok(()),
        EventKind::FindingAsserted => apply_finding_asserted(state, event, idx),
        EventKind::FindingReviewed => apply_finding_reviewed(state, event, idx),
        EventKind::FindingNoted => apply_finding_annotation(state, event, "noted", idx),
        EventKind::FindingCaveated => apply_finding_annotation(state, event, "caveated", idx),
        EventKind::SourceTextReviewed => Ok(()),
        EventKind::FindingConfidenceRevised => apply_finding_confidence_revised(state, event, idx),
        EventKind::FindingRejected => apply_finding_rejected(state, event, idx),
        EventKind::FindingRetracted => apply_finding_retracted(state, event, idx),
        EventKind::FindingContributionRecorded => {
            apply_finding_contribution_recorded(state, event, idx)
        }
        // Phase L: per-dependent cascade event. Replay marks the
        // dependent as contested and records the upstream chain in an
        // annotation so a fresh reduce reproduces the post-cascade
        // state without re-running the propagator.
        EventKind::FindingDependencyInvalidated => apply_finding_dependency_invalidated(state, event, idx),
        EventKind::ArtifactAsserted => apply_artifact_asserted(state, event),
        EventKind::VerifierAttachmentAdded => apply_verifier_attachment_added(state, event),
        EventKind::ArtifactReviewed => apply_artifact_reviewed(state, event),
        EventKind::ArtifactRetracted => apply_artifact_retracted(state, event),
        // v0.51: tier re-classification.
        EventKind::TierSet => apply_tier_set(state, event),
        // v0.56: mechanical evidence-atom locator repair.
        EventKind::EvidenceAtomLocatorRepaired => apply_evidence_atom_locator_repaired(state, event),
        // v0.57: mechanical finding-level span repair.
        EventKind::FindingSpanRepaired => apply_finding_span_repaired(state, event, idx),
        // v0.79.4: per-event attestation. No-op on findings;
        // attestations live as append-only canonical events
        // pointing at a target event id.
        EventKind::AttestationRecorded => Ok(()),
        // v0.201: a `vsd_*` Scientific Diff Pack was signed, applied,
        // and is now released. The event is a metadata-only handle —
        // its payload references the pack id; replay does not mutate
        // project state because the pack's member proposals already
        // applied through their own `proposal.accepted` arms. The arm
        // exists so the event is a first-class handle that
        // hubs can index by `vsd_*`.
        EventKind::DiffPackReleased => apply_diff_pack_released(state, event),
        // v0.205: a reviewer issued a verdict on a `vsd_*` Diff Pack.
        // The event payload carries (pack_id, verdict, reviewer_actor,
        // reason). Like `diff_pack.released`, this arm is metadata-
        // only — member proposals mutate state through their own
        // existing acceptance paths (proposals.rs). The arm exists
        // so the verdict is a first-class canonical event the log
        // pins. Theorem 26 (Diff Pack verdict atomicity) pins the
        // promoter-side guarantee that accept either applies every
        // member or none.
        EventKind::DiffPackReviewed => apply_diff_pack_reviewed(state, event),
        // v0.218: a verdict-conflict resolution lands on the log.
        // Append the VerdictConflict record to state.verdict_conflicts
        // (idempotent on conflict_id).
        EventKind::VerdictConflictResolved => apply_verdict_conflict_resolved(state, event),
        // T7: a contradiction resolution lands on the log. Upsert the
        // resolved Contradiction into state.contradictions by id.
        EventKind::ContradictionResolved => apply_contradiction_resolved(state, event),
        // Attempt lifecycle: a signed deposit, then append-only resolutions.
        EventKind::AttemptDeposited => apply_attempt_deposited(state, event),
        EventKind::TransferDeposited => apply_transfer_deposited(state, event),
        EventKind::EndorsementDeposited => apply_endorsement_deposited(state, event),
        EventKind::AttemptResolved => apply_attempt_resolved(state, event),
        EventKind::StatementAttested => apply_statement_attested(state, event),
        EventKind::AnchorAttached => apply_anchor_attached(state, event),
        EventKind::AnchorRetracted => apply_anchor_retracted(state, event),
        EventKind::AttemptClaimed => apply_attempt_claimed(state, event),
        EventKind::StatementRegistered => apply_statement_registered(state, event),
        // Supersession: the event targets the *old* finding and flips its
        // `flags.superseded`. The replacement finding's body lives in the
        // accepted proposal's `payload.new_finding` and enters replay via
        // genesis seeding (`repo::seed_genesis`), not via this arm — the
        // event payload is deliberately thin ({proposal_id, new_finding_id}).
        EventKind::FindingSuperseded => apply_finding_superseded(state, event, idx),
        // Causal re-grading (`vela finding causal-set`): replays the
        // claim/grade mutation from the event's `payload.after`.
        EventKind::AssertionReinterpretedCausal => apply_assertion_reinterpreted_causal(state, event, idx),
        // Audit-only / writerless kinds. Each is validated at emit time and
        // appended to the log, but mutates no projected state on replay:
        // their consumers read the events directly. The threshold,
        // correction-return, research-trace, and prediction-expiry kinds had
        // their CLI writers removed in the v0.700 surface cut (zero such
        // events exist in any live log); `frontier.observation_reviewed` and
        // `key.revoke` are audit records. `key.revoke` does not mutate the
        // repository actor registry; Profile v1 freezes that registry until
        // a separate governed rotation and recovery contract exists. Explicit
        // arms let historical logs containing either event replay.
        // A reviewer-tier key's recommend-accept: audit record consumed by
        // owner/maintainer keys; no projected-state mutation.
        EventKind::ProposalRecommended
        | EventKind::FrontierObservationReviewed
        | EventKind::CorrectionReturnReview
        | EventKind::ResearchTraceReview
        | EventKind::KeyRevoke
        // Reviewer decision records. Audit-only on the FINDING projection:
        // the accept's effect on state is the domain event it produced
        // (finding.asserted, …), already replayed by its own arm; the
        // review.* event records WHO decided and HOW. Proposal `status` is
        // a separate projection over these events, verified by
        // `proposals::verify_proposal_decision_parity` — not reconstructed
        // here, so verify_replay's finding hashes are untouched.
        | EventKind::ReviewAccepted
        | EventKind::ReviewRejected
        | EventKind::ReviewRevisionRequested
        | EventKind::ProposalWithdrawn
        | EventKind::ActorRegistrationActivated
        // policy.auto_admitted: deterministic machine-verified admission (Phase 1A).
        // Like review.*, it records the decision (WHO/HOW: the frozen verifier + the
        // audited predicate) without mutating findings — the verifier attachments
        // already on the frontier define the gate status. No-op on finding hashes.
        | EventKind::PolicyAutoAdmitted => Ok(()),
        EventKind::FrontierRepositoryBound => apply_frontier_repository_bound(event),
        EventKind::Other(other) => Err(format!("reducer: unsupported event kind '{other}'")),
    }
}

/// Replay an entire event log from genesis state.
///
/// `genesis` is the bootstrap finding set (the state of the frontier at
/// the moment of compile, before any reviewed transitions). `events` is
/// the full canonical event log. Returns the materialized `Project` after
/// applying every event in sequence.
pub fn replay_from_genesis(
    genesis: Vec<crate::bundle::FindingBundle>,
    events: Vec<StateEvent>,
    name: &str,
    description: &str,
    compiled_at: &str,
    compiler: &str,
) -> Result<Project, String> {
    let boundary_errors =
        crate::frontier_repository::validate_repository_boundary_event_set(&events);
    if !boundary_errors.is_empty() {
        return Err(format!(
            "repository-boundary event set is invalid: {}",
            boundary_errors.join("; ")
        ));
    }
    let mut state = Project {
        vela_version: project::VELA_SCHEMA_VERSION.to_string(),
        schema: project::VELA_SCHEMA_URL.to_string(),
        frontier_id: None,
        project: project::ProjectMeta {
            name: name.to_string(),
            description: description.to_string(),
            compiled_at: compiled_at.to_string(),
            compiler: compiler.to_string(),
            papers_processed: 0,
            errors: 0,
            dependencies: Vec::new(),
        },
        stats: project::ProjectStats::default(),
        findings: genesis,
        sources: Vec::new(),
        evidence_atoms: Vec::new(),
        condition_records: Vec::new(),
        review_events: Vec::new(),
        confidence_updates: Vec::new(),
        events: Vec::new(),
        proposals: Vec::new(),
        proof_state: crate::proposals::ProofState::default(),
        signatures: Vec::new(),
        actors: Vec::new(),
        artifacts: Vec::new(),
        released_diff_packs: Vec::new(),
        verdict_conflicts: Vec::new(),
        contradictions: Vec::new(),
        verifier_attachments: Vec::new(),
        attempts: Vec::new(),
        attempt_resolutions: Vec::new(),
        transfers: Vec::new(),
        endorsements: Vec::new(),
        statement_attestations: Vec::new(),
        anchor_links: Vec::new(),
        attempt_claims: Vec::new(),
        statement_registrations: Vec::new(),
    };
    crate::sources::materialize_project(&mut state);
    // v0.105: build the finding-id index once, reuse across every
    // event. Replay is the hot path and was previously O(N^2) (each
    // per-kind apply linear-scanned state.findings); with the index
    // it is O(N).
    let mut idx = build_finding_index(&state);
    // v0.106.6: take events by value and move each one into
    // state.events instead of cloning. Pre-v0.106.6 the input was
    // &[StateEvent] and the loop did event.clone() on every
    // iteration, which walked the heap-allocated payload Value tree
    // for each event. At N=20k events this was the next bottleneck
    // after the v0.105 O(N^2) scan was removed.
    for event in events {
        apply_event_indexed(&mut state, &event, &mut idx)?;
        state.events.push(event);
    }
    project::recompute_stats(&mut state);
    Ok(state)
}

fn apply_frontier_repository_bound(event: &StateEvent) -> Result<(), String> {
    let payload = crate::frontier_repository::repository_boundary_payload_from_event_shape(event)?;
    crate::frontier_repository::verify_repository_boundary_signature_only(
        event,
        &payload.administrator_public_key,
    )?;
    Ok(())
}

/// Canonical replay order: (timestamp, id). This is the same order
/// `events::replay_report` uses for chain verification. Timestamps are
/// RFC3339 with microseconds; the content-addressed id is the
/// deterministic tiebreak.
pub fn sorted_for_replay(events: &[StateEvent]) -> Vec<StateEvent> {
    let mut sorted: Vec<StateEvent> = events.to_vec();
    sorted.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then_with(|| a.id.cmp(&b.id)));
    sorted
}

/// Synthesize the genesis finding set from the event log plus the
/// proposal payload store. The protocol's `finding.asserted` events are
/// deliberately thin (`{proposal_id}`); the asserted body lives in the
/// accepted proposal's `payload.finding` (or `payload.new_finding` for a
/// supersession) and is cryptographically pinned: the assert event's
/// `after_hash` is `finding_hash` of the body pushed at accept time.
/// Every hydration is verified against that hash — a tampered or missing
/// proposal becomes a diagnostic, never a silently wrong finding.
///
/// Events whose payload carries `finding` inline (v0.3 genesis form) are
/// NOT seeded here: the reducer's `finding.asserted` arm applies them
/// during replay.
pub fn seed_genesis(
    events_sorted: &[StateEvent],
    proposals: &[crate::proposals::StateProposal],
) -> (Vec<crate::bundle::FindingBundle>, Vec<String>) {
    use crate::bundle::FindingBundle;
    let by_id: HashMap<&str, &crate::proposals::StateProposal> =
        proposals.iter().map(|p| (p.id.as_str(), p)).collect();
    let mut genesis: Vec<FindingBundle> = Vec::new();
    let mut diagnostics: Vec<String> = Vec::new();
    for ev in events_sorted {
        let (payload_key, is_supersede) = match ev.kind.as_str() {
            "finding.asserted" => ("finding", false),
            "finding.superseded" => ("new_finding", true),
            _ => continue,
        };
        if !is_supersede && ev.payload.get("finding").is_some() {
            // Inline (v0.3 genesis) form: the reducer arm applies it.
            continue;
        }
        let Some(pid) = ev.payload.get("proposal_id").and_then(Value::as_str) else {
            diagnostics.push(format!(
                "{}: {} carries neither an inline body nor a proposal_id",
                ev.id, ev.kind
            ));
            continue;
        };
        let Some(proposal) = by_id.get(pid) else {
            diagnostics.push(format!(
                "{}: {} references proposal {pid}, which is not in the proposal store",
                ev.id, ev.kind
            ));
            continue;
        };
        let Some(body) = proposal.payload.get(payload_key) else {
            diagnostics.push(format!(
                "{}: proposal {pid} has no payload.{payload_key} to hydrate from",
                ev.id
            ));
            continue;
        };
        let finding: FindingBundle = match serde_json::from_value(body.clone()) {
            Ok(f) => f,
            Err(e) => {
                diagnostics.push(format!(
                    "{}: proposal {pid} payload.{payload_key} does not deserialize: {e}",
                    ev.id
                ));
                continue;
            }
        };
        // The pin: the assert event's after_hash is finding_hash of the
        // body as pushed (links excluded from the hash, so the writer's
        // auto-injected supersedes link cannot break it). For
        // finding.superseded the after_hash covers the OLD finding, so
        // the new body is hydrated unverified-by-hash but is still
        // confined to the signed, content-addressed proposal store.
        if !is_supersede {
            let h = events::finding_hash(&finding);
            if h != ev.after_hash {
                diagnostics.push(format!(
                    "{}: hydrated body hash {h} != event after_hash {} (proposal {pid} tampered or stale)",
                    ev.id, ev.after_hash
                ));
                continue;
            }
        }
        if genesis.iter().any(|g| g.id == finding.id) {
            continue; // idempotent under duplicate asserts
        }
        genesis.push(finding);
    }
    (genesis, diagnostics)
}

/// One full reducer replay of a loaded project's own event log: sort a
/// copy of the events into canonical replay order, seed genesis from the
/// proposal payload store, and run `replay_from_genesis`. The loader
/// grafts every event-derived collection from the result — this is the
/// single code path that makes "loader = reducer" true. Hydration
/// diagnostics are not fatal here (a finding that fails to hydrate is
/// simply absent from the replayed copy); `verify_replay` is where they
/// become check failures.
pub fn replayed_projection(state: &Project) -> Result<Project, String> {
    let sorted = sorted_for_replay(&state.events);
    let (genesis, _diagnostics, _remnants) = seed_genesis_with_remnants(state, &sorted);
    replay_from_genesis(
        genesis,
        sorted,
        &state.project.name,
        &state.project.description,
        &state.project.compiled_at,
        &state.project.compiler,
    )
}

/// Genesis = hydrated asserts (from the proposal payload store) plus
/// *genesis remnants*: cached findings with no assert/supersede event
/// anywhere in the log. Remnants predate the event-first discipline (or
/// were assembled directly, as in tests); they cannot be replayed into
/// existence, but later events may target them, so both the loader and
/// the verifier must seed them or replay would reject their own log.
/// Returns (genesis, hydration diagnostics, remnant count).
pub fn seed_genesis_with_remnants(
    state: &Project,
    events_sorted: &[StateEvent],
) -> (Vec<crate::bundle::FindingBundle>, Vec<String>, usize) {
    let (mut genesis, diagnostics) = seed_genesis(events_sorted, &state.proposals);
    let evented_ids: std::collections::HashSet<&str> = events_sorted
        .iter()
        .filter(|e| matches!(e.kind.as_str(), "finding.asserted" | "finding.superseded"))
        .flat_map(|e| {
            let mut ids = vec![e.target.id.as_str()];
            if let Some(nid) = e.payload.get("new_finding_id").and_then(Value::as_str) {
                ids.push(nid);
            }
            ids
        })
        .collect();
    let mut remnants = 0usize;
    for f in &state.findings {
        if !evented_ids.contains(f.id.as_str()) && !genesis.iter().any(|g| g.id == f.id) {
            genesis.push(f.clone());
            remnants += 1;
        }
    }
    (genesis, diagnostics, remnants)
}

/// Order-independent digest over a finding set (ids sorted, links
/// excluded via `finding_hash`). This is the comparison surface of
/// `verify_replay`: the full `snapshot_hash` covers loader-only state
/// (proposals, actors, stats) that a pure replay can never reproduce,
/// so replayed-vs-materialized equality is only meaningful over the
/// findings themselves.
fn findings_digest(findings: &[crate::bundle::FindingBundle]) -> String {
    let mut pairs: Vec<(String, String)> = findings
        .iter()
        .map(|f| (f.id.clone(), events::finding_hash(f)))
        .collect();
    pairs.sort();
    let joined = pairs
        .iter()
        .map(|(id, h)| format!("{id}:{h}"))
        .collect::<Vec<_>>()
        .join("\n");
    use sha2::Digest;
    hex::encode(sha2::Sha256::digest(joined.as_bytes()))
}

/// Verify that the materialized `state` is reproducible from its own
/// event log: seed genesis from the proposal payload store, replay every
/// event through the one reducer, and compare per-finding
/// `finding_hash` between the replayed and materialized findings.
///
/// This is the load-bearing check that turns Vela's replay claim into a
/// verifiable invariant — the loader and the reducer can no longer
/// drift apart silently.
pub fn verify_replay(state: &Project) -> ReplayVerification {
    verify_replay_events(state, state.events.clone())
}

/// Verify the materialized scientific projection against the union of the
/// immutable Era-0 event log and an already-verified Era-1 authority log.
///
/// Authority verification deliberately remains outside the reducer. Each
/// supplied event is converted to its transaction-independent semantic event
/// identity before ordinary replay. Duplicate semantic identities across or
/// within eras fail closed.
pub fn verify_replay_with_authority(
    state: &Project,
    authority_events: &[crate::authority::AuthorityEventV1],
) -> ReplayVerification {
    let events = match semantic_event_union(state, authority_events) {
        Ok(events) => events,
        Err(error) => {
            return ReplayVerification {
                ok: false,
                replayed_snapshot_hash: String::new(),
                materialized_snapshot_hash: findings_digest(&state.findings),
                diffs: vec![error],
                note: "dual-log event history does not replay through the reducer".to_string(),
            };
        }
    };
    verify_replay_events(state, events)
}

/// Return the transaction-independent semantic event union of the retained
/// Era-0 log and an already verified repository-authority log.
///
/// Authority verification remains the caller's responsibility. This helper is
/// for read/check projections that need the same event identities as the
/// reducer without mutating or relabeling either retained log.
pub fn semantic_event_union(
    state: &Project,
    authority_events: &[crate::authority::AuthorityEventV1],
) -> Result<Vec<StateEvent>, String> {
    let mut events = state.events.clone();
    let mut ids = events
        .iter()
        .map(|event| event.id.clone())
        .collect::<std::collections::BTreeSet<_>>();
    for authority_event in authority_events {
        // Era-1 `Other` records are authority/workflow audit events such as
        // policy rotation and Receipt landing. The scientific reducer
        // deliberately rejects `Other`; these records are replayed by the
        // authority-history verifier and their own projections instead.
        if matches!(authority_event.content.kind, EventKind::Other(_)) {
            continue;
        }
        let mut event = match authority_event.semantic_state_event() {
            Ok(event) => event,
            Err(error) => {
                return Err(format!(
                    "repository-authority event {} has no valid semantic replay form: {error}",
                    authority_event.id
                ));
            }
        };
        // Lease release/refresh payloads name the stored authority-event ID of
        // the prior claim. Coordination replay therefore retains that ID.
        // Scientific domain links use the semantic ID above.
        if authority_event.content.kind == EventKind::AttemptClaimed {
            event.id = authority_event.id.clone();
        }
        if !ids.insert(event.id.clone()) {
            return Err(format!(
                "semantic event {} occurs more than once across the dual log",
                event.id
            ));
        }
        events.push(event);
    }
    // Split-repository objects load in filename order, and visible Profile v1
    // materialization uses the same content-ID ordering. The virtual dual-log
    // projection must therefore use semantic event-ID order too; otherwise an
    // exact clean clone can replay correctly while deriving a different
    // legacy snapshot solely from in-memory append order.
    events.sort_by(|left, right| left.id.cmp(&right.id));
    Ok(events)
}

fn verify_replay_events(state: &Project, events: Vec<StateEvent>) -> ReplayVerification {
    if events.is_empty() {
        let d = findings_digest(&state.findings);
        return ReplayVerification {
            ok: true,
            replayed_snapshot_hash: d.clone(),
            materialized_snapshot_hash: d,
            diffs: Vec::new(),
            note: "no events; replay is identity".to_string(),
        };
    }
    let sorted = sorted_for_replay(&events);
    let (genesis, mut diffs, remnants) = seed_genesis_with_remnants(state, &sorted);
    let replayed = match replay_from_genesis(
        genesis,
        sorted,
        &state.project.name,
        &state.project.description,
        &state.project.compiled_at,
        &state.project.compiler,
    ) {
        Ok(p) => p,
        Err(e) => {
            return ReplayVerification {
                ok: false,
                replayed_snapshot_hash: String::new(),
                materialized_snapshot_hash: findings_digest(&state.findings),
                diffs: vec![format!("replay failed: {e}")],
                note: "event log does not replay through the reducer".to_string(),
            };
        }
    };
    let replayed_by_id: HashMap<&str, &crate::bundle::FindingBundle> = replayed
        .findings
        .iter()
        .map(|f| (f.id.as_str(), f))
        .collect();
    for cached in &state.findings {
        match replayed_by_id.get(cached.id.as_str()) {
            None => diffs.push(format!(
                "finding {} is materialized but absent from replay (no assert event hydrates it)",
                cached.id
            )),
            Some(rep) => {
                let ch = events::finding_hash(cached);
                let rh = events::finding_hash(rep);
                if ch != rh {
                    diffs.push(format!(
                        "finding {} diverges: materialized {ch} vs replayed {rh}",
                        cached.id
                    ));
                }
            }
        }
    }
    for rep in &replayed.findings {
        if !state.findings.iter().any(|c| c.id == rep.id) {
            diffs.push(format!(
                "finding {} is replayable from the log but absent from the materialized state",
                rep.id
            ));
        }
    }
    let ok = diffs.is_empty();
    ReplayVerification {
        ok,
        replayed_snapshot_hash: findings_digest(&replayed.findings),
        materialized_snapshot_hash: findings_digest(&state.findings),
        diffs,
        note: if ok {
            format!(
                "replayed {} event(s) over {} seeded finding(s) ({} genesis remnant(s)); materialized state reproduced",
                events.len(),
                replayed.findings.len(),
                remnants
            )
        } else {
            "materialized state is NOT reproducible from the event log".to_string()
        },
    }
}

#[derive(Debug, Clone)]
pub struct ReplayVerification {
    pub ok: bool,
    pub replayed_snapshot_hash: String,
    pub materialized_snapshot_hash: String,
    pub diffs: Vec<String>,
    pub note: String,
}

/// v0.701: per-finding provenance classification for the event-sourcing
/// migration. Where `verify_replay` *proves* the materialized findings are
/// reducible, this reports *why* each one is reducible — exactly which
/// on-disk derived view still pins a finding to git — so a migration can
/// target the gap and a decommit can be justified one bucket at a time.
///
/// Each finding lands in exactly one bucket (inline takes precedence, so a
/// finding asserted-by-proposal then superseded-inline counts as inline —
/// its current body is in the log):
///
/// - `inline`: an assert/supersede event carries the full body in its
///   payload; reducible from `events/` alone.
/// - `proposal_backed`: an assert event exists but hydrates its body from
///   the signed proposal store; still needs `proposals/`.
/// - `remnant`: no assert/supersede event targets it; seeded straight from
///   the `findings/` cache. Predates the event-first discipline.
///
/// A frontier is *fully event-sourced* iff `proposal_backed` and `remnant`
/// are both empty: then `events/` reduces to its whole finding set and the
/// derived views are pure caches, safe to decommit. This is the explanatory
/// companion to `verify_replay`, not a trust gate — `verify_replay` remains
/// the exact, byte-parity invariant.
#[derive(Debug, Clone, Default)]
pub struct ProvenanceReport {
    pub inline: Vec<String>,
    pub proposal_backed: Vec<String>,
    pub remnant: Vec<String>,
    pub actors: usize,
    pub proposals: usize,
}

impl ProvenanceReport {
    /// True when every materialized finding is reducible from the event log
    /// alone (no proposal-backed bodies, no pre-event remnants).
    pub fn fully_event_sourced(&self) -> bool {
        self.proposal_backed.is_empty() && self.remnant.is_empty()
    }
}

/// Classify every materialized finding by how its body enters the log.
/// Mirrors the `seed_genesis` dispatch: an inline body (`payload.finding`
/// / `payload.new_finding`) vs a proposal reference (`payload.proposal_id`).
pub fn classify_provenance(state: &Project) -> ProvenanceReport {
    use std::collections::HashSet;
    let mut inline: HashSet<&str> = HashSet::new();
    let mut proposal_backed: HashSet<&str> = HashSet::new();
    for ev in &state.events {
        match ev.kind.as_str() {
            "finding.asserted" => {
                let id = ev.target.id.as_str();
                if ev.payload.get("finding").is_some() {
                    inline.insert(id);
                } else if ev.payload.get("proposal_id").is_some() {
                    proposal_backed.insert(id);
                }
            }
            "finding.superseded" => {
                if let Some(nid) = ev.payload.get("new_finding_id").and_then(Value::as_str) {
                    if ev.payload.get("new_finding").is_some() {
                        inline.insert(nid);
                    } else if ev.payload.get("proposal_id").is_some() {
                        proposal_backed.insert(nid);
                    }
                }
            }
            _ => {}
        }
    }
    let mut report = ProvenanceReport {
        actors: state.actors.len(),
        proposals: state.proposals.len(),
        ..Default::default()
    };
    for f in &state.findings {
        let id = f.id.as_str();
        if inline.contains(id) {
            report.inline.push(f.id.clone());
        } else if proposal_backed.contains(id) {
            report.proposal_backed.push(f.id.clone());
        } else {
            report.remnant.push(f.id.clone());
        }
    }
    report
}

// --- per-kind reducer rules ---------------------------------------------------

fn apply_finding_asserted(
    state: &mut Project,
    event: &StateEvent,
    idx: &mut FindingIndex,
) -> Result<(), String> {
    // For a v0.3 frontier emitting genesis events, finding.asserted carries
    // the full finding in payload.finding; for legacy frontiers replay is
    // a no-op (the finding was already materialized at genesis).
    if let Some(finding_value) = event.payload.get("finding") {
        let finding: crate::bundle::FindingBundle =
            serde_json::from_value(finding_value.clone())
                .map_err(|e| format!("reducer: invalid finding.asserted payload.finding: {e}"))?;
        if idx.contains_key(&finding.id) {
            return Ok(());
        }
        let position = state.findings.len();
        idx.insert(finding.id.clone(), position);
        state.findings.push(finding);
    }
    Ok(())
}

fn apply_finding_reviewed(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    let id = event.target.id.as_str();
    let status = event
        .payload
        .get("status")
        .and_then(Value::as_str)
        .ok_or("reducer: finding.reviewed missing payload.status")?;
    let idx = *index
        .get(id)
        .ok_or_else(|| format!("reducer: finding.reviewed targets unknown finding {id}"))?;
    use crate::bundle::ReviewState;
    let new_state = match status {
        "accepted" | "approved" => ReviewState::Accepted,
        "contested" => ReviewState::Contested,
        "needs_revision" => ReviewState::NeedsRevision,
        "rejected" => ReviewState::Rejected,
        other => return Err(format!("reducer: unsupported review status '{other}'")),
    };
    state.findings[idx].flags.contested = new_state.implies_contested();
    state.findings[idx].flags.review_state = Some(new_state);
    Ok(())
}

fn apply_finding_annotation(
    state: &mut Project,
    event: &StateEvent,
    _kind_label: &str,
    index: &mut FindingIndex,
) -> Result<(), String> {
    let id = event.target.id.as_str();
    let text = event
        .payload
        .get("text")
        .and_then(Value::as_str)
        .ok_or("reducer: annotation event missing payload.text")?;
    let annotation_id = event
        .payload
        .get("annotation_id")
        .and_then(Value::as_str)
        .ok_or("reducer: annotation event missing payload.annotation_id")?;
    let idx = *index
        .get(id)
        .ok_or_else(|| format!("reducer: annotation event targets unknown finding {id}"))?;
    if state.findings[idx]
        .annotations
        .iter()
        .any(|a| a.id == annotation_id)
    {
        return Ok(());
    }
    // Phase β (v0.6): pass through optional structured provenance from
    // the event payload to the materialized annotation. The validator in
    // `events::validate_event_payload` already rejected all-empty
    // provenance objects, so deserialization here is best-effort —
    // unknown shapes silently drop to None rather than failing the
    // whole reduce.
    let provenance = event
        .payload
        .get("provenance")
        .and_then(|v| serde_json::from_value::<crate::bundle::ProvenanceRef>(v.clone()).ok());
    state.findings[idx].annotations.push(Annotation {
        id: annotation_id.to_string(),
        text: text.to_string(),
        author: event.actor.id.clone(),
        timestamp: event.timestamp.clone(),
        provenance,
    });
    Ok(())
}

fn apply_finding_confidence_revised(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    let id = event.target.id.as_str();
    let new_score = event
        .payload
        .get("new_score")
        .and_then(Value::as_f64)
        .ok_or("reducer: finding.confidence_revised missing payload.new_score")?;
    let previous = event
        .payload
        .get("previous_score")
        .and_then(Value::as_f64)
        .unwrap_or(0.0);
    let idx = *index
        .get(id)
        .ok_or_else(|| format!("reducer: confidence_revised targets unknown finding {id}"))?;
    let updated_at = event
        .payload
        .get("updated_at")
        .and_then(Value::as_str)
        .map(str::to_string)
        .unwrap_or_else(|| event.timestamp.clone());
    state.findings[idx].confidence.score = new_score;
    state.findings[idx].confidence.basis = format!(
        "expert revision from {:.3} to {:.3}: {}",
        previous, new_score, event.reason
    );
    state.findings[idx].confidence.method = ConfidenceMethod::ExpertJudgment;
    state.findings[idx].updated = Some(updated_at);
    Ok(())
}

fn apply_finding_rejected(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    let id = event.target.id.as_str();
    let idx = *index
        .get(id)
        .ok_or_else(|| format!("reducer: finding.rejected targets unknown finding {id}"))?;
    state.findings[idx].flags.contested = true;
    Ok(())
}

fn apply_finding_retracted(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    let id = event.target.id.as_str();
    let idx = *index
        .get(id)
        .ok_or_else(|| format!("reducer: finding.retracted targets unknown finding {id}"))?;
    state.findings[idx].flags.retracted = true;
    Ok(())
}

/// Append a claim-granularity attribution to a finding's provenance. Purely
/// descriptive: it touches no flag, no confidence, no review state, and the gate
/// never reads `contributions[]` as evidence. Idempotent replay — a contribution
/// already present (same unit + agent + role) is not duplicated.
fn apply_finding_contribution_recorded(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    let id = event.target.id.as_str();
    let idx = *index.get(id).ok_or_else(|| {
        format!("reducer: finding.contribution.recorded targets unknown finding {id}")
    })?;
    let contribution: crate::bundle::Contribution = serde_json::from_value(
        event
            .payload
            .get("contribution")
            .cloned()
            .ok_or("reducer: finding.contribution.recorded missing payload.contribution")?,
    )
    .map_err(|e| format!("reducer: malformed contribution: {e}"))?;
    contribution.validate()?;
    let existing = &mut state.findings[idx].provenance.contributions;
    if !existing.iter().any(|c| {
        c.unit == contribution.unit
            && c.agent_id == contribution.agent_id
            && c.role == contribution.role
    }) {
        existing.push(contribution);
    }
    Ok(())
}

/// `finding.superseded` targets the OLD finding and flips its
/// `flags.superseded` (idempotent). The replacement finding is NOT
/// applied here: the event payload is thin (`{proposal_id,
/// new_finding_id}`) and the replacement's body lives in the accepted
/// proposal's `payload.new_finding`, entering replay as a genesis seed.
/// Note: the writer (`proposals::apply_supersede`) also auto-injects a
/// `supersedes` link into the replacement; links are excluded from
/// `finding_hash`, so replay verification is unaffected by that
/// injection.
fn apply_finding_superseded(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    let id = event.target.id.as_str();
    let idx = *index
        .get(id)
        .ok_or_else(|| format!("reducer: finding.superseded targets unknown finding {id}"))?;
    state.findings[idx].flags.superseded = true;
    Ok(())
}

/// `assertion.reinterpreted_causal` replays the causal re-grading from
/// the event's `payload.after` (`{claim, grade}`), mirroring the writer
/// in `state::causal_set`. Invalid vocabulary is an error — the payload
/// was validated at emit time, so a mismatch here means a corrupted log.
fn apply_assertion_reinterpreted_causal(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    use crate::bundle::{CausalClaim, CausalEvidenceGrade};
    let id = event.target.id.as_str();
    let idx = *index.get(id).ok_or_else(|| {
        format!("reducer: assertion.reinterpreted_causal targets unknown finding {id}")
    })?;
    let after = event
        .payload
        .get("after")
        .ok_or("reducer: assertion.reinterpreted_causal missing payload.after")?;
    let claim = after
        .get("claim")
        .and_then(Value::as_str)
        .ok_or("reducer: assertion.reinterpreted_causal missing payload.after.claim")?;
    let parsed_claim = match claim {
        "correlation" => CausalClaim::Correlation,
        "mediation" => CausalClaim::Mediation,
        "intervention" => CausalClaim::Intervention,
        other => return Err(format!("reducer: invalid causal claim '{other}'")),
    };
    let parsed_grade = match after.get("grade").and_then(Value::as_str) {
        None => None,
        Some("rct") => Some(CausalEvidenceGrade::Rct),
        Some("quasi_experimental") => Some(CausalEvidenceGrade::QuasiExperimental),
        Some("observational") => Some(CausalEvidenceGrade::Observational),
        Some("theoretical") => Some(CausalEvidenceGrade::Theoretical),
        Some(other) => return Err(format!("reducer: invalid causal evidence grade '{other}'")),
    };
    state.findings[idx].assertion.causal_claim = Some(parsed_claim);
    if let Some(g) = parsed_grade {
        state.findings[idx].assertion.causal_evidence_grade = Some(g);
    }
    Ok(())
}

fn apply_finding_dependency_invalidated(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    let id = event.target.id.as_str();
    let upstream = event
        .payload
        .get("upstream_finding_id")
        .and_then(Value::as_str)
        .unwrap_or("?");
    let depth = event
        .payload
        .get("depth")
        .and_then(Value::as_u64)
        .unwrap_or(1);
    let idx = *index.get(id).ok_or_else(|| {
        format!("reducer: finding.dependency_invalidated targets unknown finding {id}")
    })?;
    state.findings[idx].flags.contested = true;
    let annotation_id = format!("ann_dep_{}_{}", &event.id[4..], depth);
    if !state.findings[idx]
        .annotations
        .iter()
        .any(|a| a.id == annotation_id)
    {
        state.findings[idx].annotations.push(Annotation {
            id: annotation_id,
            text: format!("Upstream {upstream} retracted (cascade depth {depth})."),
            author: event.actor.id.clone(),
            timestamp: event.timestamp.clone(),
            provenance: None,
        });
    }
    Ok(())
}

fn apply_artifact_asserted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let artifact_value = event
        .payload
        .get("artifact")
        .ok_or("reducer: artifact.asserted missing payload.artifact")?;
    let artifact: crate::bundle::Artifact = serde_json::from_value(artifact_value.clone())
        .map_err(|e| format!("reducer: invalid artifact.asserted payload: {e}"))?;
    if state.artifacts.iter().any(|a| a.id == artifact.id) {
        return Ok(());
    }
    state.artifacts.push(artifact);
    Ok(())
}

/// Append a verifier attachment (target = `vf_…`) to the sidecar collection.
/// Idempotent on the content-addressed `vva_` id. The per-finding trust-gate
/// status is derived from these on read (export), never stored here.
fn apply_verifier_attachment_added(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let value = event
        .payload
        .get("attachment")
        .ok_or("reducer: verifier_attachment.added missing payload.attachment")?;
    let att: crate::verifier_attachment::VerifierAttachment = serde_json::from_value(value.clone())
        .map_err(|e| format!("reducer: invalid verifier_attachment.added payload: {e}"))?;
    // Re-verify the embedded object's content-addressed id on apply, exactly as
    // every sibling object reducer does (this arm previously skipped it, leaving
    // a forged-id attachment landable). The gate's G4 id-integrity check is the
    // second line of defense; this is the first.
    att.verify()
        .map_err(|e| format!("reducer: verifier_attachment.added failed id-integrity: {e}"))?;
    if state.verifier_attachments.iter().any(|a| a.id == att.id) {
        return Ok(());
    }
    state.verifier_attachments.push(att);
    Ok(())
}

fn apply_artifact_reviewed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let id = event.target.id.as_str();
    let status = event
        .payload
        .get("status")
        .and_then(Value::as_str)
        .ok_or("reducer: artifact.reviewed missing payload.status")?;
    use crate::bundle::ReviewState;
    let new_state = match status {
        "accepted" | "approved" => ReviewState::Accepted,
        "contested" => ReviewState::Contested,
        "needs_revision" => ReviewState::NeedsRevision,
        "rejected" => ReviewState::Rejected,
        other => return Err(format!("reducer: unsupported review status '{other}'")),
    };
    let idx = state
        .artifacts
        .iter()
        .position(|a| a.id == id)
        .ok_or_else(|| format!("reducer: artifact.reviewed targets unknown artifact {id}"))?;
    state.artifacts[idx].review_state = Some(new_state);
    Ok(())
}

fn apply_artifact_retracted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let id = event.target.id.as_str();
    let idx = state
        .artifacts
        .iter()
        .position(|a| a.id == id)
        .ok_or_else(|| format!("reducer: artifact.retracted targets unknown artifact {id}"))?;
    state.artifacts[idx].retracted = true;
    Ok(())
}

/// v0.51: Apply a `tier.set` event. Re-classifies the access_tier on
/// the matched finding / artifact. The validator
/// has already checked the object_type and tier strings; here we
/// just locate the object and mutate.
fn apply_tier_set(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let object_type = event
        .payload
        .get("object_type")
        .and_then(Value::as_str)
        .ok_or("reducer: tier.set missing payload.object_type")?;
    let object_id = event
        .payload
        .get("object_id")
        .and_then(Value::as_str)
        .ok_or("reducer: tier.set missing payload.object_id")?;
    let new_tier_str = event
        .payload
        .get("new_tier")
        .and_then(Value::as_str)
        .ok_or("reducer: tier.set missing payload.new_tier")?;
    let new_tier = crate::access_tier::AccessTier::parse(new_tier_str)
        .map_err(|e| format!("reducer: tier.set {e}"))?;
    match object_type {
        "finding" => {
            let idx = state
                .findings
                .iter()
                .position(|f| f.id == object_id)
                .ok_or_else(|| format!("reducer: tier.set targets unknown finding {object_id}"))?;
            state.findings[idx].access_tier = new_tier;
        }
        "artifact" => {
            let idx = state
                .artifacts
                .iter()
                .position(|a| a.id == object_id)
                .ok_or_else(|| format!("reducer: tier.set targets unknown artifact {object_id}"))?;
            state.artifacts[idx].access_tier = new_tier;
        }
        other => {
            return Err(format!(
                "reducer: tier.set object_type '{other}' must be one of finding, artifact"
            ));
        }
    }
    Ok(())
}

/// v0.213: append a ReleasedDiffPackRecord to
/// `state.released_diff_packs` when a `diff_pack.released` event
/// lands on the canonical log. Idempotent on pack_id — re-applying
/// the same released event is a no-op so hub re-sync stays
/// clean. Theorem 29 pins the accumulation algebra.
fn apply_diff_pack_released(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::released_diff_pack::ReleasedDiffPackRecord;

    let pack_id = event
        .payload
        .get("pack_id")
        .and_then(Value::as_str)
        .ok_or("diff_pack.released event missing payload.pack_id")?;
    if !pack_id.starts_with("vsd_") {
        return Err(format!(
            "diff_pack.released event payload.pack_id must start with `vsd_`, got `{pack_id}`"
        ));
    }
    if state
        .released_diff_packs
        .iter()
        .any(|r| r.pack_id == pack_id)
    {
        return Ok(());
    }
    let frontier_id = event
        .payload
        .get("frontier_id")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    let summary = event
        .payload
        .get("summary")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    let aggregate_kind = event
        .payload
        .get("aggregate_kind")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    let member_proposals: Vec<String> = event
        .payload
        .get("members")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(Value::as_str)
                .map(String::from)
                .collect()
        })
        .unwrap_or_default();
    state
        .released_diff_packs
        .push(ReleasedDiffPackRecord::from_released_event(
            pack_id.to_string(),
            frontier_id,
            summary,
            aggregate_kind,
            event.timestamp.clone(),
            event.id.clone(),
            member_proposals,
        ));
    Ok(())
}

/// v0.213: update the matching ReleasedDiffPackRecord when a
/// `diff_pack.reviewed` event lands. Sets verdict +
/// verdict_event_id + reviewer_actor + applied_members +
/// sdk_only_members from the payload. Idempotent under
/// re-application: re-applying the same verdict to the same
/// record produces no further change.
///
/// If no ReleasedDiffPackRecord exists for the pack_id yet (the
/// release event has not been replayed, or the pack was promoted
/// without first emitting `diff_pack.released`), the function
/// creates a record on the fly from the verdict event's payload
/// so the log stays self-sufficient.
fn apply_diff_pack_reviewed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::released_diff_pack::{ReleasedDiffPackRecord, ReleasedVerdict};

    let pack_id = event
        .payload
        .get("pack_id")
        .and_then(Value::as_str)
        .ok_or("diff_pack.reviewed event missing payload.pack_id")?
        .to_string();
    if !pack_id.starts_with("vsd_") {
        return Err(format!(
            "diff_pack.reviewed event payload.pack_id must start with `vsd_`, got `{pack_id}`"
        ));
    }
    let verdict_str = event
        .payload
        .get("verdict")
        .and_then(Value::as_str)
        .ok_or("diff_pack.reviewed event missing payload.verdict")?;
    let verdict = ReleasedVerdict::from_str_ci(verdict_str).ok_or_else(|| {
        format!(
            "diff_pack.reviewed event payload.verdict must be accept|reject|revise, got `{verdict_str}`"
        )
    })?;
    let reviewer_actor = event
        .payload
        .get("reviewer_actor")
        .and_then(Value::as_str)
        .unwrap_or(&event.actor.id)
        .to_string();
    let applied: Vec<String> = event
        .payload
        .get("applied_members")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();
    let sdk_only: Vec<String> = event
        .payload
        .get("sdk_only_members")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    if let Some(rec) = state
        .released_diff_packs
        .iter_mut()
        .find(|r| r.pack_id == pack_id)
    {
        rec.verdict = Some(verdict);
        rec.verdict_event_id = Some(event.id.clone());
        rec.reviewer_actor = Some(reviewer_actor);
        rec.applied_members = applied;
        rec.sdk_only_members = sdk_only;
    } else {
        // No prior `diff_pack.released` event for this pack. Create
        // a record from the verdict event so the log stays self-
        // sufficient. The promoter typically emits the release event
        // before the verdict, but a hub that receives only the
        // verdict (e.g., a peer hub that missed the release)
        // can still reconstruct a sensible record.
        let mut rec = ReleasedDiffPackRecord::from_released_event(
            pack_id,
            event
                .payload
                .get("frontier_id")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
            String::new(),
            String::new(),
            event.timestamp.clone(),
            String::new(),
            Vec::new(),
        );
        rec.verdict = Some(verdict);
        rec.verdict_event_id = Some(event.id.clone());
        rec.reviewer_actor = Some(reviewer_actor);
        rec.applied_members = applied;
        rec.sdk_only_members = sdk_only;
        state.released_diff_packs.push(rec);
    }
    Ok(())
}

/// v0.218: append a VerdictConflict record to
/// `state.verdict_conflicts` when a `verdict_conflict.resolved`
/// event lands. The full conflict body lives in the event payload
/// under `conflict`. Idempotent on conflict_id — re-applying the
/// same resolution is a no-op. T32 pins the bounded-length
/// accumulation algebra.
fn apply_verdict_conflict_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::verdict_conflict::VerdictConflict;

    let conflict_value = event
        .payload
        .get("conflict")
        .ok_or("verdict_conflict.resolved event missing payload.conflict")?
        .clone();
    let conflict: VerdictConflict = serde_json::from_value(conflict_value)
        .map_err(|e| format!("verdict_conflict.resolved payload parse: {e}"))?;
    conflict
        .verify()
        .map_err(|e| format!("verdict_conflict.resolved body did not verify: {e}"))?;
    if state
        .verdict_conflicts
        .iter()
        .any(|c| c.conflict_id == conflict.conflict_id)
    {
        return Ok(());
    }
    state.verdict_conflicts.push(conflict);
    Ok(())
}

/// T7: upsert a resolved Contradiction into `state.contradictions`
/// when a `contradiction.resolved` event lands. The full object lives
/// in the event payload under `contradiction`. Integrity check: the
/// object's `contradiction_id` must equal the content address of its
/// own (frontier_id, finding pair), so a forged or mismatched id is
/// rejected. Latest resolution per id wins — re-applying the same
/// event is a no-op; a later transition replaces the earlier record.
fn apply_contradiction_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::contradiction::Contradiction;

    let value = event
        .payload
        .get("contradiction")
        .ok_or("contradiction.resolved event missing payload.contradiction")?
        .clone();
    let contradiction: Contradiction = serde_json::from_value(value)
        .map_err(|e| format!("contradiction.resolved payload parse: {e}"))?;

    let expected = Contradiction::content_address(
        &contradiction.frontier_id,
        &contradiction.finding_a,
        &contradiction.finding_b,
    );
    if contradiction.contradiction_id != expected {
        return Err(format!(
            "contradiction.resolved id '{}' does not match its pair (expected '{expected}')",
            contradiction.contradiction_id
        ));
    }

    if let Some(slot) = state
        .contradictions
        .iter_mut()
        .find(|c| c.contradiction_id == contradiction.contradiction_id)
    {
        *slot = contradiction;
    } else {
        state.contradictions.push(contradiction);
    }
    Ok(())
}

/// Idempotent upsert into a content-addressed collection: replace the element
/// that matches `item` by `same`, or append it. The shared shape behind the
/// attempt/resolution reducer arms.
fn upsert_by<T>(vec: &mut Vec<T>, item: T, same: impl Fn(&T, &T) -> bool) {
    if let Some(slot) = vec.iter_mut().find(|x| same(x, &item)) {
        *slot = item;
    } else {
        vec.push(item);
    }
}

/// Upsert a signed banked attempt into `state.attempts` when an
/// `attempt.deposited` event lands. The full object lives in
/// `payload.attempt`. Integrity: the object must `verify()` (id re-derives,
/// signature checks, claim_digest matches) — a forged or hand-edited deposit
/// is rejected. Idempotent by `vat_` id.
/// `statement.attested`: upsert the signed attestation from
/// `payload.attestation`. The record's own signature + content address
/// are re-verified on every apply — a tampered attestation cannot
/// re-enter through replay.
/// `attempt.claimed`: append/refresh an obligation lease. The
/// determinism rule: a prior lease is "expired" relative to THIS
/// event's timestamp (parse both RFC3339 instants; if claimed_at + ttl
/// <= new event's timestamp, the old lease is dead and the claim
/// succeeds). Same claimant refreshing their own live lease is allowed only
/// under the same key. A zero-TTL update is an immediate release and must
/// compare-and-swap the exact current claim event with the same actor and key.
fn apply_attempt_claimed(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let p = &event.payload;
    let obligation_id = p
        .get("obligation_id")
        .and_then(Value::as_str)
        .ok_or("attempt.claimed missing payload.obligation_id")?;
    let ttl = p
        .get("lease_ttl_seconds")
        .and_then(Value::as_u64)
        .ok_or("attempt.claimed missing payload.lease_ttl_seconds")?;
    if ttl > crate::events::MAX_ATTEMPT_LEASE_TTL_SECONDS {
        return Err(format!(
            "attempt.claimed payload.lease_ttl_seconds must be at most {}",
            crate::events::MAX_ATTEMPT_LEASE_TTL_SECONDS
        ));
    }
    let claimant_actor = p
        .get("claimant_actor")
        .and_then(Value::as_str)
        .unwrap_or(&event.actor.id)
        .to_string();
    let claimant_pubkey = p
        .get("claimant_pubkey")
        .and_then(Value::as_str)
        .unwrap_or("")
        .to_string();
    if claimant_actor != event.actor.id {
        return Err(format!(
            "attempt.claimed payload claimant {claimant_actor} does not match event actor {}",
            event.actor.id
        ));
    }
    if event.target.id != obligation_id {
        return Err(format!(
            "attempt.claimed target {} does not match obligation {obligation_id}",
            event.target.id
        ));
    }
    let prior_claim_event_id = p.get("prior_claim_event_id").and_then(Value::as_str);
    let release_reason = p.get("release_reason").and_then(Value::as_str);
    let parse = chrono::DateTime::parse_from_rfc3339;
    let event_at = parse(&event.timestamp)
        .map_err(|e| format!("attempt.claimed: bad event timestamp: {e}"))?;
    let live_at_event = |claimed_at: &chrono::DateTime<chrono::FixedOffset>, lease_ttl: u64| {
        i64::try_from(lease_ttl)
            .ok()
            .and_then(chrono::Duration::try_seconds)
            .and_then(|duration| claimed_at.checked_add_signed(duration))
            .is_some_and(|expires_at| expires_at > event_at)
    };
    let existing = state
        .attempt_claims
        .iter()
        .find(|c| c.obligation_id == obligation_id)
        .cloned();
    if ttl == 0 {
        let existing = existing.as_ref().ok_or_else(|| {
            format!("cannot release obligation {obligation_id}: no current lease exists")
        })?;
        let claimed_at = parse(&existing.claimed_at)
            .map_err(|e| format!("attempt.claimed: bad prior claim timestamp: {e}"))?;
        if !live_at_event(&claimed_at, existing.lease_ttl_seconds) {
            return Err(format!(
                "cannot release obligation {obligation_id}: the current lease is not live"
            ));
        }
        if event_at < claimed_at {
            return Err(format!(
                "cannot release obligation {obligation_id}: release timestamp predates the prior claim"
            ));
        }
        if existing.claimant_actor != claimant_actor {
            return Err(format!(
                "cannot release obligation {obligation_id}: leased by {}, not {claimant_actor}",
                existing.claimant_actor
            ));
        }
        if existing.claimant_pubkey != claimant_pubkey {
            return Err(format!(
                "cannot release obligation {obligation_id}: claimant key does not match the current lease"
            ));
        }
        let expected_prior = existing.claim_event_id.as_deref().ok_or_else(|| {
            format!(
                "cannot release obligation {obligation_id}: prior lease identity is unavailable"
            )
        })?;
        if prior_claim_event_id != Some(expected_prior) {
            return Err(format!(
                "cannot release obligation {obligation_id}: prior lease identity does not match"
            ));
        }
        if release_reason.is_none_or(|reason| reason.trim().is_empty()) {
            return Err(format!(
                "cannot release obligation {obligation_id}: release reason is required"
            ));
        }
    } else if let Some(existing) = existing.as_ref() {
        let live = parse(&existing.claimed_at)
            .map(|claimed_at| live_at_event(&claimed_at, existing.lease_ttl_seconds))
            .unwrap_or(false);
        if live && existing.claimant_actor != claimant_actor {
            return Err(format!(
                "obligation {obligation_id} is leased by {} until +{}s; route around it or wait for expiry",
                existing.claimant_actor, existing.lease_ttl_seconds
            ));
        }
        if live && existing.claimant_pubkey != claimant_pubkey {
            return Err(format!(
                "obligation {obligation_id} is leased by {claimant_actor} under a different key; use the original session key or wait for expiry"
            ));
        }
        if live
            && prior_claim_event_id.is_some()
            && prior_claim_event_id != existing.claim_event_id.as_deref()
        {
            return Err(format!(
                "obligation {obligation_id} refresh names a stale prior lease"
            ));
        }
    }
    state
        .attempt_claims
        .retain(|c| c.obligation_id != obligation_id);
    state.attempt_claims.push(crate::project::AttemptClaim {
        obligation_id: obligation_id.to_string(),
        claimant_actor,
        claimant_pubkey,
        claimed_at: event.timestamp.clone(),
        lease_ttl_seconds: ttl,
        claim_event_id: Some(event.id.clone()),
    });
    Ok(())
}

/// `statement.registered`: append a priority registration (idempotent
/// on statement_hash).
fn apply_statement_registered(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let p = &event.payload;
    let hash = p
        .get("statement_hash")
        .and_then(Value::as_str)
        .ok_or("statement.registered missing payload.statement_hash")?;
    if hash.len() != 64 || hex::decode(hash).is_err() {
        return Err("statement_hash must be 32 bytes of hex".to_string());
    }
    if state
        .statement_registrations
        .iter()
        .any(|r| r.statement_hash == hash)
    {
        return Ok(());
    }
    state
        .statement_registrations
        .push(crate::project::StatementRegistration {
            statement_hash: hash.to_string(),
            informal_ref: p
                .get("informal_ref")
                .and_then(Value::as_str)
                .unwrap_or("")
                .to_string(),
            registered_by: event.actor.id.clone(),
            registered_at: event.timestamp.clone(),
            // Gap 5 (STATE_PLANE_MEMO appendix): the optional
            // finding-to-registration edge. Old events carry no
            // payload.finding_id and store None.
            finding_id: p
                .get("finding_id")
                .and_then(Value::as_str)
                .map(str::to_string),
        });
    Ok(())
}

fn apply_statement_attested(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::statement_attestation::StatementAttestation;
    let value = event
        .payload
        .get("attestation")
        .ok_or("statement.attested event missing payload.attestation")?
        .clone();
    let att: StatementAttestation = serde_json::from_value(value)
        .map_err(|e| format!("statement.attested payload parse: {e}"))?;
    att.verify()
        .map_err(|e| format!("statement.attested rejected: {e}"))?;
    if let Some(existing) = state
        .statement_attestations
        .iter_mut()
        .find(|a| a.id == att.id)
    {
        *existing = att;
    } else {
        state.statement_attestations.push(att);
    }
    Ok(())
}

/// `anchor.attached`: upsert a signed `val_` anchor link from
/// `payload.anchor_link`. The link's own signature + content address are
/// re-verified on every apply, so a tampered anchor cannot enter state.
fn apply_anchor_attached(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::anchor::AnchorLink;
    let value = event
        .payload
        .get("anchor_link")
        .ok_or("anchor.attached event missing payload.anchor_link")?
        .clone();
    let link: AnchorLink =
        serde_json::from_value(value).map_err(|e| format!("anchor.attached payload parse: {e}"))?;
    link.verify()
        .map_err(|e| format!("anchor.attached rejected: {e}"))?;
    if let Some(existing) = state.anchor_links.iter_mut().find(|a| a.id == link.id) {
        *existing = link;
    } else {
        state.anchor_links.push(link);
    }
    Ok(())
}

/// `anchor.retracted`: remove the anchor link named by
/// `payload.anchor_link_id`. Anchor attachment is fallible and therefore
/// retractable (frontier-calculus Law 22). Retracting an absent id is a
/// no-op, so replay stays idempotent.
fn apply_anchor_retracted(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    let id = event
        .payload
        .get("anchor_link_id")
        .and_then(|v| v.as_str())
        .ok_or("anchor.retracted event missing payload.anchor_link_id")?;
    state.anchor_links.retain(|a| a.id != id);
    Ok(())
}

fn apply_attempt_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::attempt::Attempt;

    let value = event
        .payload
        .get("attempt")
        .ok_or("attempt.deposited event missing payload.attempt")?
        .clone();
    let attempt: Attempt = serde_json::from_value(value)
        .map_err(|e| format!("attempt.deposited payload parse: {e}"))?;
    attempt
        .verify()
        .map_err(|e| format!("attempt.deposited rejected: {e}"))?;

    upsert_by(&mut state.attempts, attempt, |a, b| {
        a.attempt_id == b.attempt_id
    });
    Ok(())
}

/// Upsert a signed cross-domain transfer into `state.transfers` when a
/// `transfer.deposited` event lands. The full object lives in
/// `payload.transfer`. Integrity: the object must `verify()` (id re-derives,
/// signature checks) — a forged or hand-edited transfer is rejected. Admission
/// (whether the link is sound) is NOT decided here; it is derived on read via
/// `transfer::derive_transfer_status`. Idempotent by `vtr_` id.
fn apply_transfer_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::transfer::Transfer;

    let value = event
        .payload
        .get("transfer")
        .ok_or("transfer.deposited event missing payload.transfer")?
        .clone();
    let transfer: Transfer = serde_json::from_value(value)
        .map_err(|e| format!("transfer.deposited payload parse: {e}"))?;
    transfer
        .verify()
        .map_err(|e| format!("transfer.deposited rejected: {e}"))?;

    upsert_by(&mut state.transfers, transfer, |a, b| {
        a.transfer_id == b.transfer_id
    });
    Ok(())
}

/// Upsert a signed significance endorsement into `state.endorsements` when an
/// `endorsement.deposited` event lands. The object lives in
/// `payload.endorsement`. Integrity: it must `verify()` (id re-derives,
/// signature checks). Idempotent by `ven_` id. There is deliberately NO
/// aggregation here — endorsements accumulate as individual records and are
/// never folded into a significance score.
fn apply_endorsement_deposited(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::endorsement::Endorsement;

    let value = event
        .payload
        .get("endorsement")
        .ok_or("endorsement.deposited event missing payload.endorsement")?
        .clone();
    let endorsement: Endorsement = serde_json::from_value(value)
        .map_err(|e| format!("endorsement.deposited payload parse: {e}"))?;
    endorsement
        .verify()
        .map_err(|e| format!("endorsement.deposited rejected: {e}"))?;

    upsert_by(&mut state.endorsements, endorsement, |a, b| {
        a.endorsement_id == b.endorsement_id
    });
    Ok(())
}

/// Append a lifecycle transition into `state.attempt_resolutions` when an
/// `attempt.resolved` event lands. The [`crate::attempt::ResolutionEvent`]
/// lives in `payload.resolution`. Integrity: the object must `verify()`
/// (`vre_` id re-derives). Idempotent by `vre_` id; the head per attempt is
/// the latest by `at`, computed on read (`Project::head_resolution`).
fn apply_attempt_resolved(state: &mut Project, event: &StateEvent) -> Result<(), String> {
    use crate::attempt::ResolutionEvent;

    let value = event
        .payload
        .get("resolution")
        .ok_or("attempt.resolved event missing payload.resolution")?
        .clone();
    let resolution: ResolutionEvent = serde_json::from_value(value)
        .map_err(|e| format!("attempt.resolved payload parse: {e}"))?;
    resolution
        .verify()
        .map_err(|e| format!("attempt.resolved rejected: {e}"))?;

    upsert_by(&mut state.attempt_resolutions, resolution, |a, b| {
        a.resolution_id == b.resolution_id
    });
    Ok(())
}

/// v0.57: Apply a `finding.span_repaired` event. Appends a
/// `{section, text}` span object to
/// `state.findings[i].evidence.evidence_spans`. Idempotent:
/// applying twice with the same (section, text) pair is a no-op.
fn apply_finding_span_repaired(
    state: &mut Project,
    event: &StateEvent,
    index: &mut FindingIndex,
) -> Result<(), String> {
    if event.target.r#type != "finding" {
        return Err(format!(
            "reducer: finding.span_repaired target.type must be 'finding', got '{}'",
            event.target.r#type
        ));
    }
    let finding_id = event.target.id.as_str();
    let section = event
        .payload
        .get("section")
        .and_then(Value::as_str)
        .ok_or("reducer: finding.span_repaired missing payload.section")?;
    let text = event
        .payload
        .get("text")
        .and_then(Value::as_str)
        .ok_or("reducer: finding.span_repaired missing payload.text")?;
    let idx = *index.get(finding_id).ok_or_else(|| {
        format!("reducer: finding.span_repaired targets unknown finding {finding_id}")
    })?;
    let span_value = serde_json::json!({"section": section, "text": text});
    let already_present = state.findings[idx]
        .evidence
        .evidence_spans
        .iter()
        .any(|existing| {
            existing.get("section").and_then(Value::as_str) == Some(section)
                && existing.get("text").and_then(Value::as_str) == Some(text)
        });
    if !already_present {
        state.findings[idx].evidence.evidence_spans.push(span_value);
    }
    Ok(())
}

/// v0.56: Apply an `evidence_atom.locator_repaired` event. Sets
/// `locator` on the named atom and removes the "missing evidence
/// locator" caveat if present. Idempotent: applying twice with the
/// same locator is a no-op. Mismatched locator values fail the reduce
/// rather than silently overwriting, since divergent locators on the
/// same atom are a chain-integrity issue, not a repair.
fn apply_evidence_atom_locator_repaired(
    state: &mut Project,
    event: &StateEvent,
) -> Result<(), String> {
    if event.target.r#type != "evidence_atom" {
        return Err(format!(
            "reducer: evidence_atom.locator_repaired target.type must be 'evidence_atom', got '{}'",
            event.target.r#type
        ));
    }
    let atom_id = event.target.id.as_str();
    let locator = event
        .payload
        .get("locator")
        .and_then(Value::as_str)
        .ok_or("reducer: evidence_atom.locator_repaired missing payload.locator")?;
    let idx = state
        .evidence_atoms
        .iter()
        .position(|atom| atom.id == atom_id)
        .ok_or_else(|| {
            format!("reducer: evidence_atom.locator_repaired targets unknown atom {atom_id}")
        })?;
    if let Some(existing) = &state.evidence_atoms[idx].locator
        && existing != locator
    {
        return Err(format!(
            "reducer: evidence_atom {atom_id} already has locator '{existing}', refusing to overwrite with '{locator}'"
        ));
    }
    state.evidence_atoms[idx].locator = Some(locator.to_string());
    state.evidence_atoms[idx]
        .caveats
        .retain(|c| c != "missing evidence locator");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bundle::{Assertion, Conditions, Confidence, Evidence, Flags, Provenance};
    use crate::events::{FindingEventInput, NULL_HASH, StateActor, StateTarget};
    use chrono::Utc;
    use serde_json::json;

    fn lease_event(
        actor: &str,
        pubkey: &str,
        at: &str,
        ttl: u64,
        prior: Option<&str>,
        reason: Option<&str>,
    ) -> StateEvent {
        let mut payload = json!({
            "obligation_id": "scope:lease-cas",
            "lease_ttl_seconds": ttl,
            "claimant_actor": actor,
            "claimant_pubkey": pubkey,
        });
        if let Some(prior) = prior {
            payload["prior_claim_event_id"] = json!(prior);
        }
        if let Some(reason) = reason {
            payload["release_reason"] = json!(reason);
        }
        crate::events::new_finding_event(FindingEventInput {
            kind: crate::events::EVENT_KIND_ATTEMPT_CLAIMED,
            finding_id: "scope:lease-cas",
            actor_id: actor,
            actor_type: "agent",
            reason: reason.unwrap_or("claim fixture"),
            before_hash: NULL_HASH,
            after_hash: NULL_HASH,
            payload,
            caveats: Vec::new(),
            timestamp: Some(at),
        })
    }

    fn state_with_claim(claim: &StateEvent) -> crate::project::Project {
        let mut state = crate::project::assemble("lease", Vec::new(), 0, 0, "test");
        apply_event(&mut state, claim).unwrap();
        state
    }

    #[test]
    fn zero_ttl_lease_release_is_an_exact_same_owner_compare_and_swap() {
        let claim = lease_event(
            "agent:owner",
            &"11".repeat(32),
            "2026-07-14T12:00:00.500Z",
            3_600,
            None,
            None,
        );
        let initial = state_with_claim(&claim);
        assert_eq!(
            initial.attempt_claims[0].claim_event_id.as_deref(),
            Some(claim.id.as_str())
        );

        for (label, release, expected) in [
            (
                "different actor",
                lease_event(
                    "agent:other",
                    &"11".repeat(32),
                    "2026-07-14T12:01:00Z",
                    0,
                    Some(&claim.id),
                    Some("not mine"),
                ),
                "leased by agent:owner",
            ),
            (
                "different key",
                lease_event(
                    "agent:owner",
                    &"22".repeat(32),
                    "2026-07-14T12:01:00Z",
                    0,
                    Some(&claim.id),
                    Some("wrong key"),
                ),
                "key does not match",
            ),
            (
                "stale predecessor",
                lease_event(
                    "agent:owner",
                    &"11".repeat(32),
                    "2026-07-14T12:01:00Z",
                    0,
                    Some("vev_0000000000000000"),
                    Some("stale"),
                ),
                "prior lease identity does not match",
            ),
            (
                "backdated",
                lease_event(
                    "agent:owner",
                    &"11".repeat(32),
                    "2026-07-14T12:00:00.499Z",
                    0,
                    Some(&claim.id),
                    Some("backdated"),
                ),
                "predates the prior claim",
            ),
        ] {
            let mut state = state_with_claim(&claim);
            let error = apply_event(&mut state, &release).unwrap_err();
            assert!(error.contains(expected), "{label}: {error}");
            assert_eq!(state.attempt_claims, initial.attempt_claims, "{label}");
        }

        let mut state = initial;
        let release = lease_event(
            "agent:owner",
            &"11".repeat(32),
            "2026-07-14T12:01:00Z",
            0,
            Some(&claim.id),
            Some("switching approaches"),
        );
        apply_event(&mut state, &release).unwrap();
        assert_eq!(state.attempt_claims.len(), 1);
        assert_eq!(state.attempt_claims[0].lease_ttl_seconds, 0);
        assert_eq!(
            state.attempt_claims[0].claim_event_id.as_deref(),
            Some(release.id.as_str())
        );
    }

    #[test]
    fn live_lease_refresh_requires_the_same_actor_key() {
        let mut state = crate::project::assemble("lease", Vec::new(), 0, 0, "test");
        let claim = lease_event(
            "agent:owner",
            &"11".repeat(32),
            "2026-07-14T12:00:00Z",
            3_600,
            None,
            None,
        );
        apply_event(&mut state, &claim).unwrap();
        let refresh = lease_event(
            "agent:owner",
            &"22".repeat(32),
            "2026-07-14T12:01:00Z",
            3_600,
            Some(&claim.id),
            None,
        );
        let error = apply_event(&mut state, &refresh).unwrap_err();
        assert!(error.contains("different key"), "{error}");
    }

    fn finding(id: &str) -> crate::bundle::FindingBundle {
        crate::bundle::FindingBundle::new(
            Assertion {
                text: format!("test finding {id}"),
                assertion_type: "mechanism".to_string(),
                entities: Vec::new(),
                relation: None,
                direction: None,
                causal_claim: None,
                causal_evidence_grade: None,
            },
            Evidence {
                evidence_type: "experimental".to_string(),
                model_system: String::new(),
                method: "test".to_string(),
                replicated: false,
                replication_count: None,
                evidence_spans: Vec::new(),
            },
            Conditions {
                text: "test".to_string(),
                duration: None,
            },
            Confidence::raw(0.5, "test", 0.8),
            Provenance {
                source_type: "published_paper".to_string(),
                doi: Some(format!("10.1/test-{id}")),
                url: None,
                title: format!("Source for {id}"),
                authors: Vec::new(),
                year: Some(2026),
                license: None,
                publisher: None,
                funders: Vec::new(),
                extraction: crate::bundle::Extraction::default(),
                review: None,
                contributions: Vec::new(),
            },
            Flags {
                gap: false,
                negative_space: false,
                contested: false,
                retracted: false,
                declining: false,
                gravity_well: false,
                review_state: None,
                superseded: false,
                signature_threshold: None,
                jointly_accepted: false,
            },
        )
    }

    #[test]
    fn replay_with_no_events_is_identity() {
        let state = project::assemble("test", vec![finding("a")], 0, 0, "test");
        let v = verify_replay(&state);
        assert!(v.ok, "diffs: {:?} note: {}", v.diffs, v.note);
        assert_eq!(v.replayed_snapshot_hash, v.materialized_snapshot_hash);
    }

    #[test]
    fn reducer_marks_finding_contested() {
        let f = finding("a");
        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
        let event = events::new_finding_event(FindingEventInput {
            kind: "finding.reviewed",
            finding_id: &f.id,
            actor_id: "reviewer:test",
            actor_type: "human",
            reason: "test",
            before_hash: &events::finding_hash(&f),
            after_hash: NULL_HASH,
            payload: json!({"status": "contested"}),
            caveats: vec![],
            timestamp: None,
        });
        apply_event(&mut state, &event).unwrap();
        assert!(state.findings[0].flags.contested);
    }

    #[test]
    fn classify_provenance_separates_inline_from_remnant() {
        // `inline` carries its body in a finding.asserted event; `rem` has
        // no event at all (a pre-event-sourcing remnant seeded from cache).
        let inline = finding("inline");
        let rem = finding("rem");
        let mut state = project::assemble("test", vec![inline.clone(), rem.clone()], 0, 0, "test");
        state.events.push(StateEvent {
            schema: events::EVENT_SCHEMA.to_string(),
            id: "vev_inline".to_string(),
            kind: "finding.asserted".into(),
            target: StateTarget {
                r#type: "finding".to_string(),
                id: inline.id.clone(),
            },
            actor: StateActor {
                id: "reviewer:test".to_string(),
                r#type: "human".to_string(),
            },
            timestamp: Utc::now().to_rfc3339(),
            reason: "assert".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: events::finding_hash(&inline),
            payload: json!({ "finding": inline }),
            caveats: vec![],
            signature: None,
        });

        let report = classify_provenance(&state);
        assert_eq!(report.inline, vec![inline.id.clone()]);
        assert_eq!(report.remnant, vec![rem.id.clone()]);
        assert!(report.proposal_backed.is_empty());
        assert!(
            !report.fully_event_sourced(),
            "a frontier with a remnant is not fully event-sourced"
        );

        // Removing the remnant leaves an all-inline frontier: fully reducible.
        state.findings.retain(|f| f.id != rem.id);
        assert!(classify_provenance(&state).fully_event_sourced());
    }

    #[test]
    fn reducer_retracts_finding() {
        let f = finding("a");
        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
        let event = StateEvent {
            schema: events::EVENT_SCHEMA.to_string(),
            id: "vev_test".to_string(),
            kind: "finding.retracted".into(),
            target: StateTarget {
                r#type: "finding".to_string(),
                id: f.id.clone(),
            },
            actor: StateActor {
                id: "reviewer:test".to_string(),
                r#type: "human".to_string(),
            },
            timestamp: Utc::now().to_rfc3339(),
            reason: "test retraction".to_string(),
            before_hash: events::finding_hash(&f),
            after_hash: NULL_HASH.to_string(),
            payload: json!({"proposal_id": "vpr_x"}),
            caveats: vec![],
            signature: None,
        };
        apply_event(&mut state, &event).unwrap();
        assert!(state.findings[0].flags.retracted);
    }

    #[test]
    fn confidence_revision_replay_uses_event_payload_timestamp() {
        let f = finding("a");
        let mut expected = f.clone();
        let updated_at = "2026-05-07T23:30:00Z";
        let reason = "lower confidence after review";
        expected.confidence.score = 0.42;
        expected.confidence.basis = format!(
            "expert revision from {:.3} to {:.3}: {}",
            f.confidence.score, 0.42, reason
        );
        expected.confidence.method = ConfidenceMethod::ExpertJudgment;
        expected.updated = Some(updated_at.to_string());
        let mut state = project::assemble("test", vec![f.clone()], 0, 0, "test");
        let event = StateEvent {
            schema: events::EVENT_SCHEMA.to_string(),
            id: "vev_confidence".to_string(),
            kind: "finding.confidence_revised".into(),
            target: StateTarget {
                r#type: "finding".to_string(),
                id: f.id.clone(),
            },
            actor: StateActor {
                id: "reviewer:test".to_string(),
                r#type: "human".to_string(),
            },
            timestamp: "2026-05-07T23:31:00Z".to_string(),
            reason: reason.to_string(),
            before_hash: events::finding_hash(&f),
            after_hash: events::finding_hash(&expected),
            payload: json!({
                "previous_score": f.confidence.score,
                "new_score": 0.42,
                "updated_at": updated_at,
            }),
            caveats: vec![],
            signature: None,
        };

        apply_event(&mut state, &event).unwrap();

        assert_eq!(state.findings[0].updated.as_deref(), Some(updated_at));
        assert_eq!(events::finding_hash(&state.findings[0]), event.after_hash);
    }

    #[test]
    fn reducer_rejects_unknown_kind() {
        let mut state = project::assemble("test", vec![], 0, 0, "test");
        let event = StateEvent {
            schema: events::EVENT_SCHEMA.to_string(),
            id: "vev_test".to_string(),
            kind: "finding.unknown_kind".into(),
            target: StateTarget {
                r#type: "finding".to_string(),
                id: "vf_x".to_string(),
            },
            actor: StateActor {
                id: "x".to_string(),
                r#type: "human".to_string(),
            },
            timestamp: Utc::now().to_rfc3339(),
            reason: "x".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: NULL_HASH.to_string(),
            payload: Value::Null,
            caveats: vec![],
            signature: None,
        };
        let r = apply_event(&mut state, &event);
        assert!(r.is_err());
    }

    /// v0.49.3: the dispatch table in `apply_event` and the
    /// `REDUCER_MUTATION_KINDS` constant must agree. Adding a new
    /// match arm without updating the constant (or vice versa) makes
    /// CI fail loudly here, which then makes the cross-impl fixture
    /// coverage assertion fail correctly downstream. This is the
    /// single source of truth that retires the hand-maintained mirror.
    #[test]
    fn dispatch_handles_every_declared_kind() {
        for kind in REDUCER_MUTATION_KINDS {
            let mut state = project::assemble("test", vec![], 0, 0, "test");
            // Dummy event with the declared kind. The handler may
            // reject the payload (it's empty), but it MUST NOT reject
            // the kind itself with "unsupported event kind" — that
            // would prove the dispatch table is missing an arm for
            // a kind the constant declares.
            let event = StateEvent {
                schema: events::EVENT_SCHEMA.to_string(),
                id: "vev_dispatch_check".to_string(),
                kind: (*kind).into(),
                target: StateTarget {
                    r#type: "finding".to_string(),
                    id: "vf_x".to_string(),
                },
                actor: StateActor {
                    id: "x".to_string(),
                    r#type: "human".to_string(),
                },
                timestamp: Utc::now().to_rfc3339(),
                reason: String::new(),
                before_hash: NULL_HASH.to_string(),
                after_hash: NULL_HASH.to_string(),
                payload: Value::Null,
                caveats: vec![],
                signature: None,
            };
            let r = apply_event(&mut state, &event);
            if let Err(e) = r {
                assert!(
                    !e.contains("unsupported event kind"),
                    "kind {kind:?} declared in REDUCER_MUTATION_KINDS \
                     but rejected by apply_event dispatch: {e}"
                );
            }
        }
    }

    /// The writer/reducer seam invariant: every kind the protocol can
    /// emit or store (`events::KNOWN_EVENT_KINDS` — the writer-side
    /// universe) must be handled by the dispatch, either with a real arm
    /// or an explicit no-op. A new writer kind without a reducer arm
    /// fails here instead of erroring on the next replay of a live log.
    /// (This is the test that would have caught `finding.superseded`
    /// being emittable-but-unreplayable.)
    #[test]
    fn every_known_kind_reduces() {
        for kind in events::KNOWN_EVENT_KINDS {
            let mut state = project::assemble("test", vec![], 0, 0, "test");
            let event = StateEvent {
                schema: events::EVENT_SCHEMA.to_string(),
                id: "vev_known_kind_check".to_string(),
                kind: (*kind).into(),
                target: StateTarget {
                    r#type: "finding".to_string(),
                    id: "vf_x".to_string(),
                },
                actor: StateActor {
                    id: "x".to_string(),
                    r#type: "human".to_string(),
                },
                timestamp: Utc::now().to_rfc3339(),
                reason: String::new(),
                before_hash: NULL_HASH.to_string(),
                after_hash: NULL_HASH.to_string(),
                payload: Value::Null,
                caveats: vec![],
                signature: None,
            };
            if let Err(e) = apply_event(&mut state, &event) {
                assert!(
                    !e.contains("unsupported event kind"),
                    "kind {kind:?} is in events::KNOWN_EVENT_KINDS (a writer \
                     can emit it) but the reducer dispatch rejects it: {e}"
                );
            }
        }
    }

    fn project_with_one_atom(missing_locator: bool) -> Project {
        // `project::assemble` calls `sources::materialize_project`,
        // which derives one evidence atom per finding. The hand-built
        // atom below is appended after materialization with a distinct
        // id (`vea_test_atom`), so it survives alongside the derived
        // atom. Tests look up atoms by id via `atom_by_id`.
        let mut state = project::assemble("test-locator", vec![finding("a")], 0, 0, "test");
        state.sources.push(crate::sources::SourceRecord {
            id: "vs_test_source".to_string(),
            source_type: "paper".to_string(),
            locator: "doi:10.1/test-source".to_string(),
            content_hash: None,
            title: "Test source".to_string(),
            authors: Vec::new(),
            year: Some(2026),
            doi: Some("10.1/test-source".to_string()),
            pmid: None,
            imported_at: "2026-01-01T00:00:00Z".to_string(),
            extraction_mode: "manual".to_string(),
            source_quality: "declared".to_string(),
            caveats: Vec::new(),
            finding_ids: vec![state.findings[0].id.clone()],
        });
        state.evidence_atoms.push(crate::sources::EvidenceAtom {
            id: "vea_test_atom".to_string(),
            source_id: "vs_test_source".to_string(),
            finding_id: state.findings[0].id.clone(),
            locator: if missing_locator {
                None
            } else {
                Some("doi:10.1/already-set".to_string())
            },
            evidence_type: "experimental".to_string(),
            measurement_or_claim: "test claim".to_string(),
            supports_or_challenges: "supports".to_string(),
            condition_refs: Vec::new(),
            extraction_method: "manual".to_string(),
            human_verified: false,
            caveats: if missing_locator {
                vec!["missing evidence locator".to_string()]
            } else {
                Vec::new()
            },
        });
        state
    }

    fn atom_by_id<'a>(state: &'a Project, id: &str) -> &'a crate::sources::EvidenceAtom {
        state
            .evidence_atoms
            .iter()
            .find(|atom| atom.id == id)
            .expect("atom exists")
    }

    #[test]
    fn evidence_atom_locator_repaired_sets_locator_and_clears_caveat() {
        let mut state = project_with_one_atom(true);
        assert!(state.evidence_atoms[0].locator.is_none());
        let event = StateEvent {
            schema: crate::events::EVENT_SCHEMA.to_string(),
            id: "vev_test".to_string(),
            kind: "evidence_atom.locator_repaired".into(),
            target: StateTarget {
                r#type: "evidence_atom".to_string(),
                id: "vea_test_atom".to_string(),
            },
            actor: StateActor {
                id: "agent:test".to_string(),
                r#type: "agent".to_string(),
            },
            timestamp: Utc::now().to_rfc3339(),
            reason: "Mechanical repair from parent source".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: NULL_HASH.to_string(),
            payload: json!({
                "proposal_id": "vpr_test",
                "source_id": "vs_test_source",
                "locator": "doi:10.1/test-source",
            }),
            caveats: vec![],
            signature: None,
        };
        apply_event(&mut state, &event).expect("apply locator_repaired");
        let atom = atom_by_id(&state, "vea_test_atom");
        assert_eq!(atom.locator.as_deref(), Some("doi:10.1/test-source"));
        assert!(atom.caveats.is_empty());
    }

    #[test]
    fn evidence_atom_locator_repaired_is_idempotent() {
        let mut state = project_with_one_atom(true);
        let event = StateEvent {
            schema: crate::events::EVENT_SCHEMA.to_string(),
            id: "vev_test".to_string(),
            kind: "evidence_atom.locator_repaired".into(),
            target: StateTarget {
                r#type: "evidence_atom".to_string(),
                id: "vea_test_atom".to_string(),
            },
            actor: StateActor {
                id: "agent:test".to_string(),
                r#type: "agent".to_string(),
            },
            timestamp: Utc::now().to_rfc3339(),
            reason: "Mechanical repair from parent source".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: NULL_HASH.to_string(),
            payload: json!({
                "proposal_id": "vpr_test",
                "source_id": "vs_test_source",
                "locator": "doi:10.1/test-source",
            }),
            caveats: vec![],
            signature: None,
        };
        apply_event(&mut state, &event).expect("first apply");
        apply_event(&mut state, &event).expect("second apply is a no-op when locator matches");
        let atom = atom_by_id(&state, "vea_test_atom");
        assert_eq!(atom.locator.as_deref(), Some("doi:10.1/test-source"));
    }

    #[test]
    fn evidence_atom_locator_repaired_refuses_divergent_overwrite() {
        let mut state = project_with_one_atom(false);
        let event = StateEvent {
            schema: crate::events::EVENT_SCHEMA.to_string(),
            id: "vev_test".to_string(),
            kind: "evidence_atom.locator_repaired".into(),
            target: StateTarget {
                r#type: "evidence_atom".to_string(),
                id: "vea_test_atom".to_string(),
            },
            actor: StateActor {
                id: "agent:test".to_string(),
                r#type: "agent".to_string(),
            },
            timestamp: Utc::now().to_rfc3339(),
            reason: "Different repair".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: NULL_HASH.to_string(),
            payload: json!({
                "proposal_id": "vpr_test",
                "source_id": "vs_test_source",
                "locator": "doi:10.1/different",
            }),
            caveats: vec![],
            signature: None,
        };
        let r = apply_event(&mut state, &event);
        assert!(r.is_err());
        assert!(r.unwrap_err().contains("already has locator"));
    }

    #[test]
    fn evidence_atom_locator_repaired_does_not_mutate_findings() {
        // Cross-impl conformance: this event mutates evidence_atoms only.
        let mut state = project_with_one_atom(true);
        let hashes_before: Vec<String> = state
            .findings
            .iter()
            .map(crate::events::finding_hash)
            .collect();
        let event = StateEvent {
            schema: crate::events::EVENT_SCHEMA.to_string(),
            id: "vev_test".to_string(),
            kind: "evidence_atom.locator_repaired".into(),
            target: StateTarget {
                r#type: "evidence_atom".to_string(),
                id: "vea_test_atom".to_string(),
            },
            actor: StateActor {
                id: "agent:test".to_string(),
                r#type: "agent".to_string(),
            },
            timestamp: Utc::now().to_rfc3339(),
            reason: "Mechanical repair".to_string(),
            before_hash: NULL_HASH.to_string(),
            after_hash: NULL_HASH.to_string(),
            payload: json!({
                "proposal_id": "vpr_test",
                "source_id": "vs_test_source",
                "locator": "doi:10.1/test-source",
            }),
            caveats: vec![],
            signature: None,
        };
        apply_event(&mut state, &event).expect("apply ok");
        let hashes_after: Vec<String> = state
            .findings
            .iter()
            .map(crate::events::finding_hash)
            .collect();
        assert_eq!(hashes_before, hashes_after);
    }

    #[test]
    fn attempt_deposit_and_resolution_roundtrip() {
        use crate::attempt::{Attempt, AttemptDraft, AttemptResolution, ResolutionEvent};
        use ed25519_dalek::SigningKey;
        let key = SigningKey::from_bytes(&[7u8; 32]);
        let mut state = project::assemble("test", vec![], 0, 0, "test");

        let att = Attempt::build(
            AttemptDraft {
                problem: 309,
                kind: "lower_bound".into(),
                claim: "a(8) >= 33".to_string(),
                ..Default::default()
            },
            &key,
        )
        .unwrap();
        let dep = att.deposit_event("agent:opus", "agent", "bank attempt");
        apply_event(&mut state, &dep).unwrap();
        assert_eq!(state.attempts.len(), 1);
        assert_eq!(state.attempts[0].attempt_id, att.attempt_id);
        // Idempotent: re-applying the same deposit is a no-op.
        apply_event(&mut state, &dep).unwrap();
        assert_eq!(state.attempts.len(), 1);
        // No resolution yet -> still a candidate.
        assert!(state.head_resolution(&att.attempt_id).is_none());

        let res = ResolutionEvent::new(
            &att.attempt_id,
            AttemptResolution::Verified {
                gate_ref: "gate@vva_x".to_string(),
            },
            "reviewer:will-blair",
            "2026-06-09T00:00:00Z",
            "two independent methods",
        )
        .unwrap();
        apply_event(&mut state, &res.to_state_event("reviewer", "verified")).unwrap();
        assert_eq!(
            state
                .head_resolution(&att.attempt_id)
                .unwrap()
                .resolution
                .as_str(),
            "verified"
        );

        // A later refutation becomes the head (latest by `at`); history kept.
        let res2 = ResolutionEvent::new(
            &att.attempt_id,
            AttemptResolution::Refuted {
                by_probe: "case_b".to_string(),
            },
            "reviewer:skeptic",
            "2026-06-10T00:00:00Z",
            "Case B breaks it",
        )
        .unwrap();
        apply_event(&mut state, &res2.to_state_event("reviewer", "refuted")).unwrap();
        assert_eq!(
            state
                .head_resolution(&att.attempt_id)
                .unwrap()
                .resolution
                .as_str(),
            "refuted"
        );
        assert_eq!(state.attempt_resolutions.len(), 2);
    }

    #[test]
    fn forged_attempt_deposit_is_rejected_by_reducer() {
        use crate::attempt::{Attempt, AttemptDraft};
        use ed25519_dalek::SigningKey;
        let key = SigningKey::from_bytes(&[9u8; 32]);
        let mut state = project::assemble("test", vec![], 0, 0, "test");
        let att = Attempt::build(
            AttemptDraft {
                problem: 1,
                kind: "k".into(),
                claim: "c".to_string(),
                ..Default::default()
            },
            &key,
        )
        .unwrap();
        let mut dep = att.deposit_event("agent:opus", "agent", "x");
        // Hand-edit the embedded attempt: the signature no longer verifies.
        dep.payload["attempt"]["claim"] = serde_json::json!("tampered");
        assert!(apply_event(&mut state, &dep).is_err());
        assert_eq!(state.attempts.len(), 0);
    }
}