vela-protocol 0.102.0

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
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
//! Proposal-first frontier writes and proof freshness tracking.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};

use crate::bundle::{Annotation, Artifact, ConfidenceMethod, FindingBundle};
use crate::canonical;
use crate::events::{self, NULL_HASH, StateActor, StateEvent, StateTarget};
use crate::project::{self, Project};
use crate::propagate::{self, PropagationAction};
use crate::repo;

pub const PROPOSAL_SCHEMA: &str = "vela.proposal.v0.1";

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct StateProposal {
    #[serde(default = "default_schema")]
    pub schema: String,
    pub id: String,
    pub kind: String,
    pub target: StateTarget,
    pub actor: StateActor,
    pub created_at: String,
    /// v0.67: when an agent drafts a proposal long before the
    /// reviewer accepts it, `drafted_at` records the draft moment.
    /// `created_at` records the moment the proposal entered the
    /// canonical store. The throughput dashboard reads against
    /// `drafted_at` when present, falling back to `created_at`,
    /// so the "median proposal-to-event latency" surfaces real
    /// reviewer queue time rather than zero.
    /// Backward-compatible: pre-v0.67 proposals load with `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drafted_at: Option<String>,
    pub reason: String,
    #[serde(default)]
    pub payload: Value,
    #[serde(default)]
    pub source_refs: Vec<String>,
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reviewed_by: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reviewed_at: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decision_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub applied_event_id: Option<String>,
    #[serde(default)]
    pub caveats: Vec<String>,
    /// v0.22 (Agent Inbox): when a proposal originates from a scoped
    /// agent run (e.g. Literature Scout reading a PDF folder), this
    /// captures the model, the run id, and the wall-clock window.
    /// The substrate stays dumb — it does not know whether the
    /// proposer was a human, a Claude run, a GPT run, or a lab
    /// pipeline; this is informational provenance only, surfaced in
    /// the Workbench Inbox so reviewers can judge what they're
    /// looking at. Optional + skip-if-none so existing frontiers
    /// without proposals serialize byte-identically.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_run: Option<AgentRun>,
}

/// Agent provenance attached to a `StateProposal`.
///
/// Doctrine: the substrate stays model-agnostic. Agents — Literature
/// Scout, Notes Compiler, Code Analyst, etc. — sit in the
/// `vela-scientist` crate (or external code) and write proposals into
/// a frontier through the existing protocol. This struct is the
/// reviewer-facing record of *who proposed what, with what model,
/// during which run* — never used as access control or trust
/// assignment.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct AgentRun {
    /// Stable agent name (e.g. "literature-scout"). Pairs with the
    /// proposal's `actor.id == "agent:literature-scout"`.
    pub agent: String,
    /// Model identifier (e.g. "claude-sonnet-4-6"). Free-form so the
    /// substrate never has to enumerate model names.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub model: String,
    /// Run identifier — typically a UUID or short hash. Lets the
    /// reviewer group multiple proposals that came out of the same
    /// agent invocation.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub run_id: String,
    /// ISO-8601 wall-clock start of the run.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub started_at: String,
    /// ISO-8601 wall-clock end. Optional because some agents stream.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub finished_at: Option<String>,
    /// Free-form context the reviewer should see — e.g. the input
    /// folder path, the count of papers processed, the prompt
    /// version. Kept as a flat string map so it round-trips cleanly
    /// through canonical JSON without imposing a schema.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub context: BTreeMap<String, String>,
    /// v0.49: explicit tool-call traces from this run. Each entry
    /// records one tool invocation by content-addressable summary
    /// (tool name + input hash + output hash + duration). Lets a
    /// reviewer see what the agent actually called without bloating
    /// the bundle with raw payloads. Optional + skip-if-empty so
    /// existing frontiers round-trip byte-identically.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCallTrace>,
    /// v0.49: declared permission state for this run. Lists the
    /// data sources the agent had read access to and the tools it
    /// could invoke. Reviewers compare this declaration against
    /// `tool_calls` to spot drift. Optional + skip-if-empty so
    /// existing frontiers round-trip byte-identically.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub permissions: Option<PermissionState>,
}

/// One tool invocation made during an `AgentRun`. Stored as a
/// content-addressable summary, never the raw payload — keeps the
/// bundle bounded while preserving "did this happen, with what
/// inputs, returning what outputs" for reviewer audit. v0.49.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ToolCallTrace {
    /// Tool identifier (e.g. "pubmed_search", "arxiv_fetch", "compile").
    pub tool: String,
    /// SHA-256 hex of the canonical-JSON input. 64-char.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub input_sha256: String,
    /// SHA-256 hex of the canonical-JSON output. 64-char. Optional
    /// for tools whose output is opaque (a side effect, a navigation,
    /// etc.).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_sha256: Option<String>,
    /// ISO-8601 wall-clock start of the call.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub at: String,
    /// Wall-clock duration in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_ms: Option<u32>,
    /// Optional non-error status string (e.g. "ok", "rate_limited",
    /// "partial"). Kept free-form so a tool layer can emit whatever
    /// taxonomy it wants without protocol bumps.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub status: String,
    /// Optional human-readable error detail when `status` indicates a
    /// failure. Free-form so tool layers can carry a stack frame, an
    /// HTTP response body, or a one-line summary — whatever a
    /// reviewer needs to audit what went wrong without re-running the
    /// agent. Skipped when empty so successful calls round-trip
    /// byte-identically.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub error_message: String,
}

/// Declared permission boundary for an `AgentRun`. Lists what the
/// agent could read and which tools it could call. Reviewers can
/// diff this against `tool_calls` to spot scope creep. v0.49.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct PermissionState {
    /// Data sources the agent had read access to. Free-form URIs:
    /// `pubmed:`, `dataset:`, `frontier:vfr_…`, `path:./papers/…`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub data_access: Vec<String>,
    /// Tool identifiers the agent was allowed to call. Should be the
    /// allow-list `tool_calls[*].tool` is checked against by the
    /// runtime.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_access: Vec<String>,
    /// Optional human-readable note explaining the scope (e.g.
    /// "read-only access to BBB Flagship; can call pubmed search
    /// and arxiv fetch only"). Reviewer affordance only.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub note: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProposalSummary {
    pub total: usize,
    pub pending_review: usize,
    pub accepted: usize,
    pub rejected: usize,
    pub applied: usize,
    #[serde(default)]
    pub by_kind: BTreeMap<String, usize>,
    #[serde(default)]
    pub duplicate_ids: Vec<String>,
    #[serde(default)]
    pub invalid_targets: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProofState {
    #[serde(default)]
    pub latest_packet: ProofPacketState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_event_at_export: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stale_reason: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProofPacketState {
    pub generated_at: Option<String>,
    pub snapshot_hash: Option<String>,
    pub event_log_hash: Option<String>,
    pub packet_manifest_hash: Option<String>,
    pub status: String,
}

impl Default for ProofPacketState {
    fn default() -> Self {
        Self {
            generated_at: None,
            snapshot_hash: None,
            event_log_hash: None,
            packet_manifest_hash: None,
            status: "never_exported".to_string(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct CreateProposalResult {
    pub proposal_id: String,
    pub finding_id: String,
    pub status: String,
    pub applied_event_id: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct ImportProposalReport {
    pub imported: usize,
    pub applied: usize,
    pub rejected: usize,
    pub duplicates: usize,
    pub wrote_to: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProposalValidationReport {
    pub ok: bool,
    pub checked: usize,
    pub valid: usize,
    pub invalid: usize,
    #[serde(default)]
    pub errors: Vec<String>,
    #[serde(default)]
    pub proposal_ids: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ProposalPreview {
    pub proposal_id: String,
    pub kind: String,
    pub target: StateTarget,
    pub reviewer: String,
    #[serde(default)]
    pub changed_findings: Vec<String>,
    #[serde(default)]
    pub changed_artifacts: Vec<String>,
    #[serde(default)]
    pub new_event_ids: Vec<String>,
    #[serde(default)]
    pub event_kinds: Vec<String>,
    pub findings_before: usize,
    pub findings_after: usize,
    pub findings_delta: isize,
    pub artifacts_before: usize,
    pub artifacts_after: usize,
    pub artifacts_delta: isize,
    pub events_before: usize,
    pub events_after: usize,
    pub events_delta: isize,
    pub proof_would_be_stale: bool,
    pub applied_event_id: String,
}

#[derive(Debug, Clone)]
pub struct ProofPacketRecord {
    pub generated_at: String,
    pub snapshot_hash: String,
    pub event_log_hash: String,
    pub packet_manifest_hash: String,
}

fn default_schema() -> String {
    PROPOSAL_SCHEMA.to_string()
}

#[allow(clippy::too_many_arguments)]
pub fn new_proposal(
    kind: impl Into<String>,
    target: StateTarget,
    actor_id: impl Into<String>,
    actor_type: impl Into<String>,
    reason: impl Into<String>,
    payload: Value,
    source_refs: Vec<String>,
    caveats: Vec<String>,
) -> StateProposal {
    let created_at = Utc::now().to_rfc3339();
    let mut proposal = StateProposal {
        schema: PROPOSAL_SCHEMA.to_string(),
        id: String::new(),
        kind: kind.into(),
        target,
        actor: StateActor {
            id: actor_id.into(),
            r#type: actor_type.into(),
        },
        created_at,
        drafted_at: None,
        reason: reason.into(),
        payload,
        source_refs,
        status: "pending_review".to_string(),
        reviewed_by: None,
        reviewed_at: None,
        decision_reason: None,
        applied_event_id: None,
        caveats,
        agent_run: None,
    };
    proposal.id = proposal_id(&proposal);
    proposal
}

/// Phase P (v0.5): `vpr_…` is content-addressed over the *logical* proposal
/// content only — `created_at` is excluded from the preimage. Identical
/// logical proposals (same actor, target, kind, reason, payload) deterministically
/// produce the same proposal_id regardless of when they were constructed.
///
/// This is the substrate property that makes agent retries idempotent.
/// `created_at` stays on the proposal as non-canonical metadata; replay-attack
/// detection layers on the signed envelope, not the content hash.
pub fn proposal_id(proposal: &StateProposal) -> String {
    let preimage = json!({
        "schema": proposal.schema,
        "kind": proposal.kind,
        "target": proposal.target,
        "actor": proposal.actor,
        "reason": proposal.reason,
        "payload": proposal.payload,
        "source_refs": proposal.source_refs,
        "caveats": proposal.caveats,
    });
    let bytes = canonical::to_canonical_bytes(&preimage).unwrap_or_default();
    format!("vpr_{}", &hex::encode(Sha256::digest(bytes))[..16])
}

pub fn is_placeholder_reviewer(value: &str) -> bool {
    let normalized = value.trim().to_ascii_lowercase();
    normalized.is_empty()
        || normalized == "local-reviewer"
        || normalized == "local-user"
        || normalized == "reviewer"
        || normalized == "user"
        || normalized == "unknown"
        || normalized.starts_with("local-")
}

pub fn validate_reviewer_identity(value: &str) -> Result<(), String> {
    if is_placeholder_reviewer(value) {
        return Err(format!(
            "Reviewer identity '{}' is missing or placeholder. Use a stable named reviewer id.",
            value
        ));
    }
    Ok(())
}

pub fn summary(frontier: &Project) -> ProposalSummary {
    let mut out = ProposalSummary::default();
    let mut seen = BTreeSet::new();
    let finding_ids = frontier
        .findings
        .iter()
        .map(|finding| finding.id.as_str())
        .collect::<BTreeSet<_>>();
    let artifact_ids = frontier
        .artifacts
        .iter()
        .map(|artifact| artifact.id.as_str())
        .collect::<BTreeSet<_>>();
    for proposal in &frontier.proposals {
        out.total += 1;
        *out.by_kind.entry(proposal.kind.clone()).or_default() += 1;
        match proposal.status.as_str() {
            "pending_review" => out.pending_review += 1,
            "accepted" => out.accepted += 1,
            "rejected" => out.rejected += 1,
            "applied" => out.applied += 1,
            _ => {}
        }
        if !seen.insert(proposal.id.clone()) {
            out.duplicate_ids.push(proposal.id.clone());
        }
        let target_known = match proposal.target.r#type.as_str() {
            "finding" => {
                proposal.kind == "finding.add" || finding_ids.contains(proposal.target.id.as_str())
            }
            "artifact" => {
                proposal.kind == "artifact.assert"
                    || artifact_ids.contains(proposal.target.id.as_str())
            }
            _ => true,
        };
        if !target_known {
            out.invalid_targets.push(proposal.target.id.clone());
        }
    }
    out.duplicate_ids.sort();
    out.duplicate_ids.dedup();
    out.invalid_targets.sort();
    out.invalid_targets.dedup();
    out
}

pub fn proposals_for_finding<'a>(
    frontier: &'a Project,
    finding_id: &str,
) -> Vec<&'a StateProposal> {
    frontier
        .proposals
        .iter()
        .filter(|proposal| proposal.target.r#type == "finding" && proposal.target.id == finding_id)
        .collect()
}

/// Phase P (v0.5): upsert by content address. If a proposal with the same
/// `vpr_…` already exists in the frontier, return the existing record instead
/// of inserting a duplicate. Combined with the `created_at`-free preimage,
/// this makes agent retries idempotent at the substrate level.
///
/// `apply` semantics are also idempotent: if the same proposal+reviewer pair
/// has already been applied (proposal.applied_event_id is set), return the
/// existing event_id rather than emitting a duplicate canonical event.
pub fn create_or_apply(
    path: &Path,
    proposal: StateProposal,
    apply: bool,
) -> Result<CreateProposalResult, String> {
    let mut frontier = repo::load_from_path(path)?;
    let finding_id = proposal.target.id.clone();
    let proposal_id = proposal.id.clone();

    // Idempotent insert: if a proposal with this content-addressed id already
    // exists, skip insertion and treat the existing record as authoritative.
    let existing_idx = frontier
        .proposals
        .iter()
        .position(|existing| existing.id == proposal_id);
    if existing_idx.is_none() {
        validate_new_proposal(&frontier, &proposal)?;
        frontier.proposals.push(proposal);
    }

    let applied_event_id = if apply {
        // Idempotent apply: if the existing record was already applied, return
        // its event_id rather than emitting a duplicate event.
        if let Some(idx) = existing_idx
            && let Some(existing_event) = frontier.proposals[idx].applied_event_id.clone()
        {
            Some(existing_event)
        } else {
            let reviewer = frontier
                .proposals
                .iter()
                .find(|proposal| proposal.id == proposal_id)
                .map(|proposal| proposal.actor.id.clone())
                .ok_or_else(|| format!("Proposal not found after insertion: {proposal_id}"))?;
            Some(accept_proposal_in_frontier(
                &mut frontier,
                &proposal_id,
                &reviewer,
                "Applied locally from proposal creation",
            )?)
        }
    } else {
        existing_idx.and_then(|idx| frontier.proposals[idx].applied_event_id.clone())
    };

    // v0.13: materialize source/evidence/condition projections after every
    // applied proposal so the lint surface stops emitting `missing_source_record`
    // for findings whose provenance derives a SourceRecord that wasn't yet in
    // `frontier.sources`. Pre-v0.13, `vela normalize --write` was the only path
    // to populate these — but normalize refuses on event-ful frontiers, so any
    // frontier built via CLI proposals could never reach proof-ready state.
    // Materializing inline at apply time keeps source_records in lockstep with
    // findings; when no finding state changed (caveat/note/review on existing
    // findings) the projection is idempotent and bytes don't churn.
    if applied_event_id.is_some() {
        crate::sources::materialize_project(&mut frontier);
    } else {
        project::recompute_stats(&mut frontier);
    }
    repo::save_to_path(path, &frontier)?;
    Ok(CreateProposalResult {
        proposal_id,
        finding_id,
        status: applied_event_id
            .as_ref()
            .map_or_else(|| "pending_review".to_string(), |_| "applied".to_string()),
        applied_event_id,
    })
}

pub fn list(frontier: &Project, status: Option<&str>) -> Vec<StateProposal> {
    let mut proposals = frontier
        .proposals
        .iter()
        .filter(|proposal| status.is_none_or(|wanted| proposal.status == wanted))
        .cloned()
        .collect::<Vec<_>>();
    proposals.sort_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
    proposals
}

pub fn show<'a>(frontier: &'a Project, proposal_id: &str) -> Result<&'a StateProposal, String> {
    frontier
        .proposals
        .iter()
        .find(|proposal| proposal.id == proposal_id)
        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))
}

pub fn preview_at_path(
    path: &Path,
    proposal_id: &str,
    reviewer: &str,
) -> Result<ProposalPreview, String> {
    validate_reviewer_identity(reviewer)?;
    let frontier = repo::load_from_path(path)?;
    preview_in_frontier(&frontier, proposal_id, reviewer)
}

pub fn preview_in_frontier(
    frontier: &Project,
    proposal_id: &str,
    reviewer: &str,
) -> Result<ProposalPreview, String> {
    validate_reviewer_identity(reviewer)?;
    let proposal = frontier
        .proposals
        .iter()
        .find(|proposal| proposal.id == proposal_id)
        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?
        .clone();
    if proposal.status == "applied" {
        let applied_event_id = proposal
            .applied_event_id
            .clone()
            .ok_or_else(|| format!("Proposal {} is applied but has no event id", proposal.id))?;
        return Ok(ProposalPreview {
            proposal_id: proposal.id,
            kind: proposal.kind,
            changed_findings: changed_targets_for_type(frontier, &proposal.target, "finding"),
            changed_artifacts: changed_targets_for_type(frontier, &proposal.target, "artifact"),
            new_event_ids: vec![applied_event_id.clone()],
            event_kinds: frontier
                .events
                .iter()
                .find(|event| event.id == applied_event_id)
                .map(|event| vec![event.kind.clone()])
                .unwrap_or_default(),
            target: proposal.target,
            reviewer: reviewer.to_string(),
            findings_before: frontier.findings.len(),
            findings_after: frontier.findings.len(),
            findings_delta: 0,
            artifacts_before: frontier.artifacts.len(),
            artifacts_after: frontier.artifacts.len(),
            artifacts_delta: 0,
            events_before: frontier.events.len(),
            events_after: frontier.events.len(),
            events_delta: 0,
            proof_would_be_stale: false,
            applied_event_id,
        });
    }
    if !matches!(proposal.status.as_str(), "pending_review" | "accepted") {
        return Err(format!(
            "Proposal {} cannot be previewed from status {}",
            proposal.id, proposal.status
        ));
    }
    let mut preview_state: Project = serde_json::from_value(
        serde_json::to_value(frontier).map_err(|e| format!("serialize frontier preview: {e}"))?,
    )
    .map_err(|e| format!("clone frontier preview: {e}"))?;
    let finding_ids_before = preview_state
        .findings
        .iter()
        .map(|finding| finding.id.clone())
        .collect::<BTreeSet<_>>();
    let artifact_ids_before = preview_state
        .artifacts
        .iter()
        .map(|artifact| artifact.id.clone())
        .collect::<BTreeSet<_>>();
    let findings_before = preview_state.findings.len();
    let artifacts_before = preview_state.artifacts.len();
    let events_before = preview_state.events.len();
    let event_id = apply_proposal(
        &mut preview_state,
        &proposal,
        reviewer,
        "Preview proposal application",
    )?;
    let findings_after = preview_state.findings.len();
    let artifacts_after = preview_state.artifacts.len();
    let events_after = preview_state.events.len();
    let new_events = preview_state
        .events
        .iter()
        .skip(events_before)
        .cloned()
        .collect::<Vec<_>>();
    Ok(ProposalPreview {
        proposal_id: proposal.id,
        kind: proposal.kind,
        target: proposal.target,
        reviewer: reviewer.to_string(),
        changed_findings: changed_finding_ids(&preview_state, &finding_ids_before, &new_events),
        changed_artifacts: changed_artifact_ids(&preview_state, &artifact_ids_before, &new_events),
        new_event_ids: new_events.iter().map(|event| event.id.clone()).collect(),
        event_kinds: new_events.iter().map(|event| event.kind.clone()).collect(),
        findings_before,
        findings_after,
        findings_delta: findings_after as isize - findings_before as isize,
        artifacts_before,
        artifacts_after,
        artifacts_delta: artifacts_after as isize - artifacts_before as isize,
        events_before,
        events_after,
        events_delta: events_after as isize - events_before as isize,
        proof_would_be_stale: true,
        applied_event_id: event_id,
    })
}

fn changed_targets_for_type(
    frontier: &Project,
    target: &StateTarget,
    target_type: &str,
) -> Vec<String> {
    let known = match target_type {
        "finding" => frontier
            .findings
            .iter()
            .any(|finding| finding.id == target.id),
        "artifact" => frontier
            .artifacts
            .iter()
            .any(|artifact| artifact.id == target.id),
        _ => false,
    };
    if target.r#type == target_type && known {
        vec![target.id.clone()]
    } else {
        Vec::new()
    }
}

fn changed_finding_ids(
    preview_state: &Project,
    finding_ids_before: &BTreeSet<String>,
    new_events: &[StateEvent],
) -> Vec<String> {
    let mut ids = preview_state
        .findings
        .iter()
        .filter(|finding| !finding_ids_before.contains(&finding.id))
        .map(|finding| finding.id.clone())
        .collect::<BTreeSet<_>>();
    for event in new_events {
        if event.target.r#type == "finding" {
            ids.insert(event.target.id.clone());
        }
    }
    ids.into_iter().collect()
}

fn changed_artifact_ids(
    preview_state: &Project,
    artifact_ids_before: &BTreeSet<String>,
    new_events: &[StateEvent],
) -> Vec<String> {
    let mut ids = preview_state
        .artifacts
        .iter()
        .filter(|artifact| !artifact_ids_before.contains(&artifact.id))
        .map(|artifact| artifact.id.clone())
        .collect::<BTreeSet<_>>();
    for event in new_events {
        if event.target.r#type == "artifact" {
            ids.insert(event.target.id.clone());
        }
    }
    ids.into_iter().collect()
}

pub fn import_from_path(path: &Path, source: &Path) -> Result<ImportProposalReport, String> {
    let mut frontier = repo::load_from_path(path)?;
    let proposals = load_proposals(source)?;
    let wrote_to = path.display().to_string();
    let mut report = ImportProposalReport {
        wrote_to,
        ..ImportProposalReport::default()
    };
    for proposal in proposals {
        if frontier
            .proposals
            .iter()
            .any(|existing| existing.id == proposal.id)
        {
            report.duplicates += 1;
            continue;
        }
        validate_new_proposal(&frontier, &proposal)?;
        frontier.proposals.push(proposal.clone());
        report.imported += 1;
        match proposal.status.as_str() {
            "accepted" => {
                let reviewer = proposal
                    .reviewed_by
                    .as_deref()
                    .ok_or_else(|| {
                        format!("Accepted proposal {} missing reviewed_by", proposal.id)
                    })?
                    .to_string();
                let reason = proposal
                    .decision_reason
                    .clone()
                    .unwrap_or_else(|| "Imported accepted proposal".to_string());
                let _ =
                    accept_proposal_in_frontier(&mut frontier, &proposal.id, &reviewer, &reason)?;
                report.applied += 1;
            }
            "applied" => {
                let reviewer = proposal
                    .reviewed_by
                    .as_deref()
                    .ok_or_else(|| format!("Applied proposal {} missing reviewed_by", proposal.id))?
                    .to_string();
                let reason = proposal
                    .decision_reason
                    .clone()
                    .unwrap_or_else(|| "Imported applied proposal".to_string());
                let _ =
                    accept_proposal_in_frontier(&mut frontier, &proposal.id, &reviewer, &reason)?;
                report.applied += 1;
            }
            "rejected" => report.rejected += 1,
            _ => {}
        }
    }
    project::recompute_stats(&mut frontier);
    repo::save_to_path(path, &frontier)?;
    Ok(report)
}

pub fn validate_source(source: &Path) -> Result<ProposalValidationReport, String> {
    let proposals = load_proposals(source)?;
    let mut report = ProposalValidationReport {
        checked: proposals.len(),
        ..ProposalValidationReport::default()
    };
    let scratch = project::assemble("proposal-validation", Vec::new(), 0, 0, "validate");
    let mut seen = BTreeSet::new();
    for proposal in proposals {
        if !seen.insert(proposal.id.clone()) {
            report.invalid += 1;
            report
                .errors
                .push(format!("Duplicate proposal id {}", proposal.id));
            continue;
        }
        report.proposal_ids.push(proposal.id.clone());
        match validate_standalone_proposal(&scratch, &proposal) {
            Ok(()) => report.valid += 1,
            Err(err) => {
                report.invalid += 1;
                report.errors.push(format!("{}: {}", proposal.id, err));
            }
        }
    }
    report.ok = report.invalid == 0;
    Ok(report)
}

pub fn export_to_path(
    frontier_path: &Path,
    output: &Path,
    status: Option<&str>,
) -> Result<usize, String> {
    let frontier = repo::load_from_path(frontier_path)?;
    let proposals = list(&frontier, status);
    let json = serde_json::to_string_pretty(&proposals)
        .map_err(|e| format!("Failed to serialize proposals for export: {e}"))?;
    std::fs::write(output, json).map_err(|e| {
        format!(
            "Failed to write proposal export '{}': {e}",
            output.display()
        )
    })?;
    Ok(proposals.len())
}

pub fn accept_at_path(
    path: &Path,
    proposal_id: &str,
    reviewer: &str,
    reason: &str,
) -> Result<String, String> {
    let mut frontier = repo::load_from_path(path)?;
    let event_id = accept_proposal_in_frontier(&mut frontier, proposal_id, reviewer, reason)?;
    project::recompute_stats(&mut frontier);
    repo::save_to_path(path, &frontier)?;
    Ok(event_id)
}

pub fn reject_at_path(
    path: &Path,
    proposal_id: &str,
    reviewer: &str,
    reason: &str,
) -> Result<(), String> {
    let mut frontier = repo::load_from_path(path)?;
    reject_proposal_in_frontier(&mut frontier, proposal_id, reviewer, reason)?;
    project::recompute_stats(&mut frontier);
    repo::save_to_path(path, &frontier)?;
    Ok(())
}

pub fn request_revision_at_path(
    path: &Path,
    proposal_id: &str,
    reviewer: &str,
    reason: &str,
) -> Result<(), String> {
    let mut frontier = repo::load_from_path(path)?;
    request_revision_in_frontier(&mut frontier, proposal_id, reviewer, reason)?;
    project::recompute_stats(&mut frontier);
    repo::save_to_path(path, &frontier)?;
    Ok(())
}

pub fn record_proof_export(frontier: &mut Project, record: ProofPacketRecord) {
    frontier.proof_state.latest_packet = ProofPacketState {
        generated_at: Some(record.generated_at),
        snapshot_hash: Some(record.snapshot_hash),
        event_log_hash: Some(record.event_log_hash),
        packet_manifest_hash: Some(record.packet_manifest_hash),
        status: "current".to_string(),
    };
    frontier.proof_state.last_event_at_export =
        frontier.events.last().map(|event| event.timestamp.clone());
    frontier.proof_state.stale_reason = None;
}

pub fn mark_proof_stale(frontier: &mut Project, reason: String) {
    if frontier.proof_state.latest_packet.status != "never_exported" {
        frontier.proof_state.latest_packet.status = "stale".to_string();
        frontier.proof_state.stale_reason = Some(reason);
    }
}

pub fn proof_state_json(proof_state: &ProofState) -> Value {
    serde_json::to_value(proof_state).unwrap_or_else(|_| json!({"status": "never_exported"}))
}

pub fn proposal_state_hash(proposals: &[StateProposal]) -> String {
    let bytes = canonical::to_canonical_bytes(proposals).unwrap_or_default();
    hex::encode(Sha256::digest(bytes))
}

fn load_proposals(source: &Path) -> Result<Vec<StateProposal>, String> {
    if source.is_file() {
        let data = std::fs::read_to_string(source)
            .map_err(|e| format!("Failed to read proposal file '{}': {e}", source.display()))?;
        if let Ok(proposals) = serde_json::from_str::<Vec<StateProposal>>(&data) {
            return Ok(proposals);
        }
        let proposal = serde_json::from_str::<StateProposal>(&data)
            .map_err(|e| format!("Failed to parse proposal JSON '{}': {e}", source.display()))?;
        return Ok(vec![proposal]);
    }
    if source.is_dir() {
        let mut entries = std::fs::read_dir(source)
            .map_err(|e| format!("Failed to read proposal dir '{}': {e}", source.display()))?
            .filter_map(|entry| entry.ok().map(|entry| entry.path()))
            .filter(|path| path.extension().is_some_and(|ext| ext == "json"))
            .collect::<Vec<_>>();
        entries.sort();
        let mut proposals = Vec::new();
        for path in entries {
            proposals.extend(load_proposals(&path)?);
        }
        return Ok(proposals);
    }
    Err(format!(
        "Proposal source does not exist: {}",
        source.display()
    ))
}

fn validate_new_proposal(frontier: &Project, proposal: &StateProposal) -> Result<(), String> {
    if proposal.schema != PROPOSAL_SCHEMA {
        return Err(format!("Unsupported proposal schema '{}'", proposal.schema));
    }
    if frontier
        .proposals
        .iter()
        .any(|existing| existing.id == proposal.id)
    {
        return Err(format!("Duplicate proposal id {}", proposal.id));
    }
    validate_proposal_shape(frontier, proposal)?;
    validate_decision_state(proposal)
}

fn validate_proposal_shape(frontier: &Project, proposal: &StateProposal) -> Result<(), String> {
    // v0.52: relax the finding-only constraint so the agent inbox
    // can deposit nulls and trajectories through the same review-
    // gated flow as findings. The proposal-kind dispatch below
    // enforces that target.type matches the kind family.
    if !matches!(
        proposal.target.r#type.as_str(),
        "finding"
            | "artifact"
            | "negative_result"
            | "trajectory"
            | "evidence_atom"
            | "frontier_observation"
    ) {
        return Err(format!(
            "Unsupported proposal target type '{}'; valid: finding, artifact, negative_result, trajectory, evidence_atom, frontier_observation",
            proposal.target.r#type
        ));
    }
    if proposal.reason.trim().is_empty() {
        return Err("Proposal reason must be non-empty".to_string());
    }
    if !matches!(
        proposal.status.as_str(),
        "pending_review" | "accepted" | "rejected" | "applied"
    ) {
        return Err(format!("Unsupported proposal status '{}'", proposal.status));
    }
    match proposal.kind.as_str() {
        "finding.add" => {
            let finding_value = proposal
                .payload
                .get("finding")
                .ok_or("finding.add proposal missing payload.finding")?
                .clone();
            let finding: FindingBundle = serde_json::from_value(finding_value)
                .map_err(|e| format!("Invalid finding.add payload: {e}"))?;
            if finding.id != proposal.target.id {
                return Err(format!(
                    "finding.add target {} does not match payload finding {}",
                    proposal.target.id, finding.id
                ));
            }
            if frontier
                .findings
                .iter()
                .any(|existing| existing.id == proposal.target.id)
            {
                return Err(format!(
                    "Refusing to add duplicate finding with existing finding ID {}",
                    proposal.target.id
                ));
            }
        }
        "finding.review" => {
            require_existing_finding(frontier, &proposal.target.id)?;
            let status = proposal
                .payload
                .get("status")
                .and_then(Value::as_str)
                .ok_or("finding.review proposal missing payload.status")?;
            if !matches!(
                status,
                "accepted" | "approved" | "contested" | "needs_revision" | "rejected"
            ) {
                return Err(format!("Unsupported review proposal status '{status}'"));
            }
        }
        "finding.caveat" => {
            require_existing_finding(frontier, &proposal.target.id)?;
            let text = proposal
                .payload
                .get("text")
                .and_then(Value::as_str)
                .ok_or("finding.caveat proposal missing payload.text")?;
            if text.trim().is_empty() {
                return Err("finding.caveat payload.text must be non-empty".to_string());
            }
        }
        "finding.note" => {
            require_existing_finding(frontier, &proposal.target.id)?;
            let text = proposal
                .payload
                .get("text")
                .and_then(Value::as_str)
                .ok_or("finding.note proposal missing payload.text")?;
            if text.trim().is_empty() {
                return Err("finding.note payload.text must be non-empty".to_string());
            }
        }
        "finding.confidence_revise" => {
            require_existing_finding(frontier, &proposal.target.id)?;
            let score = proposal
                .payload
                .get("confidence")
                .and_then(Value::as_f64)
                .ok_or("finding.confidence_revise proposal missing payload.confidence")?;
            if !(0.0..=1.0).contains(&score) {
                return Err(
                    "finding.confidence_revise confidence must be between 0.0 and 1.0".to_string(),
                );
            }
        }
        "finding.reject" => {
            require_existing_finding(frontier, &proposal.target.id)?;
        }
        "finding.retract" => {
            let idx = require_existing_finding(frontier, &proposal.target.id)?;
            if frontier.findings[idx].flags.retracted {
                return Err(format!(
                    "Finding {} is already retracted",
                    proposal.target.id
                ));
            }
        }
        "finding.supersede" => {
            let idx = require_existing_finding(frontier, &proposal.target.id)?;
            if frontier.findings[idx].flags.superseded {
                return Err(format!(
                    "Finding {} is already superseded",
                    proposal.target.id
                ));
            }
            let new_finding_value = proposal
                .payload
                .get("new_finding")
                .ok_or("finding.supersede proposal missing payload.new_finding")?
                .clone();
            let new_finding: FindingBundle = serde_json::from_value(new_finding_value)
                .map_err(|e| format!("Invalid finding.supersede payload.new_finding: {e}"))?;
            if new_finding.id == proposal.target.id {
                return Err(
                    "finding.supersede new_finding has same content address as the superseded target — change assertion text, type, or provenance to derive a distinct vf_…".to_string(),
                );
            }
            if frontier
                .findings
                .iter()
                .any(|existing| existing.id == new_finding.id)
            {
                return Err(format!(
                    "Refusing to add superseding finding with existing finding ID {}",
                    new_finding.id
                ));
            }
        }
        "artifact.assert" => {
            if proposal.target.r#type != "artifact" {
                return Err(format!(
                    "artifact.assert proposal target.type must be 'artifact', got '{}'",
                    proposal.target.r#type
                ));
            }
            let artifact_value = proposal
                .payload
                .get("artifact")
                .ok_or("artifact.assert proposal missing payload.artifact")?
                .clone();
            let artifact: Artifact = serde_json::from_value(artifact_value)
                .map_err(|e| format!("Invalid artifact.assert payload: {e}"))?;
            if artifact.id != proposal.target.id {
                return Err(format!(
                    "artifact.assert target {} does not match payload id {}",
                    proposal.target.id, artifact.id
                ));
            }
            if frontier.artifacts.iter().any(|a| a.id == artifact.id) {
                return Err(format!(
                    "Refusing to add duplicate artifact with existing id {}",
                    artifact.id
                ));
            }
        }
        // v0.52: NegativeResult deposit through the proposals
        // pipeline. Mirrors finding.add: payload.negative_result
        // carries the inline NegativeResult struct; target.id is the
        // resulting vnr_*. Validators here are the proposal-side
        // shape check; the canonical event validator in events.rs
        // re-checks at event-emit time.
        "negative_result.assert" => {
            if proposal.target.r#type != "negative_result" {
                return Err(format!(
                    "negative_result.assert proposal target.type must be 'negative_result', got '{}'",
                    proposal.target.r#type
                ));
            }
            let nr_value = proposal
                .payload
                .get("negative_result")
                .ok_or("negative_result.assert proposal missing payload.negative_result")?
                .clone();
            let nr: crate::bundle::NegativeResult = serde_json::from_value(nr_value)
                .map_err(|e| format!("Invalid negative_result.assert payload: {e}"))?;
            if nr.id != proposal.target.id {
                return Err(format!(
                    "negative_result.assert target {} does not match payload id {}",
                    proposal.target.id, nr.id
                ));
            }
            if frontier.negative_results.iter().any(|n| n.id == nr.id) {
                return Err(format!(
                    "Refusing to add duplicate negative_result with existing id {}",
                    nr.id
                ));
            }
        }
        // v0.52: Trajectory deposit through the proposals pipeline.
        // payload.trajectory carries the inline Trajectory (with
        // empty steps); steps land later via separate
        // `trajectory.step_append` proposals.
        "trajectory.create" => {
            if proposal.target.r#type != "trajectory" {
                return Err(format!(
                    "trajectory.create proposal target.type must be 'trajectory', got '{}'",
                    proposal.target.r#type
                ));
            }
            let traj_value = proposal
                .payload
                .get("trajectory")
                .ok_or("trajectory.create proposal missing payload.trajectory")?
                .clone();
            let traj: crate::bundle::Trajectory = serde_json::from_value(traj_value)
                .map_err(|e| format!("Invalid trajectory.create payload: {e}"))?;
            if traj.id != proposal.target.id {
                return Err(format!(
                    "trajectory.create target {} does not match payload id {}",
                    proposal.target.id, traj.id
                ));
            }
            if frontier.trajectories.iter().any(|t| t.id == traj.id) {
                return Err(format!(
                    "Refusing to add duplicate trajectory with existing id {}",
                    traj.id
                ));
            }
        }
        // v0.57: Mechanical finding-level span repair. Appends a
        // `{section, text}` span to the finding's evidence_spans.
        "finding.span_repair" => {
            if proposal.target.r#type != "finding" {
                return Err(format!(
                    "finding.span_repair target.type must be 'finding', got '{}'",
                    proposal.target.r#type
                ));
            }
            require_existing_finding(frontier, &proposal.target.id)?;
            let section = proposal
                .payload
                .get("section")
                .and_then(Value::as_str)
                .ok_or("finding.span_repair proposal missing payload.section")?;
            if section.trim().is_empty() {
                return Err("finding.span_repair payload.section must be non-empty".to_string());
            }
            let text = proposal
                .payload
                .get("text")
                .and_then(Value::as_str)
                .ok_or("finding.span_repair proposal missing payload.text")?;
            if text.trim().is_empty() {
                return Err("finding.span_repair payload.text must be non-empty".to_string());
            }
        }
        // v0.57: Entity resolution on a single named entity inside a
        // finding's assertion.entities. Sets canonical_id and
        // resolution metadata; clears needs_review.
        "finding.entity_resolve" => {
            if proposal.target.r#type != "finding" {
                return Err(format!(
                    "finding.entity_resolve target.type must be 'finding', got '{}'",
                    proposal.target.r#type
                ));
            }
            let f_idx = require_existing_finding(frontier, &proposal.target.id)?;
            let entity_name = proposal
                .payload
                .get("entity_name")
                .and_then(Value::as_str)
                .ok_or("finding.entity_resolve proposal missing payload.entity_name")?;
            if entity_name.trim().is_empty() {
                return Err(
                    "finding.entity_resolve payload.entity_name must be non-empty".to_string(),
                );
            }
            let _e_idx = frontier.findings[f_idx]
                .assertion
                .entities
                .iter()
                .position(|e| e.name == entity_name)
                .ok_or_else(|| {
                    format!(
                        "finding.entity_resolve entity_name '{entity_name}' not in finding {}",
                        proposal.target.id
                    )
                })?;
            let source = proposal
                .payload
                .get("source")
                .and_then(Value::as_str)
                .ok_or("finding.entity_resolve proposal missing payload.source")?;
            if source.trim().is_empty() {
                return Err("finding.entity_resolve payload.source must be non-empty".to_string());
            }
            let id = proposal
                .payload
                .get("id")
                .and_then(Value::as_str)
                .ok_or("finding.entity_resolve proposal missing payload.id")?;
            if id.trim().is_empty() {
                return Err("finding.entity_resolve payload.id must be non-empty".to_string());
            }
            let confidence = proposal
                .payload
                .get("confidence")
                .and_then(Value::as_f64)
                .ok_or("finding.entity_resolve proposal missing payload.confidence")?;
            if !(0.0..=1.0).contains(&confidence) {
                return Err(format!(
                    "finding.entity_resolve confidence {confidence} out of [0.0, 1.0]"
                ));
            }
        }
        // v0.79: Append a new entity tag to an existing finding.
        // Closes the v0.78.4 honest gap where reviewers had to
        // append new findings to add tags. Required payload:
        // {entity_name, entity_type, reason}; the proposal validates
        // that the target finding exists. The reducer's apply is
        // idempotent on (finding_id, entity_name): re-applying with
        // the same name + type is a no-op.
        "finding.entity_add" => {
            if proposal.target.r#type != "finding" {
                return Err(format!(
                    "finding.entity_add target.type must be 'finding', got '{}'",
                    proposal.target.r#type
                ));
            }
            let _f_idx = require_existing_finding(frontier, &proposal.target.id)?;
            let entity_name = proposal
                .payload
                .get("entity_name")
                .and_then(Value::as_str)
                .ok_or("finding.entity_add proposal missing payload.entity_name")?;
            if entity_name.trim().is_empty() {
                return Err("finding.entity_add payload.entity_name must be non-empty".to_string());
            }
            let entity_type = proposal
                .payload
                .get("entity_type")
                .and_then(Value::as_str)
                .ok_or("finding.entity_add proposal missing payload.entity_type")?;
            const VALID_ENTITY_TYPES: &[&str] = &[
                "gene",
                "protein",
                "compound",
                "disease",
                "cell_type",
                "organism",
                "pathway",
                "assay",
                "anatomical_structure",
                "particle",
                "instrument",
                "dataset",
                "quantity",
                "other",
            ];
            if !VALID_ENTITY_TYPES.contains(&entity_type) {
                return Err(format!(
                    "finding.entity_add payload.entity_type '{entity_type}' not in {VALID_ENTITY_TYPES:?}"
                ));
            }
            let reason_text = proposal
                .payload
                .get("reason")
                .and_then(Value::as_str)
                .ok_or("finding.entity_add proposal missing payload.reason")?;
            if reason_text.trim().is_empty() {
                return Err("finding.entity_add payload.reason must be non-empty".to_string());
            }
        }
        // v0.56: Mechanical evidence-atom locator repair. Targets one
        // evidence atom by id; payload carries the resolved locator
        // string and the parent source id it was derived from. The
        // proposal is mechanical: the locator is already present on
        // `frontier.sources[atom.source_id].locator`. Reviewer accepts
        // (or auto-accepts) and the canonical event lands the locator
        // on the atom while preserving the derivation in the payload.
        "evidence_atom.locator_repair" => {
            if proposal.target.r#type != "evidence_atom" {
                return Err(format!(
                    "evidence_atom.locator_repair target.type must be 'evidence_atom', got '{}'",
                    proposal.target.r#type
                ));
            }
            let atom_id = proposal.target.id.as_str();
            let atom = frontier
                .evidence_atoms
                .iter()
                .find(|atom| atom.id == atom_id)
                .ok_or_else(|| {
                    format!("evidence_atom.locator_repair targets unknown atom {atom_id}")
                })?;
            let locator = proposal
                .payload
                .get("locator")
                .and_then(Value::as_str)
                .ok_or("evidence_atom.locator_repair proposal missing payload.locator")?;
            if locator.trim().is_empty() {
                return Err(
                    "evidence_atom.locator_repair payload.locator must be non-empty".to_string(),
                );
            }
            let source_id = proposal
                .payload
                .get("source_id")
                .and_then(Value::as_str)
                .ok_or("evidence_atom.locator_repair proposal missing payload.source_id")?;
            if source_id.trim().is_empty() {
                return Err(
                    "evidence_atom.locator_repair payload.source_id must be non-empty".to_string(),
                );
            }
            if atom.source_id != source_id {
                return Err(format!(
                    "evidence_atom.locator_repair payload.source_id '{source_id}' does not match atom.source_id '{}'",
                    atom.source_id
                ));
            }
            // Refuse a no-op repair so the curation pipeline doesn't
            // emit empty events. An atom that already carries the same
            // locator should be filtered upstream.
            if let Some(existing) = &atom.locator
                && existing == locator
            {
                return Err(format!(
                    "evidence_atom {atom_id} already carries locator '{existing}'"
                ));
            }
            // Refuse a divergent overwrite. A different existing
            // locator is a chain-integrity issue, not a repair.
            if let Some(existing) = &atom.locator
                && existing != locator
            {
                return Err(format!(
                    "evidence_atom {atom_id} already carries locator '{existing}'; refusing to overwrite with '{locator}'"
                ));
            }
        }
        // v0.52: Append a step to an existing Trajectory through the
        // proposals pipeline. target.id is the parent vtr_*; payload
        // carries the inline TrajectoryStep.
        "trajectory.step_append" => {
            if proposal.target.r#type != "trajectory" {
                return Err(format!(
                    "trajectory.step_append proposal target.type must be 'trajectory', got '{}'",
                    proposal.target.r#type
                ));
            }
            let parent_id = proposal.target.id.as_str();
            let parent_idx = frontier
                .trajectories
                .iter()
                .position(|t| t.id == parent_id)
                .ok_or_else(|| {
                    format!("trajectory.step_append targets unknown trajectory {parent_id}")
                })?;
            let step_value = proposal
                .payload
                .get("step")
                .ok_or("trajectory.step_append proposal missing payload.step")?
                .clone();
            let step: crate::bundle::TrajectoryStep = serde_json::from_value(step_value)
                .map_err(|e| format!("Invalid trajectory.step_append payload.step: {e}"))?;
            if frontier.trajectories[parent_idx]
                .steps
                .iter()
                .any(|s| s.id == step.id)
            {
                return Err(format!(
                    "Refusing to add duplicate step with existing id {} on trajectory {}",
                    step.id, parent_id
                ));
            }
        }
        // v0.59: federation conflict resolution. Reviewer-driven
        // verdict on a previously emitted `frontier.conflict_detected`
        // event. The conflict event itself is not modified; this
        // proposal records the resolution as a paired event.
        "frontier.conflict_resolve" => {
            if proposal.target.r#type != "frontier_observation" {
                return Err(format!(
                    "frontier.conflict_resolve target.type must be 'frontier_observation', got '{}'",
                    proposal.target.r#type
                ));
            }
            let conflict_event_id = proposal
                .payload
                .get("conflict_event_id")
                .and_then(Value::as_str)
                .ok_or("frontier.conflict_resolve proposal missing payload.conflict_event_id")?;
            if conflict_event_id.trim().is_empty() {
                return Err(
                    "frontier.conflict_resolve payload.conflict_event_id must be non-empty"
                        .to_string(),
                );
            }
            // The named conflict event must actually be present on
            // this frontier. A reviewer can't resolve a conflict that
            // hasn't been detected.
            let conflict_event = frontier
                .events
                .iter()
                .find(|e| e.id == conflict_event_id)
                .ok_or_else(|| {
                    format!(
                        "frontier.conflict_resolve targets unknown event id '{conflict_event_id}'"
                    )
                })?;
            if conflict_event.kind != "frontier.conflict_detected" {
                return Err(format!(
                    "frontier.conflict_resolve target event '{conflict_event_id}' has kind '{}', expected 'frontier.conflict_detected'",
                    conflict_event.kind
                ));
            }
            // Refuse double-resolution: if a `frontier.conflict_resolved`
            // event already exists pointing at this conflict_event_id,
            // there's nothing to resolve.
            if frontier.events.iter().any(|e| {
                e.kind == "frontier.conflict_resolved"
                    && e.payload.get("conflict_event_id").and_then(Value::as_str)
                        == Some(conflict_event_id)
            }) {
                return Err(format!(
                    "Conflict event '{conflict_event_id}' already has a recorded resolution"
                ));
            }
            let note = proposal
                .payload
                .get("resolution_note")
                .and_then(Value::as_str)
                .ok_or("frontier.conflict_resolve proposal missing payload.resolution_note")?;
            if note.trim().is_empty() {
                return Err(
                    "frontier.conflict_resolve payload.resolution_note must be non-empty"
                        .to_string(),
                );
            }
            // winning_proposal_id is optional; some conflicts resolve
            // by reviewer judgment without picking a specific proposal.
            if let Some(value) = proposal.payload.get("winning_proposal_id")
                && !value.is_null()
                && value.as_str().is_none()
            {
                return Err(
                    "frontier.conflict_resolve payload.winning_proposal_id must be a string when present"
                        .to_string(),
                );
            }
        }
        other => {
            return Err(format!("Unsupported proposal kind '{other}'"));
        }
    }
    Ok(())
}

fn validate_decision_state(proposal: &StateProposal) -> Result<(), String> {
    match proposal.status.as_str() {
        "pending_review" => Ok(()),
        "accepted" | "applied" | "rejected" => {
            let reviewer = proposal
                .reviewed_by
                .as_deref()
                .ok_or_else(|| format!("Proposal {} missing reviewed_by", proposal.id))?;
            validate_reviewer_identity(reviewer)?;
            if proposal
                .decision_reason
                .as_deref()
                .is_none_or(|reason| reason.trim().is_empty())
            {
                return Err(format!("Proposal {} missing decision_reason", proposal.id));
            }
            if proposal.status == "applied" && proposal.applied_event_id.is_none() {
                return Err(format!(
                    "Applied proposal {} missing applied_event_id",
                    proposal.id
                ));
            }
            Ok(())
        }
        other => Err(format!("Unsupported proposal status '{}'", other)),
    }
}

fn validate_standalone_proposal(
    _frontier: &Project,
    proposal: &StateProposal,
) -> Result<(), String> {
    if proposal.schema != PROPOSAL_SCHEMA {
        return Err(format!("Unsupported proposal schema '{}'", proposal.schema));
    }
    if !matches!(
        proposal.target.r#type.as_str(),
        "finding" | "evidence_atom" | "frontier_observation"
    ) {
        return Err(
            "Only finding, evidence_atom, and frontier_observation proposals are supported in v0"
                .to_string(),
        );
    }
    if proposal.reason.trim().is_empty() {
        return Err("Proposal reason must be non-empty".to_string());
    }
    match proposal.kind.as_str() {
        "finding.add" => {
            let finding_value = proposal
                .payload
                .get("finding")
                .ok_or("finding.add proposal missing payload.finding")?
                .clone();
            let finding: FindingBundle = serde_json::from_value(finding_value)
                .map_err(|e| format!("Invalid finding.add payload: {e}"))?;
            if finding.id != proposal.target.id {
                return Err(format!(
                    "finding.add target {} does not match payload finding {}",
                    proposal.target.id, finding.id
                ));
            }
        }
        "finding.review" => {
            let status = proposal
                .payload
                .get("status")
                .and_then(Value::as_str)
                .ok_or("finding.review proposal missing payload.status")?;
            if !matches!(
                status,
                "accepted" | "approved" | "contested" | "needs_revision" | "rejected"
            ) {
                return Err(format!("Unsupported review proposal status '{status}'"));
            }
        }
        "finding.caveat" => {
            let text = proposal
                .payload
                .get("text")
                .and_then(Value::as_str)
                .ok_or("finding.caveat proposal missing payload.text")?;
            if text.trim().is_empty() {
                return Err("finding.caveat payload.text must be non-empty".to_string());
            }
        }
        "finding.note" => {
            let text = proposal
                .payload
                .get("text")
                .and_then(Value::as_str)
                .ok_or("finding.note proposal missing payload.text")?;
            if text.trim().is_empty() {
                return Err("finding.note payload.text must be non-empty".to_string());
            }
        }
        "finding.confidence_revise" => {
            let score = proposal
                .payload
                .get("confidence")
                .and_then(Value::as_f64)
                .ok_or("finding.confidence_revise proposal missing payload.confidence")?;
            if !(0.0..=1.0).contains(&score) {
                return Err(
                    "finding.confidence_revise confidence must be between 0.0 and 1.0".to_string(),
                );
            }
        }
        "finding.reject" | "finding.retract" => {}
        "finding.supersede" => {
            let new_finding_value = proposal
                .payload
                .get("new_finding")
                .ok_or("finding.supersede proposal missing payload.new_finding")?
                .clone();
            let new_finding: FindingBundle = serde_json::from_value(new_finding_value)
                .map_err(|e| format!("Invalid finding.supersede payload.new_finding: {e}"))?;
            if new_finding.id == proposal.target.id {
                return Err(
                    "finding.supersede new_finding has same content address as the superseded target"
                        .to_string(),
                );
            }
        }
        // v0.57: standalone validation of finding span-repair.
        "finding.span_repair" => {
            if proposal.target.r#type != "finding" {
                return Err(format!(
                    "finding.span_repair target.type must be 'finding', got '{}'",
                    proposal.target.r#type
                ));
            }
            let section = proposal
                .payload
                .get("section")
                .and_then(Value::as_str)
                .ok_or("finding.span_repair proposal missing payload.section")?;
            if section.trim().is_empty() {
                return Err("finding.span_repair payload.section must be non-empty".to_string());
            }
            let text = proposal
                .payload
                .get("text")
                .and_then(Value::as_str)
                .ok_or("finding.span_repair proposal missing payload.text")?;
            if text.trim().is_empty() {
                return Err("finding.span_repair payload.text must be non-empty".to_string());
            }
        }
        // v0.57: standalone validation of finding entity-resolve.
        "finding.entity_resolve" => {
            if proposal.target.r#type != "finding" {
                return Err(format!(
                    "finding.entity_resolve target.type must be 'finding', got '{}'",
                    proposal.target.r#type
                ));
            }
            let entity_name = proposal
                .payload
                .get("entity_name")
                .and_then(Value::as_str)
                .ok_or("finding.entity_resolve proposal missing payload.entity_name")?;
            if entity_name.trim().is_empty() {
                return Err(
                    "finding.entity_resolve payload.entity_name must be non-empty".to_string(),
                );
            }
            let source = proposal
                .payload
                .get("source")
                .and_then(Value::as_str)
                .ok_or("finding.entity_resolve proposal missing payload.source")?;
            if source.trim().is_empty() {
                return Err("finding.entity_resolve payload.source must be non-empty".to_string());
            }
            let id = proposal
                .payload
                .get("id")
                .and_then(Value::as_str)
                .ok_or("finding.entity_resolve proposal missing payload.id")?;
            if id.trim().is_empty() {
                return Err("finding.entity_resolve payload.id must be non-empty".to_string());
            }
            let confidence = proposal
                .payload
                .get("confidence")
                .and_then(Value::as_f64)
                .ok_or("finding.entity_resolve proposal missing payload.confidence")?;
            if !(0.0..=1.0).contains(&confidence) {
                return Err(format!(
                    "finding.entity_resolve confidence {confidence} out of [0.0, 1.0]"
                ));
            }
        }
        // v0.79: standalone validation of finding.entity_add. Same
        // payload shape as the contextual validator, sans
        // finding-existence check.
        "finding.entity_add" => {
            if proposal.target.r#type != "finding" {
                return Err(format!(
                    "finding.entity_add target.type must be 'finding', got '{}'",
                    proposal.target.r#type
                ));
            }
            let entity_name = proposal
                .payload
                .get("entity_name")
                .and_then(Value::as_str)
                .ok_or("finding.entity_add proposal missing payload.entity_name")?;
            if entity_name.trim().is_empty() {
                return Err("finding.entity_add payload.entity_name must be non-empty".to_string());
            }
            let entity_type = proposal
                .payload
                .get("entity_type")
                .and_then(Value::as_str)
                .ok_or("finding.entity_add proposal missing payload.entity_type")?;
            const VALID_ENTITY_TYPES: &[&str] = &[
                "gene",
                "protein",
                "compound",
                "disease",
                "cell_type",
                "organism",
                "pathway",
                "assay",
                "anatomical_structure",
                "particle",
                "instrument",
                "dataset",
                "quantity",
                "other",
            ];
            if !VALID_ENTITY_TYPES.contains(&entity_type) {
                return Err(format!(
                    "finding.entity_add payload.entity_type '{entity_type}' not in {VALID_ENTITY_TYPES:?}"
                ));
            }
            let reason = proposal
                .payload
                .get("reason")
                .and_then(Value::as_str)
                .ok_or("finding.entity_add proposal missing payload.reason")?;
            if reason.trim().is_empty() {
                return Err("finding.entity_add payload.reason must be non-empty".to_string());
            }
        }
        // v0.56: standalone validation of an evidence-atom locator
        // repair. Mirrors the contextual validator in
        // `validate_proposal_shape`, except without frontier-side
        // existence checks (the standalone validator runs over an
        // exported proposal before it is loaded into a frontier).
        "evidence_atom.locator_repair" => {
            if proposal.target.r#type != "evidence_atom" {
                return Err(format!(
                    "evidence_atom.locator_repair target.type must be 'evidence_atom', got '{}'",
                    proposal.target.r#type
                ));
            }
            let locator = proposal
                .payload
                .get("locator")
                .and_then(Value::as_str)
                .ok_or("evidence_atom.locator_repair proposal missing payload.locator")?;
            if locator.trim().is_empty() {
                return Err(
                    "evidence_atom.locator_repair payload.locator must be non-empty".to_string(),
                );
            }
            let source_id = proposal
                .payload
                .get("source_id")
                .and_then(Value::as_str)
                .ok_or("evidence_atom.locator_repair proposal missing payload.source_id")?;
            if source_id.trim().is_empty() {
                return Err(
                    "evidence_atom.locator_repair payload.source_id must be non-empty".to_string(),
                );
            }
        }
        // v0.59: federation conflict resolution (standalone shape;
        // no frontier-existence checks here, the apply step verifies
        // the conflict_event_id is present).
        "frontier.conflict_resolve" => {
            if proposal.target.r#type != "frontier_observation" {
                return Err(format!(
                    "frontier.conflict_resolve target.type must be 'frontier_observation', got '{}'",
                    proposal.target.r#type
                ));
            }
            let conflict_event_id = proposal
                .payload
                .get("conflict_event_id")
                .and_then(Value::as_str)
                .ok_or("frontier.conflict_resolve proposal missing payload.conflict_event_id")?;
            if conflict_event_id.trim().is_empty() {
                return Err(
                    "frontier.conflict_resolve payload.conflict_event_id must be non-empty"
                        .to_string(),
                );
            }
            let note = proposal
                .payload
                .get("resolution_note")
                .and_then(Value::as_str)
                .ok_or("frontier.conflict_resolve proposal missing payload.resolution_note")?;
            if note.trim().is_empty() {
                return Err(
                    "frontier.conflict_resolve payload.resolution_note must be non-empty"
                        .to_string(),
                );
            }
        }
        other => return Err(format!("Unsupported proposal kind '{other}'")),
    }
    validate_decision_state(proposal)
}

fn require_existing_finding(frontier: &Project, finding_id: &str) -> Result<usize, String> {
    frontier
        .findings
        .iter()
        .position(|finding| finding.id == finding_id)
        .ok_or_else(|| format!("Finding not found: {finding_id}"))
}

fn accept_proposal_in_frontier(
    frontier: &mut Project,
    proposal_id: &str,
    reviewer: &str,
    reason: &str,
) -> Result<String, String> {
    validate_reviewer_identity(reviewer)?;
    if reason.trim().is_empty() {
        return Err("Decision reason must be non-empty".to_string());
    }
    let index = frontier
        .proposals
        .iter()
        .position(|proposal| proposal.id == proposal_id)
        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?;
    let status = frontier.proposals[index].status.clone();
    if status == "rejected" {
        return Err(format!("Cannot accept rejected proposal {}", proposal_id));
    }
    if status == "applied" {
        return frontier.proposals[index]
            .applied_event_id
            .clone()
            .ok_or_else(|| format!("Proposal {} is applied but has no event id", proposal_id));
    }
    let proposal = frontier.proposals[index].clone();
    validate_proposal_shape(frontier, &proposal)?;
    frontier.proposals[index].status = "accepted".to_string();
    frontier.proposals[index].reviewed_by = Some(reviewer.to_string());
    frontier.proposals[index].reviewed_at = Some(Utc::now().to_rfc3339());
    frontier.proposals[index].decision_reason = Some(reason.to_string());
    let event_id = apply_proposal(frontier, &proposal, reviewer, reason)?;
    frontier.proposals[index].status = "applied".to_string();
    frontier.proposals[index].applied_event_id = Some(event_id.clone());
    Ok(event_id)
}

fn reject_proposal_in_frontier(
    frontier: &mut Project,
    proposal_id: &str,
    reviewer: &str,
    reason: &str,
) -> Result<(), String> {
    validate_reviewer_identity(reviewer)?;
    if reason.trim().is_empty() {
        return Err("Decision reason must be non-empty".to_string());
    }
    let index = frontier
        .proposals
        .iter()
        .position(|proposal| proposal.id == proposal_id)
        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?;
    match frontier.proposals[index].status.as_str() {
        "pending_review" | "accepted" => {}
        "rejected" => {
            return Err(format!("Proposal {} is already rejected", proposal_id));
        }
        "applied" => {
            return Err(format!("Proposal {} is already applied", proposal_id));
        }
        other => {
            return Err(format!("Unsupported proposal status '{}'", other));
        }
    }
    frontier.proposals[index].status = "rejected".to_string();
    frontier.proposals[index].reviewed_by = Some(reviewer.to_string());
    frontier.proposals[index].reviewed_at = Some(Utc::now().to_rfc3339());
    frontier.proposals[index].decision_reason = Some(reason.to_string());
    Ok(())
}

fn request_revision_in_frontier(
    frontier: &mut Project,
    proposal_id: &str,
    reviewer: &str,
    reason: &str,
) -> Result<(), String> {
    validate_reviewer_identity(reviewer)?;
    if reason.trim().is_empty() {
        return Err("Decision reason must be non-empty".to_string());
    }
    let index = frontier
        .proposals
        .iter()
        .position(|proposal| proposal.id == proposal_id)
        .ok_or_else(|| format!("Proposal not found: {proposal_id}"))?;
    match frontier.proposals[index].status.as_str() {
        "pending_review" => {}
        "needs_revision" => {
            return Err(format!("Proposal {} already needs revision", proposal_id));
        }
        "rejected" => {
            return Err(format!("Proposal {} is already rejected", proposal_id));
        }
        "applied" => {
            return Err(format!("Proposal {} is already applied", proposal_id));
        }
        other => {
            return Err(format!("Unsupported proposal status '{}'", other));
        }
    }
    frontier.proposals[index].status = "needs_revision".to_string();
    frontier.proposals[index].reviewed_by = Some(reviewer.to_string());
    frontier.proposals[index].reviewed_at = Some(Utc::now().to_rfc3339());
    frontier.proposals[index].decision_reason = Some(reason.to_string());
    Ok(())
}

fn apply_proposal(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    decision_reason: &str,
) -> Result<String, String> {
    // Phase L: retraction emits a fan of events — one for the source
    // and one `finding.dependency_invalidated` per dependent in BFS
    // order. apply_retract is responsible for pushing all of them in
    // sequence; this branch only assigns the primary event ID.
    if proposal.kind.as_str() == "finding.retract" {
        let events = apply_retract(frontier, proposal, reviewer, decision_reason)?;
        let primary_id = events
            .first()
            .map(|event| event.id.clone())
            .ok_or_else(|| "apply_retract returned no events".to_string())?;
        for event in events {
            frontier.events.push(event);
        }
        mark_proof_stale(
            frontier,
            format!("Applied proposal {} after latest proof export", proposal.id),
        );
        return Ok(primary_id);
    }
    // v0.55: confidence_revise can also fan out a cascade when the new
    // score crosses below the 0.5 propagation threshold. Same fan-out
    // pattern as retract.
    if proposal.kind.as_str() == "finding.confidence_revise" {
        let events = apply_confidence_revise(frontier, proposal, reviewer, decision_reason)?;
        let primary_id = events
            .first()
            .map(|event| event.id.clone())
            .ok_or_else(|| "apply_confidence_revise returned no events".to_string())?;
        for event in events {
            frontier.events.push(event);
        }
        mark_proof_stale(
            frontier,
            format!("Applied proposal {} after latest proof export", proposal.id),
        );
        return Ok(primary_id);
    }
    let event = match proposal.kind.as_str() {
        "finding.add" => apply_add(frontier, proposal, reviewer, decision_reason)?,
        "finding.review" => apply_review(frontier, proposal, reviewer, decision_reason)?,
        "finding.caveat" => apply_caveat(frontier, proposal, reviewer, decision_reason)?,
        "finding.note" => apply_note(frontier, proposal, reviewer, decision_reason)?,
        "finding.reject" => apply_reject(frontier, proposal, reviewer, decision_reason)?,
        "finding.supersede" => apply_supersede(frontier, proposal, reviewer, decision_reason)?,
        "artifact.assert" => apply_artifact_assert(frontier, proposal, reviewer, decision_reason)?,
        // v0.52: agent-inbox-deposited nulls and trajectories follow
        // the same review-gated path as findings.
        "negative_result.assert" => {
            apply_negative_result_assert(frontier, proposal, reviewer, decision_reason)?
        }
        "trajectory.create" => {
            apply_trajectory_create(frontier, proposal, reviewer, decision_reason)?
        }
        "trajectory.step_append" => {
            apply_trajectory_step_append(frontier, proposal, reviewer, decision_reason)?
        }
        // v0.56: mechanical evidence-atom locator repair.
        "evidence_atom.locator_repair" => {
            apply_evidence_atom_locator_repair(frontier, proposal, reviewer, decision_reason)?
        }
        // v0.57: mechanical finding-level span repair.
        "finding.span_repair" => {
            apply_finding_span_repair(frontier, proposal, reviewer, decision_reason)?
        }
        // v0.57: entity resolution.
        "finding.entity_resolve" => {
            apply_finding_entity_resolve(frontier, proposal, reviewer, decision_reason)?
        }
        // v0.79: append a new entity tag to an existing finding.
        // Closes the v0.78.4 honest gap.
        "finding.entity_add" => {
            apply_finding_entity_add(frontier, proposal, reviewer, decision_reason)?
        }
        // v0.59: federation conflict resolution.
        "frontier.conflict_resolve" => {
            apply_frontier_conflict_resolve(frontier, proposal, reviewer, decision_reason)?
        }
        other => return Err(format!("Unsupported proposal kind '{other}'")),
    };
    let event_id = event.id.clone();
    frontier.events.push(event);
    mark_proof_stale(
        frontier,
        format!("Applied proposal {} after latest proof export", proposal.id),
    );
    Ok(event_id)
}

/// v0.14: `finding.supersede` — first-class flow for *changing a claim's text*.
///
/// Until v0.14 the only way to update a finding was to stack caveats/notes
/// on top, because the assertion text is part of the content address. The
/// substrate-correct path for a real correction is a *new* content-addressed
/// finding that explicitly supersedes the old one. This proposal kind:
///
/// 1. Validates the old finding exists and is not already superseded.
/// 2. Adds the new finding bundle (a fresh `vf_…` content address) to
///    `frontier.findings`.
/// 3. Auto-injects a `supersedes` link from the new finding's `links` to the
///    old finding's id (if not already present in the payload).
/// 4. Sets `flags.superseded = true` on the old finding.
/// 5. Emits a `finding.superseded` canonical event targeting the *old*
///    finding (since that's the state change). The new finding's existence
///    is recorded in the event payload as `new_finding_id`.
///
/// Both findings remain queryable; readers walk the supersedes chain via
/// the link or via the `flags.superseded` marker.
fn apply_supersede(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    use crate::bundle::Link;

    let old_id = proposal.target.id.clone();
    let new_finding_value = proposal
        .payload
        .get("new_finding")
        .ok_or("finding.supersede proposal missing payload.new_finding")?
        .clone();
    let mut new_finding: FindingBundle = serde_json::from_value(new_finding_value)
        .map_err(|e| format!("Invalid finding.supersede payload.new_finding: {e}"))?;

    // Locate the old finding before mutating; capture before_hash for the event.
    let old_idx = find_finding_index(frontier, &old_id)?;
    if frontier.findings[old_idx].flags.superseded {
        return Err(format!(
            "Refusing to supersede already-superseded finding {old_id}"
        ));
    }
    if new_finding.id == old_id {
        return Err(
            "Refusing to supersede with a finding that has the same content address as the old finding (assertion / type / provenance_id are unchanged)".to_string(),
        );
    }
    if frontier
        .findings
        .iter()
        .any(|existing| existing.id == new_finding.id)
    {
        return Err(format!(
            "Refusing to add superseding finding with existing finding ID {}",
            new_finding.id
        ));
    }
    let before_hash = events::finding_hash(&frontier.findings[old_idx]);

    // Auto-inject the supersedes link if the caller didn't already include it.
    let already_links_old = new_finding
        .links
        .iter()
        .any(|l| l.target == old_id && l.link_type == "supersedes");
    if !already_links_old {
        new_finding.links.push(Link {
            target: old_id.clone(),
            link_type: "supersedes".to_string(),
            note: format!(
                "Supersedes {old_id} via finding.supersede proposal {}.",
                proposal.id
            ),
            inferred_by: "reviewer".to_string(),
            created_at: Utc::now().to_rfc3339(),
            mechanism: None,
        });
    }

    let new_finding_id = new_finding.id.clone();
    frontier.findings.push(new_finding);
    frontier.findings[old_idx].flags.superseded = true;
    let after_hash = events::finding_hash(&frontier.findings[old_idx]);

    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.superseded",
        finding_id: &old_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload: json!({
            "proposal_id": proposal.id,
            "new_finding_id": new_finding_id,
        }),
        caveats: proposal.caveats.clone(),
    }))
}

fn apply_add(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let finding_value = proposal
        .payload
        .get("finding")
        .ok_or("finding.add proposal missing payload.finding")?
        .clone();
    let finding: FindingBundle = serde_json::from_value(finding_value)
        .map_err(|e| format!("Invalid finding.add payload: {e}"))?;
    let finding_id = finding.id.clone();
    if frontier
        .findings
        .iter()
        .any(|existing| existing.id == finding_id)
    {
        return Err(format!(
            "Refusing to add duplicate finding with existing finding ID {finding_id}"
        ));
    }
    frontier.findings.push(finding);
    let after_hash = events::finding_hash_by_id(frontier, &finding_id);
    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.asserted",
        finding_id: &finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: NULL_HASH,
        after_hash: &after_hash,
        payload: json!({
            "proposal_id": proposal.id,
        }),
        caveats: proposal.caveats.clone(),
    }))
}

fn apply_artifact_assert(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let artifact_value = proposal
        .payload
        .get("artifact")
        .ok_or("artifact.assert proposal missing payload.artifact")?
        .clone();
    let artifact: Artifact = serde_json::from_value(artifact_value)
        .map_err(|e| format!("Invalid artifact.assert payload: {e}"))?;
    let artifact_id = artifact.id.clone();
    if frontier
        .artifacts
        .iter()
        .any(|existing| existing.id == artifact_id)
    {
        return Err(format!(
            "Refusing to add duplicate artifact with existing id {artifact_id}"
        ));
    }
    frontier.artifacts.push(artifact.clone());
    let mut event = StateEvent {
        schema: events::EVENT_SCHEMA.to_string(),
        id: String::new(),
        kind: events::EVENT_KIND_ARTIFACT_ASSERTED.to_string(),
        target: StateTarget {
            r#type: "artifact".to_string(),
            id: artifact_id,
        },
        actor: StateActor {
            id: reviewer.to_string(),
            r#type: if reviewer.starts_with("agent:") {
                "agent"
            } else {
                "human"
            }
            .to_string(),
        },
        timestamp: Utc::now().to_rfc3339(),
        reason: proposal.reason.clone(),
        before_hash: NULL_HASH.to_string(),
        after_hash: NULL_HASH.to_string(),
        payload: json!({
            "proposal_id": proposal.id,
            "artifact": artifact,
        }),
        caveats: proposal.caveats.clone(),
        signature: None,
        schema_artifact_id: None,
    };
    events::validate_event_payload(&event.kind, &event.payload)?;
    event.id = events::compute_event_id(&event);
    Ok(event)
}

fn apply_review(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let finding_id = proposal.target.id.as_str();
    let idx = find_finding_index(frontier, finding_id)?;
    let before_hash = events::finding_hash(&frontier.findings[idx]);
    let status = proposal
        .payload
        .get("status")
        .and_then(Value::as_str)
        .ok_or("finding.review proposal 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!("Unknown review proposal status '{other}'")),
    };
    frontier.findings[idx].flags.contested = new_state.implies_contested();
    frontier.findings[idx].flags.review_state = Some(new_state);
    let after_hash = events::finding_hash(&frontier.findings[idx]);
    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.reviewed",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload: json!({
            "status": status,
            "proposal_id": proposal.id,
        }),
        caveats: proposal.caveats.clone(),
    }))
}

fn apply_caveat(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let finding_id = proposal.target.id.as_str();
    let idx = find_finding_index(frontier, finding_id)?;
    let before_hash = events::finding_hash(&frontier.findings[idx]);
    let now = Utc::now().to_rfc3339();
    let text = proposal
        .payload
        .get("text")
        .and_then(Value::as_str)
        .ok_or("finding.caveat proposal missing payload.text")?;
    let provenance = extract_annotation_provenance(&proposal.payload);
    let annotation_id = annotation_id(finding_id, text, reviewer, &now);
    frontier.findings[idx].annotations.push(Annotation {
        id: annotation_id.clone(),
        text: text.to_string(),
        author: reviewer.to_string(),
        timestamp: now,
        provenance: provenance.clone(),
    });
    let after_hash = events::finding_hash(&frontier.findings[idx]);
    let mut payload = json!({
        "annotation_id": annotation_id,
        "text": text,
        "proposal_id": proposal.id,
    });
    if let Some(prov) = &provenance {
        payload["provenance"] = serde_json::to_value(prov).unwrap_or(Value::Null);
    }
    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.caveated",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: text,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload,
        caveats: proposal.caveats.clone(),
    }))
}

fn apply_note(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let finding_id = proposal.target.id.as_str();
    let idx = find_finding_index(frontier, finding_id)?;
    let before_hash = events::finding_hash(&frontier.findings[idx]);
    let now = Utc::now().to_rfc3339();
    let text = proposal
        .payload
        .get("text")
        .and_then(Value::as_str)
        .ok_or("finding.note proposal missing payload.text")?;
    let provenance = extract_annotation_provenance(&proposal.payload);
    let annotation_id = annotation_id(finding_id, text, reviewer, &now);
    frontier.findings[idx].annotations.push(Annotation {
        id: annotation_id.clone(),
        text: text.to_string(),
        author: reviewer.to_string(),
        timestamp: now,
        provenance: provenance.clone(),
    });
    let after_hash = events::finding_hash(&frontier.findings[idx]);
    let mut payload = json!({
        "annotation_id": annotation_id,
        "text": text,
        "proposal_id": proposal.id,
    });
    if let Some(prov) = &provenance {
        payload["provenance"] = serde_json::to_value(prov).unwrap_or(Value::Null);
    }
    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.noted",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: text,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload,
        caveats: proposal.caveats.clone(),
    }))
}

/// v0.57: Apply a `finding.entity_resolve` proposal. Sets canonical_id
/// + resolution metadata on the named entity inside the target finding's
/// assertion.entities array, and clears the entity's needs_review flag.
fn apply_finding_entity_resolve(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    use crate::bundle::{ResolutionMethod, ResolvedId};

    let finding_id = proposal.target.id.as_str();
    let entity_name = proposal
        .payload
        .get("entity_name")
        .and_then(Value::as_str)
        .ok_or("finding.entity_resolve proposal missing payload.entity_name")?
        .to_string();
    let source = proposal
        .payload
        .get("source")
        .and_then(Value::as_str)
        .ok_or("finding.entity_resolve proposal missing payload.source")?
        .to_string();
    let id = proposal
        .payload
        .get("id")
        .and_then(Value::as_str)
        .ok_or("finding.entity_resolve proposal missing payload.id")?
        .to_string();
    let confidence = proposal
        .payload
        .get("confidence")
        .and_then(Value::as_f64)
        .ok_or("finding.entity_resolve proposal missing payload.confidence")?;
    let matched_name = proposal
        .payload
        .get("matched_name")
        .and_then(Value::as_str)
        .map(str::to_string);
    let provenance = proposal
        .payload
        .get("resolution_provenance")
        .and_then(Value::as_str)
        .unwrap_or("delegated_human_curation")
        .to_string();
    let method_str = proposal
        .payload
        .get("resolution_method")
        .and_then(Value::as_str)
        .unwrap_or("manual");
    let method = match method_str {
        "exact_match" => ResolutionMethod::ExactMatch,
        "fuzzy_match" => ResolutionMethod::FuzzyMatch,
        "llm_inference" => ResolutionMethod::LlmInference,
        "manual" => ResolutionMethod::Manual,
        other => {
            return Err(format!(
                "finding.entity_resolve unknown resolution_method '{other}'"
            ));
        }
    };

    let f_idx = find_finding_index(frontier, finding_id)?;
    let e_idx = frontier.findings[f_idx]
        .assertion
        .entities
        .iter()
        .position(|e| e.name == entity_name)
        .ok_or_else(|| {
            format!("finding.entity_resolve entity '{entity_name}' not in finding {finding_id}")
        })?;

    let before_hash = events::finding_hash(&frontier.findings[f_idx]);
    let entity = &mut frontier.findings[f_idx].assertion.entities[e_idx];
    entity.canonical_id = Some(ResolvedId {
        source: source.clone(),
        id: id.clone(),
        confidence,
        matched_name: matched_name.clone(),
    });
    entity.resolution_method = Some(method);
    entity.resolution_provenance = Some(provenance.clone());
    entity.resolution_confidence = confidence;
    entity.needs_review = false;
    let after_hash = events::finding_hash(&frontier.findings[f_idx]);

    let mut payload = json!({
        "proposal_id": proposal.id,
        "entity_name": entity_name,
        "source": source,
        "id": id,
        "confidence": confidence,
        "resolution_method": method_str,
        "resolution_provenance": provenance,
    });
    if let Some(m) = matched_name {
        payload["matched_name"] = serde_json::Value::String(m);
    }

    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.entity_resolved",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload,
        caveats: proposal.caveats.clone(),
    }))
}

/// v0.79: Apply a `finding.entity_add` proposal. Pushes a new
/// `Entity{name, type, ...}` onto `state.findings[i].assertion.entities`
/// and emits one signed `finding.entity_added` event. Idempotent on
/// `(finding_id, entity_name)`.
fn apply_finding_entity_add(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    use crate::bundle::Entity;

    let finding_id = proposal.target.id.as_str();
    let entity_name = proposal
        .payload
        .get("entity_name")
        .and_then(Value::as_str)
        .ok_or("finding.entity_add proposal missing payload.entity_name")?
        .to_string();
    let entity_type = proposal
        .payload
        .get("entity_type")
        .and_then(Value::as_str)
        .ok_or("finding.entity_add proposal missing payload.entity_type")?
        .to_string();
    let reason_text = proposal
        .payload
        .get("reason")
        .and_then(Value::as_str)
        .ok_or("finding.entity_add proposal missing payload.reason")?
        .to_string();

    let idx = find_finding_index(frontier, finding_id)?;
    let already_present = frontier.findings[idx]
        .assertion
        .entities
        .iter()
        .any(|e| e.name == entity_name);

    let before_hash = events::finding_hash(&frontier.findings[idx]);
    if !already_present {
        let entity = Entity {
            name: entity_name.clone(),
            entity_type: entity_type.clone(),
            identifiers: serde_json::Map::new(),
            canonical_id: None,
            candidates: Vec::new(),
            aliases: Vec::new(),
            resolution_provenance: None,
            resolution_confidence: 1.0,
            resolution_method: None,
            species_context: None,
            needs_review: false,
        };
        frontier.findings[idx].assertion.entities.push(entity);
    }
    let after_hash = events::finding_hash(&frontier.findings[idx]);

    let payload = json!({
        "proposal_id": proposal.id,
        "entity_name": entity_name,
        "entity_type": entity_type,
        "reason": reason_text,
        "idempotent_noop": already_present,
    });

    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.entity_added",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload,
        caveats: proposal.caveats.clone(),
    }))
}

/// v0.57: Apply a `finding.span_repair` proposal. Appends a
/// `{section, text}` span to `state.findings[i].evidence.evidence_spans`
/// and emits one signed `finding.span_repaired` event.
fn apply_finding_span_repair(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let finding_id = proposal.target.id.as_str();
    let section = proposal
        .payload
        .get("section")
        .and_then(Value::as_str)
        .ok_or("finding.span_repair proposal missing payload.section")?
        .to_string();
    let text = proposal
        .payload
        .get("text")
        .and_then(Value::as_str)
        .ok_or("finding.span_repair proposal missing payload.text")?
        .to_string();
    let idx = find_finding_index(frontier, finding_id)?;
    let already_present = frontier.findings[idx]
        .evidence
        .evidence_spans
        .iter()
        .any(|existing| {
            existing.get("section").and_then(Value::as_str) == Some(section.as_str())
                && existing.get("text").and_then(Value::as_str) == Some(text.as_str())
        });
    if already_present {
        return Err(format!(
            "finding {finding_id} already carries an identical (section, text) span"
        ));
    }
    let before_hash = events::finding_hash(&frontier.findings[idx]);
    let span_value = json!({"section": section, "text": text});
    frontier.findings[idx]
        .evidence
        .evidence_spans
        .push(span_value);
    let after_hash = events::finding_hash(&frontier.findings[idx]);
    let payload = json!({
        "proposal_id": proposal.id,
        "section": section,
        "text": text,
    });
    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.span_repaired",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload,
        caveats: proposal.caveats.clone(),
    }))
}

/// v0.56: Apply an `evidence_atom.locator_repair` proposal. Sets
/// `locator` on the named evidence atom, removes the
/// "missing evidence locator" caveat, and emits one signed
/// `evidence_atom.locator_repaired` canonical event. The before/after
/// hashes are over the canonical bytes of the named atom only, so a
/// chain validator can confirm the exact atom changed and exactly the
/// named repair was applied.
fn apply_evidence_atom_locator_repair(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let atom_id = proposal.target.id.as_str();
    let locator = proposal
        .payload
        .get("locator")
        .and_then(Value::as_str)
        .ok_or("evidence_atom.locator_repair proposal missing payload.locator")?
        .to_string();
    let source_id = proposal
        .payload
        .get("source_id")
        .and_then(Value::as_str)
        .ok_or("evidence_atom.locator_repair proposal missing payload.source_id")?
        .to_string();

    let idx = frontier
        .evidence_atoms
        .iter()
        .position(|atom| atom.id == atom_id)
        .ok_or_else(|| format!("evidence_atom.locator_repair targets unknown atom {atom_id}"))?;
    if frontier.evidence_atoms[idx].source_id != source_id {
        return Err(format!(
            "evidence_atom.locator_repair payload.source_id '{source_id}' does not match atom.source_id '{}'",
            frontier.evidence_atoms[idx].source_id
        ));
    }
    if let Some(existing) = &frontier.evidence_atoms[idx].locator {
        if existing == &locator {
            return Err(format!(
                "evidence_atom {atom_id} already carries locator '{existing}'"
            ));
        }
        return Err(format!(
            "evidence_atom {atom_id} already carries locator '{existing}'; refusing to overwrite with '{locator}'"
        ));
    }

    let before_hash = events::evidence_atom_hash(&frontier.evidence_atoms[idx]);
    frontier.evidence_atoms[idx].locator = Some(locator.clone());
    frontier.evidence_atoms[idx]
        .caveats
        .retain(|c| c != "missing evidence locator");
    let after_hash = events::evidence_atom_hash(&frontier.evidence_atoms[idx]);

    let payload = json!({
        "proposal_id": proposal.id,
        "locator": locator,
        "source_id": source_id,
    });

    Ok(events::new_evidence_atom_locator_repair_event(
        atom_id,
        reviewer,
        "human",
        &proposal.reason,
        &before_hash,
        &after_hash,
        payload,
        proposal.caveats.clone(),
    ))
}

/// v0.59: apply a `frontier.conflict_resolve` proposal. Emits one
/// `frontier.conflict_resolved` event recording the reviewer's
/// verdict on a previously detected conflict. The conflict event
/// itself is not modified; consumers pair the two by matching
/// `payload.conflict_event_id` on the resolved event to the
/// detected event's id.
fn apply_frontier_conflict_resolve(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let conflict_event_id = proposal
        .payload
        .get("conflict_event_id")
        .and_then(Value::as_str)
        .ok_or("frontier.conflict_resolve proposal missing payload.conflict_event_id")?
        .to_string();
    let resolution_note = proposal
        .payload
        .get("resolution_note")
        .and_then(Value::as_str)
        .ok_or("frontier.conflict_resolve proposal missing payload.resolution_note")?
        .to_string();
    let winning_proposal_id = proposal
        .payload
        .get("winning_proposal_id")
        .and_then(Value::as_str)
        .map(|s| s.to_string());

    // Confirm the conflict event exists and is the right kind.
    // Refuse double-resolution at apply time too (the validator
    // already checks but we check again because validation is best
    // effort against the live frontier and apply is the authority).
    let conflict_event = frontier
        .events
        .iter()
        .find(|e| e.id == conflict_event_id)
        .ok_or_else(|| {
            format!("frontier.conflict_resolve targets unknown event id '{conflict_event_id}'")
        })?
        .clone();
    if conflict_event.kind != "frontier.conflict_detected" {
        return Err(format!(
            "frontier.conflict_resolve target event '{conflict_event_id}' has kind '{}', expected 'frontier.conflict_detected'",
            conflict_event.kind
        ));
    }
    if frontier.events.iter().any(|e| {
        e.kind == "frontier.conflict_resolved"
            && e.payload.get("conflict_event_id").and_then(Value::as_str)
                == Some(&conflict_event_id)
    }) {
        return Err(format!(
            "Conflict event '{conflict_event_id}' already has a recorded resolution"
        ));
    }

    let mut payload = json!({
        "proposal_id": proposal.id,
        "conflict_event_id": conflict_event_id,
        "resolved_by": reviewer,
        "resolution_note": resolution_note,
    });
    if let Some(wpid) = &winning_proposal_id {
        payload["winning_proposal_id"] = json!(wpid);
    }

    let frontier_id = frontier.frontier_id();
    Ok(events::new_frontier_conflict_resolved_event(
        &frontier_id,
        reviewer,
        "human",
        &proposal.reason,
        payload,
        proposal.caveats.clone(),
    ))
}

/// Phase β (v0.6): pull optional structured provenance off a note/caveat
/// proposal payload. The propose-* tools accept it; the validator gates
/// it; this helper threads it through to the materialized annotation
/// and the canonical event payload.
fn extract_annotation_provenance(payload: &Value) -> Option<crate::bundle::ProvenanceRef> {
    let prov = payload.get("provenance")?;
    let parsed: crate::bundle::ProvenanceRef = serde_json::from_value(prov.clone()).ok()?;
    if parsed.has_identifier() {
        Some(parsed)
    } else {
        None
    }
}

fn apply_confidence_revise(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<Vec<StateEvent>, String> {
    let finding_id = proposal.target.id.as_str();
    let idx = find_finding_index(frontier, finding_id)?;
    let now = Utc::now().to_rfc3339();
    let previous = frontier.findings[idx].confidence.score;
    let new_score = proposal
        .payload
        .get("confidence")
        .and_then(Value::as_f64)
        .ok_or("finding.confidence_revise proposal missing payload.confidence")?;

    // v0.55: when the revised confidence crosses the propagation threshold
    // (previous >= 0.5, new < 0.5), invoke the same cascade pattern that
    // `apply_retract` uses — emit `finding.dependency_invalidated` events for
    // each downstream supports/depends finding at depth ≤ MAX_DEPTH. Pre-v0.55
    // this path silently mutated confidence without firing the cascade, which
    // forced callers to chase a separate `vela propagate --reduce-confidence`
    // command for the substrate's signature feature.
    let cascade_threshold_crossed = previous >= 0.5 && new_score < 0.5;

    let pre_cascade_hashes: std::collections::HashMap<String, String> = if cascade_threshold_crossed
    {
        frontier
            .findings
            .iter()
            .map(|finding| (finding.id.clone(), events::finding_hash(finding)))
            .collect()
    } else {
        std::collections::HashMap::new()
    };

    let before_hash = events::finding_hash(&frontier.findings[idx]);

    // Apply the local mutation first so propagate_correction sees the new
    // confidence on the source finding.
    frontier.findings[idx].confidence.score = new_score;
    frontier.findings[idx].confidence.basis = format!(
        "expert revision from {:.3} to {:.3}: {}",
        previous, new_score, proposal.reason
    );
    frontier.findings[idx].confidence.method = ConfidenceMethod::ExpertJudgment;
    frontier.findings[idx].updated = Some(now.clone());

    let cascade = if cascade_threshold_crossed {
        Some(propagate::propagate_correction(
            frontier,
            finding_id,
            PropagationAction::ConfidenceReduced { new_score },
        ))
    } else {
        None
    };

    let after_hash = events::finding_hash(&frontier.findings[idx]);

    let source_event = events::new_finding_event(events::FindingEventInput {
        kind: "finding.confidence_revised",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload: json!({
            "previous_score": previous,
            "new_score": new_score,
            "updated_at": now,
            "proposal_id": proposal.id,
            "cascade_fired": cascade_threshold_crossed,
            "affected": cascade.as_ref().map(|c| c.affected).unwrap_or(0),
        }),
        caveats: proposal.caveats.clone(),
    });

    let source_event_id = source_event.id.clone();
    let mut emitted = vec![source_event];

    if let Some(cascade) = cascade {
        // Mirror apply_retract's per-dependent dependency_invalidated emission:
        // each affected dep at each depth gets a canonical event with the
        // before/after hash boundary so chain validation works downstream.
        for (depth_idx, level) in cascade.cascade.iter().enumerate() {
            let depth = (depth_idx as u32) + 1;
            for dep_id in level {
                let before = pre_cascade_hashes
                    .get(dep_id)
                    .cloned()
                    .unwrap_or_else(|| events::NULL_HASH.to_string());
                let after = events::finding_hash_by_id(frontier, dep_id);
                emitted.push(events::new_finding_event(events::FindingEventInput {
                    kind: "finding.dependency_invalidated",
                    finding_id: dep_id,
                    actor_id: reviewer,
                    actor_type: "human",
                    reason: &format!(
                        "Upstream finding {finding_id} confidence reduced to {new_score:.2}; cascade depth {depth}"
                    ),
                    before_hash: &before,
                    after_hash: &after,
                    payload: json!({
                        "upstream_finding_id": finding_id,
                        "upstream_event_id": source_event_id,
                        "depth": depth,
                        "new_score": new_score,
                        "previous_score": previous,
                        "proposal_id": proposal.id,
                    }),
                    caveats: vec![],
                }));
            }
        }
    }

    Ok(emitted)
}

fn apply_reject(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let finding_id = proposal.target.id.as_str();
    let idx = find_finding_index(frontier, finding_id)?;
    let before_hash = events::finding_hash(&frontier.findings[idx]);
    frontier.findings[idx].flags.contested = true;
    let after_hash = events::finding_hash(&frontier.findings[idx]);
    Ok(events::new_finding_event(events::FindingEventInput {
        kind: "finding.rejected",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload: json!({
            "proposal_id": proposal.id,
            "status": "rejected",
        }),
        caveats: proposal.caveats.clone(),
    }))
}

fn apply_retract(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<Vec<StateEvent>, String> {
    let finding_id = proposal.target.id.as_str();
    let idx = find_finding_index(frontier, finding_id)?;
    if frontier.findings[idx].flags.retracted {
        return Err(format!("Finding {finding_id} is already retracted"));
    }
    // Phase L: capture every finding's pre-cascade hash so each emitted
    // `finding.dependency_invalidated` event can name a real before_hash
    // that matches whatever event last touched that dep.
    let pre_cascade_hashes: std::collections::HashMap<String, String> = frontier
        .findings
        .iter()
        .map(|finding| (finding.id.clone(), events::finding_hash(finding)))
        .collect();

    let before_hash = events::finding_hash(&frontier.findings[idx]);
    let cascade =
        propagate::propagate_correction(frontier, finding_id, PropagationAction::Retracted);
    let after_hash = events::finding_hash_by_id(frontier, finding_id);

    let source_event = events::new_finding_event(events::FindingEventInput {
        kind: "finding.retracted",
        finding_id,
        actor_id: reviewer,
        actor_type: "human",
        reason: &proposal.reason,
        before_hash: &before_hash,
        after_hash: &after_hash,
        payload: json!({
            "proposal_id": proposal.id,
            "affected": cascade.affected,
            "cascade": cascade.cascade,
        }),
        caveats: vec!["Retraction impact is simulated over declared dependency links.".to_string()],
    });
    let source_event_id = source_event.id.clone();

    let mut emitted = vec![source_event];

    // Phase L: emit one canonical `finding.dependency_invalidated`
    // event per affected dependent, in BFS depth order. Each event
    // carries the before/after hash boundary for that specific dep so
    // chain validation works downstream.
    for (depth_idx, level) in cascade.cascade.iter().enumerate() {
        let depth = (depth_idx as u32) + 1;
        for dep_id in level {
            let before = pre_cascade_hashes
                .get(dep_id)
                .cloned()
                .unwrap_or_else(|| events::NULL_HASH.to_string());
            let after = events::finding_hash_by_id(frontier, dep_id);
            emitted.push(events::new_finding_event(events::FindingEventInput {
                kind: "finding.dependency_invalidated",
                finding_id: dep_id,
                actor_id: reviewer,
                actor_type: "human",
                reason: &format!("Upstream finding {finding_id} retracted; cascade depth {depth}"),
                before_hash: &before,
                after_hash: &after,
                payload: json!({
                    "upstream_finding_id": finding_id,
                    "upstream_event_id": source_event_id,
                    "depth": depth,
                    "proposal_id": proposal.id,
                }),
                caveats: vec![],
            }));
        }
    }

    Ok(emitted)
}

fn find_finding_index(frontier: &Project, finding_id: &str) -> Result<usize, String> {
    frontier
        .findings
        .iter()
        .position(|finding| finding.id == finding_id)
        .ok_or_else(|| format!("Finding not found: {finding_id}"))
}

/// v0.52: Apply a `negative_result.assert` proposal — push the
/// inline NegativeResult to state and emit a canonical
/// `negative_result.asserted` event. The event payload re-includes
/// the full NegativeResult so a fresh replay reconstructs
/// `state.negative_results` from the event log alone (matching the
/// direct `state::add_negative_result` path).
fn apply_negative_result_assert(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let nr_value = proposal
        .payload
        .get("negative_result")
        .ok_or("negative_result.assert proposal missing payload.negative_result")?
        .clone();
    let nr: crate::bundle::NegativeResult = serde_json::from_value(nr_value.clone())
        .map_err(|e| format!("Invalid negative_result.assert payload: {e}"))?;
    if frontier.negative_results.iter().any(|n| n.id == nr.id) {
        return Err(format!(
            "Refusing to add duplicate negative_result with existing id {}",
            nr.id
        ));
    }
    let nr_id = nr.id.clone();
    frontier.negative_results.push(nr);

    let mut event = StateEvent {
        schema: events::EVENT_SCHEMA.to_string(),
        id: String::new(),
        kind: events::EVENT_KIND_NEGATIVE_RESULT_ASSERTED.to_string(),
        target: StateTarget {
            r#type: "negative_result".to_string(),
            id: nr_id,
        },
        actor: StateActor {
            id: reviewer.to_string(),
            r#type: "human".to_string(),
        },
        timestamp: Utc::now().to_rfc3339(),
        reason: proposal.reason.clone(),
        before_hash: NULL_HASH.to_string(),
        after_hash: NULL_HASH.to_string(),
        payload: json!({
            "proposal_id": proposal.id,
            "negative_result": nr_value,
        }),
        caveats: proposal.caveats.clone(),
        signature: None,
        schema_artifact_id: None,
    };
    event.id = events::compute_event_id(&event);
    Ok(event)
}

/// v0.52: Apply a `trajectory.create` proposal — push the inline
/// Trajectory to state and emit a canonical `trajectory.created`
/// event. Steps land later via separate `trajectory.step_append`
/// proposals.
fn apply_trajectory_create(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let traj_value = proposal
        .payload
        .get("trajectory")
        .ok_or("trajectory.create proposal missing payload.trajectory")?
        .clone();
    let traj: crate::bundle::Trajectory = serde_json::from_value(traj_value.clone())
        .map_err(|e| format!("Invalid trajectory.create payload: {e}"))?;
    if frontier.trajectories.iter().any(|t| t.id == traj.id) {
        return Err(format!(
            "Refusing to add duplicate trajectory with existing id {}",
            traj.id
        ));
    }
    let traj_id = traj.id.clone();
    frontier.trajectories.push(traj);

    let mut event = StateEvent {
        schema: events::EVENT_SCHEMA.to_string(),
        id: String::new(),
        kind: events::EVENT_KIND_TRAJECTORY_CREATED.to_string(),
        target: StateTarget {
            r#type: "trajectory".to_string(),
            id: traj_id,
        },
        actor: StateActor {
            id: reviewer.to_string(),
            r#type: "human".to_string(),
        },
        timestamp: Utc::now().to_rfc3339(),
        reason: proposal.reason.clone(),
        before_hash: NULL_HASH.to_string(),
        after_hash: NULL_HASH.to_string(),
        payload: json!({
            "proposal_id": proposal.id,
            "trajectory": traj_value,
        }),
        caveats: proposal.caveats.clone(),
        signature: None,
        schema_artifact_id: None,
    };
    event.id = events::compute_event_id(&event);
    Ok(event)
}

/// v0.52: Apply a `trajectory.step_append` proposal — append the
/// inline TrajectoryStep to the parent trajectory's `steps` and emit
/// a canonical `trajectory.step_appended` event. Idempotent on
/// duplicate step content-addresses.
fn apply_trajectory_step_append(
    frontier: &mut Project,
    proposal: &StateProposal,
    reviewer: &str,
    _decision_reason: &str,
) -> Result<StateEvent, String> {
    let parent_id = proposal.target.id.clone();
    let parent_idx = frontier
        .trajectories
        .iter()
        .position(|t| t.id == parent_id)
        .ok_or_else(|| format!("trajectory.step_append targets unknown trajectory {parent_id}"))?;
    let step_value = proposal
        .payload
        .get("step")
        .ok_or("trajectory.step_append proposal missing payload.step")?
        .clone();
    let step: crate::bundle::TrajectoryStep = serde_json::from_value(step_value.clone())
        .map_err(|e| format!("Invalid trajectory.step_append payload.step: {e}"))?;
    if frontier.trajectories[parent_idx]
        .steps
        .iter()
        .any(|s| s.id == step.id)
    {
        return Err(format!(
            "Refusing to add duplicate step with existing id {} on trajectory {}",
            step.id, parent_id
        ));
    }
    frontier.trajectories[parent_idx].steps.push(step);

    let mut event = StateEvent {
        schema: events::EVENT_SCHEMA.to_string(),
        id: String::new(),
        kind: events::EVENT_KIND_TRAJECTORY_STEP_APPENDED.to_string(),
        target: StateTarget {
            r#type: "trajectory".to_string(),
            id: parent_id.clone(),
        },
        actor: StateActor {
            id: reviewer.to_string(),
            r#type: "human".to_string(),
        },
        timestamp: Utc::now().to_rfc3339(),
        reason: proposal.reason.clone(),
        before_hash: NULL_HASH.to_string(),
        after_hash: NULL_HASH.to_string(),
        payload: json!({
            "proposal_id": proposal.id,
            "parent_trajectory_id": parent_id,
            "step": step_value,
        }),
        caveats: proposal.caveats.clone(),
        signature: None,
        schema_artifact_id: None,
    };
    event.id = events::compute_event_id(&event);
    Ok(event)
}

fn annotation_id(finding_id: &str, text: &str, author: &str, timestamp: &str) -> String {
    let hash = Sha256::digest(format!("{finding_id}|{text}|{author}|{timestamp}").as_bytes());
    format!("ann_{}", &hex::encode(hash)[..16])
}

pub fn manifest_hash(path: &Path) -> Result<String, String> {
    let bytes = std::fs::read(path)
        .map_err(|e| format!("Failed to read manifest '{}': {e}", path.display()))?;
    Ok(hex::encode(Sha256::digest(bytes)))
}

pub fn repo_proposals_dir(root: &Path) -> PathBuf {
    root.join(".vela/proposals")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bundle::{
        Assertion, Conditions, Confidence, ConfidenceKind, ConfidenceMethod, Entity, Evidence,
        Extraction, Flags, Provenance,
    };
    use crate::project;
    use tempfile::TempDir;

    fn finding(id: &str) -> FindingBundle {
        FindingBundle {
            id: id.to_string(),
            version: 1,
            previous_version: None,
            assertion: Assertion {
                text: "Test finding".to_string(),
                assertion_type: "mechanism".to_string(),
                entities: vec![Entity {
                    name: "LRP1".to_string(),
                    entity_type: "protein".to_string(),
                    identifiers: serde_json::Map::new(),
                    canonical_id: None,
                    candidates: Vec::new(),
                    aliases: Vec::new(),
                    resolution_provenance: None,
                    resolution_confidence: 1.0,
                    resolution_method: None,
                    species_context: None,
                    needs_review: false,
                }],
                relation: None,
                direction: None,
                causal_claim: None,
                causal_evidence_grade: None,
            },
            evidence: Evidence {
                evidence_type: "experimental".to_string(),
                model_system: String::new(),
                species: None,
                method: "manual".to_string(),
                sample_size: None,
                effect_size: None,
                p_value: None,
                replicated: false,
                replication_count: None,
                evidence_spans: Vec::new(),
            },
            conditions: Conditions {
                text: "mouse".to_string(),
                species_verified: Vec::new(),
                species_unverified: Vec::new(),
                in_vitro: false,
                in_vivo: true,
                human_data: false,
                clinical_trial: false,
                concentration_range: None,
                duration: None,
                age_group: None,
                cell_type: None,
            },
            confidence: Confidence {
                kind: ConfidenceKind::FrontierEpistemic,
                score: 0.7,
                basis: "test".to_string(),
                method: ConfidenceMethod::ExpertJudgment,
                components: None,
                extraction_confidence: 1.0,
            },
            provenance: Provenance {
                source_type: "published_paper".to_string(),
                doi: None,
                pmid: None,
                pmc: None,
                openalex_id: None,
                url: None,
                title: "Test".to_string(),
                authors: Vec::new(),
                year: Some(2024),
                journal: None,
                license: None,
                publisher: None,
                funders: Vec::new(),
                extraction: Extraction::default(),
                review: None,
                citation_count: None,
            },
            flags: 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,
            },
            links: Vec::new(),
            annotations: Vec::new(),
            attachments: Vec::new(),
            created: "2026-04-23T00:00:00Z".to_string(),
            updated: None,

            access_tier: crate::access_tier::AccessTier::Public,
        }
    }

    #[test]
    fn pending_review_proposal_does_not_mutate_frontier() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let frontier = project::assemble("test", vec![finding("vf_test")], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();
        let proposal = new_proposal(
            "finding.review",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test".to_string(),
            },
            "reviewer:test",
            "human",
            "Mouse-only evidence",
            json!({"status": "contested"}),
            Vec::new(),
            Vec::new(),
        );
        create_or_apply(&path, proposal, false).unwrap();
        let loaded = repo::load_from_path(&path).unwrap();
        assert_eq!(loaded.events.len(), 1); // genesis only (proposal pending)
        assert_eq!(loaded.proposals.len(), 1);
        assert!(!loaded.findings[0].flags.contested);
    }

    #[test]
    fn applied_proposal_emits_event_and_stales_proof() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let mut frontier = project::assemble("test", vec![finding("vf_test")], 0, 0, "test");
        record_proof_export(
            &mut frontier,
            ProofPacketRecord {
                generated_at: "2026-04-23T00:00:00Z".to_string(),
                snapshot_hash: "a".repeat(64),
                event_log_hash: "b".repeat(64),
                packet_manifest_hash: "c".repeat(64),
            },
        );
        repo::save_to_path(&path, &frontier).unwrap();
        let proposal = new_proposal(
            "finding.review",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test".to_string(),
            },
            "reviewer:test",
            "human",
            "Mouse-only evidence",
            json!({"status": "contested"}),
            Vec::new(),
            Vec::new(),
        );
        create_or_apply(&path, proposal, true).unwrap();
        let loaded = repo::load_from_path(&path).unwrap();
        assert_eq!(loaded.events.len(), 2); // genesis + applied
        assert!(loaded.findings[0].flags.contested);
        assert_eq!(loaded.proposals[0].status, "applied");
        assert_eq!(loaded.proof_state.latest_packet.status, "stale");
    }

    #[test]
    fn preview_reports_changed_objects_and_event_kind_without_mutation() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let frontier = project::assemble("test", vec![finding("vf_test")], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();
        let proposal = new_proposal(
            "finding.review",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test".to_string(),
            },
            "reviewer:test",
            "human",
            "Mouse-only evidence",
            json!({"status": "contested"}),
            Vec::new(),
            Vec::new(),
        );
        let proposal_id = create_or_apply(&path, proposal, false).unwrap().proposal_id;

        let preview = preview_at_path(&path, &proposal_id, "reviewer:test").unwrap();

        assert_eq!(preview.changed_findings, vec!["vf_test"]);
        assert!(preview.changed_artifacts.is_empty());
        assert_eq!(preview.event_kinds, vec!["finding.reviewed"]);
        assert_eq!(
            preview.new_event_ids,
            vec![preview.applied_event_id.clone()]
        );
        assert_eq!(preview.events_delta, 1);
        let loaded = repo::load_from_path(&path).unwrap();
        assert_eq!(loaded.events.len(), 1, "preview must not mutate events");
        assert_eq!(
            loaded.proposals[0].status, "pending_review",
            "preview must not accept the proposal"
        );
    }

    #[test]
    fn pending_note_proposal_does_not_mutate_annotations() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let frontier = project::assemble("test", vec![finding("vf_test")], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();
        let proposal = new_proposal(
            "finding.note",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test".to_string(),
            },
            "reviewer:test",
            "human",
            "Track mouse-only evidence",
            json!({"text": "Track mouse-only evidence"}),
            Vec::new(),
            Vec::new(),
        );
        create_or_apply(&path, proposal, false).unwrap();
        let loaded = repo::load_from_path(&path).unwrap();
        assert_eq!(loaded.events.len(), 1); // genesis only
        assert_eq!(loaded.proposals.len(), 1);
        assert!(loaded.findings[0].annotations.is_empty());
        assert_eq!(loaded.proposals[0].kind, "finding.note");
    }

    #[test]
    fn applied_note_emits_noted_event_and_stales_proof() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let mut frontier = project::assemble("test", vec![finding("vf_test")], 0, 0, "test");
        record_proof_export(
            &mut frontier,
            ProofPacketRecord {
                generated_at: "2026-04-23T00:00:00Z".to_string(),
                snapshot_hash: "a".repeat(64),
                event_log_hash: "b".repeat(64),
                packet_manifest_hash: "c".repeat(64),
            },
        );
        repo::save_to_path(&path, &frontier).unwrap();
        let proposal = new_proposal(
            "finding.note",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test".to_string(),
            },
            "reviewer:test",
            "human",
            "Track mouse-only evidence",
            json!({"text": "Track mouse-only evidence"}),
            Vec::new(),
            Vec::new(),
        );
        let result = create_or_apply(&path, proposal, true).unwrap();
        let loaded = repo::load_from_path(&path).unwrap();
        assert_eq!(loaded.events.len(), 2); // genesis + finding.noted
        assert_eq!(loaded.events[1].kind, "finding.noted");
        assert_eq!(loaded.findings[0].annotations.len(), 1);
        assert_eq!(loaded.proposals[0].status, "applied");
        assert_eq!(
            loaded.proposals[0].applied_event_id,
            result.applied_event_id
        );
        assert_eq!(loaded.proof_state.latest_packet.status, "stale");
    }

    #[test]
    fn retract_emits_per_dependent_cascade_events() {
        // Phase L: a retraction must emit one canonical
        // `finding.dependency_invalidated` event per affected dependent
        // in BFS depth order. Build a tiny dependency chain:
        //   src  <-supports- dep1  <-depends- dep2
        // and assert that retracting `src` produces three events:
        // [retracted(src), dep_invalidated(dep1, depth=1),
        //  dep_invalidated(dep2, depth=2)] all carrying the source's
        // canonical event ID as `upstream_event_id`.
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let mut src = finding("vf_src");
        let mut dep1 = finding("vf_dep1");
        let mut dep2 = finding("vf_dep2");
        src.assertion.text = "src finding".into();
        dep1.assertion.text = "dep1 finding".into();
        dep2.assertion.text = "dep2 finding".into();
        // BFS edges flow from dependent → upstream via `target`.
        dep1.add_link("vf_src", "supports", "");
        dep2.add_link("vf_dep1", "depends", "");
        let frontier = project::assemble("test", vec![src, dep1, dep2], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();

        let proposal = new_proposal(
            "finding.retract",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_src".to_string(),
            },
            "reviewer:test",
            "human",
            "Source paper retracted by publisher",
            json!({}),
            Vec::new(),
            Vec::new(),
        );
        create_or_apply(&path, proposal, true).unwrap();
        let loaded = repo::load_from_path(&path).unwrap();

        // genesis + 1 source retract + 2 cascade events = 4 total.
        assert_eq!(loaded.events.len(), 4, "{:?}", loaded.events);
        let kinds: Vec<&str> = loaded.events.iter().map(|e| e.kind.as_str()).collect();
        assert_eq!(kinds[0], "frontier.created");
        assert_eq!(kinds[1], "finding.retracted");
        assert_eq!(kinds[2], "finding.dependency_invalidated");
        assert_eq!(kinds[3], "finding.dependency_invalidated");

        let source_event_id = loaded.events[1].id.clone();
        let dep1_event = &loaded.events[2];
        let dep2_event = &loaded.events[3];
        assert_eq!(dep1_event.target.id, "vf_dep1");
        assert_eq!(dep2_event.target.id, "vf_dep2");
        assert_eq!(
            dep1_event
                .payload
                .get("upstream_event_id")
                .and_then(|v| v.as_str()),
            Some(source_event_id.as_str())
        );
        assert_eq!(
            dep1_event.payload.get("depth").and_then(|v| v.as_u64()),
            Some(1)
        );
        assert_eq!(
            dep2_event.payload.get("depth").and_then(|v| v.as_u64()),
            Some(2)
        );
        // Both dependents must end up contested in materialized state.
        let dep1 = loaded.findings.iter().find(|f| f.id == "vf_dep1").unwrap();
        let dep2 = loaded.findings.iter().find(|f| f.id == "vf_dep2").unwrap();
        assert!(dep1.flags.contested);
        assert!(dep2.flags.contested);
        let src = loaded.findings.iter().find(|f| f.id == "vf_src").unwrap();
        assert!(src.flags.retracted);
    }

    #[test]
    fn proposal_id_is_content_addressed_independent_of_created_at() {
        // Phase P (v0.5): identical logical proposals constructed at different
        // times must produce the same `vpr_…`. This is the substrate property
        // that makes agent retries idempotent.
        let target = StateTarget {
            r#type: "finding".to_string(),
            id: "vf_test".to_string(),
        };
        let mut a = new_proposal(
            "finding.review",
            target.clone(),
            "reviewer:test",
            "human",
            "scope narrower than claim",
            json!({"status": "contested"}),
            Vec::new(),
            Vec::new(),
        );
        let mut b = new_proposal(
            "finding.review",
            target,
            "reviewer:test",
            "human",
            "scope narrower than claim",
            json!({"status": "contested"}),
            Vec::new(),
            Vec::new(),
        );
        // Force divergent timestamps; the IDs must still match.
        a.created_at = "2026-04-25T00:00:00Z".to_string();
        b.created_at = "2026-09-12T17:32:00Z".to_string();
        a.id = proposal_id(&a);
        b.id = proposal_id(&b);
        assert_eq!(a.id, b.id, "vpr_… must not depend on created_at");
    }

    #[test]
    fn create_or_apply_is_idempotent_under_repeated_calls() {
        // Phase P: invoking create_or_apply twice with identical content must
        // not duplicate the proposal nor emit two events. The second call
        // returns the same proposal_id and applied_event_id as the first.
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let frontier = project::assemble("test", vec![finding("vf_test")], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();

        let make = || {
            new_proposal(
                "finding.review",
                StateTarget {
                    r#type: "finding".to_string(),
                    id: "vf_test".to_string(),
                },
                "reviewer:test",
                "human",
                "agent retry test",
                json!({"status": "contested"}),
                Vec::new(),
                Vec::new(),
            )
        };

        let first = create_or_apply(&path, make(), true).unwrap();
        let second = create_or_apply(&path, make(), true).unwrap();

        assert_eq!(first.proposal_id, second.proposal_id);
        assert_eq!(first.applied_event_id, second.applied_event_id);

        let loaded = repo::load_from_path(&path).unwrap();
        assert_eq!(
            loaded.proposals.len(),
            1,
            "second create_or_apply must not insert a duplicate proposal"
        );
        // genesis + 1 applied review event = 2; not 3.
        assert_eq!(
            loaded.events.len(),
            2,
            "second create_or_apply must not emit a duplicate event"
        );
    }

    #[test]
    fn accepting_applied_proposal_is_idempotent() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let frontier = project::assemble("test", vec![finding("vf_test")], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();
        let proposal = new_proposal(
            "finding.review",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test".to_string(),
            },
            "reviewer:test",
            "human",
            "Mouse-only evidence",
            json!({"status": "contested"}),
            Vec::new(),
            Vec::new(),
        );
        let created = create_or_apply(&path, proposal, true).unwrap();
        let first_event = created.applied_event_id.clone().unwrap();
        let second_event =
            accept_at_path(&path, &created.proposal_id, "reviewer:test", "same").unwrap();
        assert_eq!(first_event, second_event);
    }

    #[test]
    fn v0_13_apply_materializes_source_records_inline() {
        // Pre-v0.13: vela check --strict on a CLI-built frontier flagged
        // `missing_source_record` because source_records weren't populated
        // until vela normalize --write — and normalize refuses on event-ful
        // frontiers. v0.13 materializes inline at apply time so source_records
        // grow in lockstep with findings.
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let mut frontier = project::assemble("test", vec![], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();
        // Add a finding via the standard finding.add proposal flow.
        let f = finding("vf_v013_inline_src");
        let proposal = new_proposal(
            "finding.add",
            StateTarget {
                r#type: "finding".to_string(),
                id: f.id.clone(),
            },
            "reviewer:test",
            "human",
            "Manual finding for v0.13 source-record materialization test",
            json!({"finding": f}),
            Vec::new(),
            Vec::new(),
        );
        create_or_apply(&path, proposal, true).unwrap();
        let loaded = repo::load_from_path(&path).unwrap();
        // Source records, evidence atoms, and condition records should all
        // be materialized — without any explicit normalize call.
        assert!(
            !loaded.sources.is_empty(),
            "v0.13: source_records should materialize inline at apply time"
        );
        assert!(
            !loaded.evidence_atoms.is_empty(),
            "v0.13: evidence_atoms should materialize inline at apply time"
        );
        assert!(
            !loaded.condition_records.is_empty(),
            "v0.13: condition_records should materialize inline at apply time"
        );
        // Sanity: stats reflect the new source registry.
        assert_eq!(loaded.stats.source_count, loaded.sources.len());
        // Suppress unused-mut warning when frontier isn't reused below.
        let _ = &mut frontier;
    }

    fn make_supersede_payload(old_id: &str, new_text: &str) -> (FindingBundle, Value) {
        let mut new_finding = finding("vf_supersede_new");
        new_finding.assertion.text = new_text.to_string();
        // Re-derive id from the new assertion text + provenance. For the
        // test we just hand-pick a distinct id; the real CLI uses
        // `build_finding_bundle` which content-addresses correctly.
        new_finding.id = format!(
            "vf_{:0>16}",
            old_id
                .bytes()
                .fold(0u64, |acc, b| acc.wrapping_add(b as u64))
        );
        let payload = json!({"new_finding": new_finding.clone()});
        (new_finding, payload)
    }

    #[test]
    fn v0_14_supersede_creates_new_finding_and_marks_old() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let mut frontier = project::assemble("test", vec![finding("vf_old")], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();
        let (new_finding, payload) = make_supersede_payload("vf_old", "Newer claim");
        let proposal = new_proposal(
            "finding.supersede",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_old".to_string(),
            },
            "reviewer:test",
            "human",
            "Newer evidence updates the wording",
            payload,
            Vec::new(),
            Vec::new(),
        );
        let result = create_or_apply(&path, proposal, true).unwrap();
        assert!(result.applied_event_id.is_some());
        let loaded = repo::load_from_path(&path).unwrap();
        // Old finding now flagged superseded.
        let old = loaded.findings.iter().find(|f| f.id == "vf_old").unwrap();
        assert!(
            old.flags.superseded,
            "old finding should be flagged superseded"
        );
        // New finding present, with auto-injected supersedes link back to old.
        let new_f = loaded
            .findings
            .iter()
            .find(|f| f.id == new_finding.id)
            .expect("new finding should be in frontier");
        assert!(
            new_f
                .links
                .iter()
                .any(|l| l.target == "vf_old" && l.link_type == "supersedes"),
            "new finding should have an auto-injected supersedes link to old finding"
        );
        // Event with kind finding.superseded targeting old, payload carries new_finding_id.
        let supersede_event = loaded
            .events
            .iter()
            .find(|e| e.kind == "finding.superseded")
            .expect("a finding.superseded event should be emitted");
        assert_eq!(supersede_event.target.id, "vf_old");
        assert_eq!(
            supersede_event.payload["new_finding_id"].as_str(),
            Some(new_finding.id.as_str())
        );
        // suppress unused warning
        let _ = &mut frontier;
    }

    #[test]
    fn v0_14_supersede_refuses_already_superseded() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let mut old = finding("vf_already_done");
        old.flags.superseded = true;
        let frontier = project::assemble("test", vec![old], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();
        let (_, payload) = make_supersede_payload("vf_already_done", "Newer wording");
        let proposal = new_proposal(
            "finding.supersede",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_already_done".to_string(),
            },
            "reviewer:test",
            "human",
            "Attempt to double-supersede",
            payload,
            Vec::new(),
            Vec::new(),
        );
        let result = create_or_apply(&path, proposal, true);
        assert!(
            result.is_err(),
            "double-supersede should be refused; got {result:?}"
        );
    }

    #[test]
    fn v0_14_supersede_refuses_same_content_address() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("frontier.json");
        let frontier = project::assemble("test", vec![finding("vf_same")], 0, 0, "test");
        repo::save_to_path(&path, &frontier).unwrap();
        // new_finding.id == target.id should be refused at validate-time.
        let mut new_finding = finding("vf_same");
        new_finding.assertion.text = "Different text but reused id".to_string();
        let proposal = new_proposal(
            "finding.supersede",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_same".to_string(),
            },
            "reviewer:test",
            "human",
            "Same id, should fail",
            json!({"new_finding": new_finding}),
            Vec::new(),
            Vec::new(),
        );
        let result = create_or_apply(&path, proposal, true);
        assert!(
            result.is_err(),
            "supersede with same content address should be refused; got {result:?}"
        );
    }

    /// v0.22 byte-stability: a proposal with `agent_run = None`
    /// must serialize without an `agent_run` field, so existing
    /// frontiers (none of which have agent_run today) round-trip
    /// byte-identically. The whole substrate guarantee depends on
    /// canonical-JSON not silently gaining new keys.
    #[test]
    fn agent_run_none_skips_serialization() {
        let p = new_proposal(
            "finding.add",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test0000000000".to_string(),
            },
            "reviewer:will-blair",
            "human",
            "test",
            json!({}),
            Vec::new(),
            Vec::new(),
        );
        let bytes = canonical::to_canonical_bytes(&p).unwrap();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(
            !s.contains("agent_run"),
            "proposal without agent_run leaked the field into canonical JSON: {s}"
        );
    }

    /// And when `agent_run` *is* set, the same proposal id is
    /// produced regardless — `proposal_id`'s preimage explicitly
    /// excludes agent_run, so attaching provenance never changes
    /// the content address.
    #[test]
    fn agent_run_does_not_change_proposal_id() {
        let bare = new_proposal(
            "finding.add",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test0000000000".to_string(),
            },
            "agent:literature-scout",
            "agent",
            "scout extracted this from paper_014",
            json!({}),
            vec!["src_paper_014".to_string()],
            Vec::new(),
        );
        let id_bare = bare.id.clone();

        let mut with_run = bare.clone();
        with_run.agent_run = Some(AgentRun {
            agent: "literature-scout".to_string(),
            model: "claude-opus-4-7".to_string(),
            run_id: "vrun_abc1234567890def".to_string(),
            started_at: "2026-04-26T01:23:45Z".to_string(),
            finished_at: Some("2026-04-26T01:24:10Z".to_string()),
            context: BTreeMap::from([
                ("input_folder".to_string(), "./papers".to_string()),
                ("pdf_count".to_string(), "12".to_string()),
            ]),
            tool_calls: Vec::new(),
            permissions: None,
        });
        let id_with_run = proposal_id(&with_run);
        assert_eq!(
            id_bare, id_with_run,
            "agent_run leaked into proposal_id preimage"
        );
    }

    /// v0.49 byte-stability: tool_calls and permissions on AgentRun
    /// must skip serialization when empty/None, so existing frontiers
    /// (none of which carry these fields today) round-trip byte-
    /// identically through canonical JSON. Same invariant as
    /// agent_run itself in v0.22.
    #[test]
    fn agent_run_empty_tool_calls_and_permissions_skip_serialization() {
        let p = new_proposal(
            "finding.add",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test0000000000".to_string(),
            },
            "agent:scout",
            "agent",
            "test",
            json!({}),
            Vec::new(),
            Vec::new(),
        );
        let mut with_run = p.clone();
        with_run.agent_run = Some(AgentRun {
            agent: "scout".to_string(),
            model: "claude-opus-4-7".to_string(),
            run_id: "vrun_x".to_string(),
            started_at: "2026-04-26T01:00:00Z".to_string(),
            finished_at: None,
            context: BTreeMap::new(),
            tool_calls: Vec::new(),
            permissions: None,
        });
        let bytes = canonical::to_canonical_bytes(&with_run).unwrap();
        let s = std::str::from_utf8(&bytes).unwrap();
        assert!(
            !s.contains("tool_calls"),
            "empty tool_calls leaked into canonical JSON: {s}"
        );
        assert!(
            !s.contains("permissions"),
            "empty permissions leaked into canonical JSON: {s}"
        );
    }

    /// v0.49: when populated, tool_calls and permissions DO serialize
    /// — this is the round-trip we want for new agent runs that
    /// actually carry tool traces.
    #[test]
    fn agent_run_populated_tool_calls_and_permissions_roundtrip() {
        let mut p = new_proposal(
            "finding.add",
            StateTarget {
                r#type: "finding".to_string(),
                id: "vf_test0000000000".to_string(),
            },
            "agent:scout",
            "agent",
            "test",
            json!({}),
            Vec::new(),
            Vec::new(),
        );
        p.agent_run = Some(AgentRun {
            agent: "scout".to_string(),
            model: "claude-opus-4-7".to_string(),
            run_id: "vrun_x".to_string(),
            started_at: "2026-04-26T01:00:00Z".to_string(),
            finished_at: None,
            context: BTreeMap::new(),
            tool_calls: vec![
                ToolCallTrace {
                    tool: "pubmed_search".to_string(),
                    input_sha256: "a".repeat(64),
                    output_sha256: Some("b".repeat(64)),
                    at: "2026-04-26T01:00:05Z".to_string(),
                    duration_ms: Some(842),
                    status: "ok".to_string(),
                    error_message: String::new(),
                },
                // v0.49: a failed tool call with an explanatory
                // error_message — the field a reviewer needs to audit
                // what went wrong without re-running the agent.
                ToolCallTrace {
                    tool: "arxiv_fetch".to_string(),
                    input_sha256: "c".repeat(64),
                    output_sha256: None,
                    at: "2026-04-26T01:00:18Z".to_string(),
                    duration_ms: Some(1200),
                    status: "error".to_string(),
                    error_message: "HTTP 503 from arxiv.org; retry budget exhausted".to_string(),
                },
            ],
            permissions: Some(PermissionState {
                data_access: vec!["pubmed:".to_string(), "frontier:vfr_bd91".to_string()],
                tool_access: vec!["pubmed_search".to_string(), "arxiv_fetch".to_string()],
                note: "read-only access to BBB Flagship".to_string(),
            }),
        });
        let bytes = canonical::to_canonical_bytes(&p).unwrap();
        let json: serde_json::Value =
            serde_json::from_slice(&bytes).expect("canonical bytes round-trip");
        assert_eq!(
            json["agent_run"]["tool_calls"][0]["tool"], "pubmed_search",
            "tool_calls did not survive the round trip: {json}"
        );
        assert_eq!(
            json["agent_run"]["permissions"]["data_access"][0], "pubmed:",
            "permissions did not survive the round trip: {json}"
        );
        // v0.49: a failed tool call with error_message carries the
        // explanation through canonical JSON. A reviewer can audit
        // exactly what failed without rerunning the agent.
        assert_eq!(
            json["agent_run"]["tool_calls"][1]["status"], "error",
            "failed tool call status did not survive: {json}"
        );
        assert_eq!(
            json["agent_run"]["tool_calls"][1]["error_message"],
            "HTTP 503 from arxiv.org; retry budget exhausted",
            "error_message did not survive the round trip: {json}"
        );
        // ...and successful calls still don't leak an empty
        // error_message into canonical bytes.
        let raw = std::str::from_utf8(&bytes).unwrap();
        let okay_call_block_end = raw.find("pubmed_search").unwrap();
        let until_first_call = &raw[..okay_call_block_end + 200];
        assert!(
            !until_first_call.contains("\"error_message\":\"\""),
            "successful tool call leaked an empty error_message: {until_first_call}"
        );
    }
}