car-server-core 0.52.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
//! Disk-backed run-trace store (agent run tracing, U3).
//!
//! Persists the per-run trace stream — the `RunStarted` line, each
//! `RunTurn`, then the terminal `RunEnded`/`Incomplete` — as JSONL so a
//! run survives daemon restarts and stays grouped by run independent of
//! the WS connection that produced it (R4). One file per run:
//!
//! ```text
//! ~/.car/runs/{agent_id}/{run_id}.jsonl
//! ```
//!
//! ## Source-of-truth split
//!
//! This disk store is the source of truth for **replay** (U5):
//! [`RunStore::get_run_trace_page_for`] / [`RunStore::list_runs_page`] read it
//! and work after a restart when memory is empty. The in-memory
//! `RunMeta.turns` buffer (U2) stays the source for the **live** stream
//! (U4) — U3 does not remove it; it mirrors what was recorded onto disk.
//!
//! ## Layout, perms, backup exclusion (R14)
//!
//! Prompts and CLI output may carry secrets, so the `runs/` tree is
//! created `0700` and every file `0600` (Unix). The `runs/` dir is
//! marked backup-excluded — a `.nobackup` marker file plus, on macOS,
//! the `com.apple.metadata:com_apple_backup_excludeItem` xattr — so Time
//! Machine / iCloud don't silently copy plaintext traces off the box.
//!
//! ## Index
//!
//! Each agent has a fixed-record newest-first summary index plus one small
//! summary sidecar per run. `runs.list` seeks directly to its requested page;
//! it never scans every run file. The JSONL trace remains authoritative and
//! startup GC rebuilds the derived index/sidecars so interrupted updates are
//! repaired before the daemon listens. `run_id -> agent_id` resolves by
//! scanning `runs/*/` for the matching `{run_id}.jsonl` (U5's
//! `runs.get_trace` takes only a `run_id`).
//!
//! ## Retention (R6)
//!
//! GC runs on daemon boot ([`RunStore::gc`]): per agent it keeps the **50
//! most recent completed runs** and drops anything older than **30 days**,
//! whichever is more restrictive. A still-in-progress run (no terminal
//! record) is **never** evicted. Both limits are configurable via
//! `~/.car/config.toml` (`[runs] max_per_agent` / `max_age_days`) with
//! that restrictive default.
//!
//! Records are appended at turn granularity (not per token) — the same
//! coarse boundary the in-memory buffer uses. A corrupt/partial trailing
//! JSONL line loads the prior valid records rather than failing the whole
//! run (the error-path test).

use car_ir::{ActionProposal, ProposalLineageStatus, ProposalResult};
use car_proto::{RunRecord, RunTermination};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::{HashMap, VecDeque};
use std::fs::File;
use std::io::{BufRead, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex, Weak};

#[cfg(not(target_os = "windows"))]
fn sync_directory(path: impl AsRef<Path>) -> std::io::Result<()> {
    File::open(path)?.sync_all()
}

#[cfg(target_os = "windows")]
fn sync_directory(_path: impl AsRef<Path>) -> std::io::Result<()> {
    // Windows FlushFileBuffers rejects directory handles with
    // ERROR_ACCESS_DENIED. File contents are synchronized before each call;
    // there is no supported directory-fsync equivalent to add here.
    Ok(())
}

const COMPLETED_PROPOSAL_OWNER_INDEX_MIGRATION_VERSION: u32 = 2;
const RUN_SUMMARY_KEY_BYTES: usize = 32;
const RUN_SUMMARY_INDEX_RECORD_BYTES: usize = 8 + RUN_SUMMARY_KEY_BYTES;
const RUN_SUMMARY_INDEX_FILE: &str = ".run-summary-index-v2";
const RUN_SUMMARY_SIDECAR_DIR: &str = ".run-summaries-v2";
const RUN_TRACE_CORRUPTION_SIDECAR_DIR: &str = ".run-trace-corruption-v1";
#[cfg(not(test))]
const MAX_RESUMED_PROPOSAL_RECEIPTS_PER_RUN: usize = 1024;
#[cfg(test)]
const MAX_RESUMED_PROPOSAL_RECEIPTS_PER_RUN: usize = 4;
#[cfg(not(test))]
const MAX_RESUMED_PROPOSAL_RECEIPT_BYTES_PER_RUN: u64 = 16 * 1024 * 1024;
#[cfg(test)]
const MAX_RESUMED_PROPOSAL_RECEIPT_BYTES_PER_RUN: u64 = 64 * 1024;

#[derive(Debug, Serialize, Deserialize)]
struct CompletedProposalOwnerIndexMigration {
    version: u32,
}

/// Default per-agent cap: keep the 50 most recent completed runs.
pub const DEFAULT_MAX_RUNS_PER_AGENT: usize = 50;
/// Default age cap: drop completed runs older than 30 days.
pub const DEFAULT_MAX_AGE_DAYS: i64 = 30;

/// Terminal/in-progress status of a run, derived from its records.
///
/// Distinct from the run-level `OutcomeStatus` carried inside a terminal
/// `Outcome` — this is the coarse "what state is this run in?" the run
/// list renders. `Incomplete` is the orphan case (no terminal record + no
/// live harness, R5); `InProgress` is a run still being written.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunStatus {
    /// No terminal record yet — still being written by a live harness.
    InProgress,
    /// `runs.complete` reported a terminal `AgentOutcome`. The concrete
    /// `OutcomeStatus` lives on the `RunEnded` record itself.
    Completed,
    /// CAR confirmed controlled work stopped and committed cancellation.
    Cancelled,
    /// The harness disconnected without reporting an outcome (R5).
    Incomplete,
    /// A durable cancellation request exists without a terminal boundary.
    CancellationPending,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunTraceCorruptionKind {
    MalformedRecord,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunTraceCorruption {
    pub kind: RunTraceCorruptionKind,
    /// One-based JSONL line number.
    pub line: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct RunTraceCorruptionMarker {
    run_id: String,
    agent_id: String,
    corruption: RunTraceCorruption,
}

/// One row of [`RunStore::list_runs`] — the summary U5's `runs.list`
/// returns. Persisted in a sidecar so bounded listing never loads every turn.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunSummary {
    pub run_id: String,
    pub agent_id: String,
    pub intent: String,
    pub started_at: DateTime<Utc>,
    /// When the terminal record was written, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ended_at: Option<DateTime<Utc>>,
    pub status: RunStatus,
    /// Number of `RunTurn` records persisted for this run.
    pub turn_count: usize,
    /// Immutable per-agent keyset used by bounded newest-first pagination.
    /// Zero is reserved for legacy sidecars that startup has not migrated yet.
    #[serde(default)]
    pub sequence: u64,
    /// Present only when a durable newline-terminated record is malformed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trace_corruption: Option<RunTraceCorruption>,
}

/// Durable preimage for a proposal whose actions already finished but whose
/// `proposal_completed` journal boundary has not yet been acknowledged.
///
/// The payload is deliberately server-owned instead of a `car_proto` run row:
/// it is an outbox transaction, not part of the public run trace. Keeping the
/// exact normal-serde result and its JCS digest lets a retry or daemon restart
/// finish the terminal without dispatching an action twice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PendingProposalFinalization {
    pub run_id: String,
    pub client_id: String,
    /// Exact caller-selected policy context. This is kept separately from
    /// `policy_session_id`: an unknown session is deliberately not trusted or
    /// journaled, but an exact retry must still present the same context.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_policy_session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_session_id: Option<String>,
    pub original_proposal_id: String,
    pub final_proposal_id: String,
    /// Exact caller-supplied JSON before serde fills defaults. This recognizes
    /// an exact retry even when an omitted timestamp is regenerated on decode.
    pub original_submission: Value,
    /// Exact normal-serde proposal CAR accepted and journaled.
    pub original_proposal: ActionProposal,
    /// Exact normal-serde proposal selected by the runtime. This duplicates
    /// the active-v3 `ProposalResult.final_proposal` intentionally: validator
    /// equality makes an outbox edit or partial producer upgrade fail closed.
    pub final_proposal: ActionProposal,
    /// Generation-keyed normal-serde preimages for every accepted lineage
    /// entry, including generation zero when it was admitted.
    #[serde(default)]
    pub accepted_proposal_preimages: Vec<AcceptedProposalPreimage>,
    #[serde(deserialize_with = "deserialize_active_proposal_result")]
    pub proposal_result: ProposalResult,
    pub result_digest: String,
}

/// Durable exact response retained after `proposal_completed` is fsynced.
///
/// Unlike the finalization outbox, this receipt intentionally survives guard
/// cleanup. A same-bound-session retry can therefore recover the typed result
/// without dispatch even if the original JSON-RPC response was lost, guard
/// unlink/fsync failed, or run-trace retention later removed `RunStarted`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CompletedProposalResponse {
    pub finalization: PendingProposalFinalization,
}

/// Content-addressed ownership claim for the retry tuple used before a live
/// run is selected. The claim is deliberately independent of the run trace:
/// completed responses outlive trace retention, and an ownership lookup must
/// read at most this one exact file rather than enumerate every receipt.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct CompletedProposalOwnership {
    run_id: String,
    client_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    requested_policy_session_id: Option<String>,
    original_submission: Value,
}

impl CompletedProposalOwnership {
    fn new(
        run_id: &str,
        client_id: &str,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> Self {
        Self {
            run_id: run_id.to_string(),
            client_id: client_id.to_string(),
            requested_policy_session_id: requested_policy_session_id.map(str::to_string),
            original_submission: original_submission.clone(),
        }
    }
}

/// Result of atomically reserving one proposal retry tuple before dispatch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProposalRetryReservation {
    Acquired,
    Existing { run_id: String, client_id: String },
}

/// Durable rollback authority written before a retry owner is reserved.
///
/// If the daemon exits before the execution marker is durable, startup uses
/// this exact preimage to release the owner. Once a marker exists, the marker
/// remains the conservative outcome-unknown guard and startup only removes the
/// stale rollback intent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalRetryRollback {
    pub run_id: String,
    pub client_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_policy_session_id: Option<String>,
    pub original_submission: Value,
}

impl ProposalRetryRollback {
    fn validate(&self) -> std::io::Result<()> {
        if self.run_id.is_empty()
            || self.client_id.is_empty()
            || self.requested_policy_session_id.as_deref() == Some("")
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proposal retry rollback requires non-empty run/client/policy identities",
            ));
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct ProposalIdClaim {
    run_id: String,
    client_id: String,
    proposal_id: String,
    original_submission: Value,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProposalIdClaimOutcome {
    Acquired,
    ExistingExact,
}

impl CompletedProposalResponse {
    pub fn proposal_result(&self) -> &ProposalResult {
        &self.finalization.proposal_result
    }

    fn validate(&self) -> std::io::Result<()> {
        self.finalization.validate()
    }

    fn execution_marker(&self) -> std::io::Result<ProposalExecutionMarker> {
        let pending = &self.finalization;
        let original_proposal = serde_json::to_value(&pending.original_proposal)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        let marker = ProposalExecutionMarker {
            run_id: pending.run_id.clone(),
            client_id: pending.client_id.clone(),
            requested_policy_session_id: pending.requested_policy_session_id.clone(),
            policy_session_id: pending.policy_session_id.clone(),
            original_proposal_id: pending.original_proposal_id.clone(),
            original_submission: pending.original_submission.clone(),
            original_proposal,
            proposal_digest: proposal_digest(&pending.original_proposal)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?,
        };
        marker.validate()?;
        Ok(marker)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AcceptedProposalPreimage {
    pub generation: u32,
    pub proposal: ActionProposal,
}

fn deserialize_active_proposal_result<'de, D>(deserializer: D) -> Result<ProposalResult, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Value::deserialize(deserializer)?;
    let object = value
        .as_object()
        .ok_or_else(|| serde::de::Error::custom("proposal_result must be an object"))?;
    for field in [
        "proposal_id",
        "original_proposal_id",
        "final_proposal",
        "replan_lineage",
        "results",
        "cost",
    ] {
        if !object.contains_key(field) {
            return Err(serde::de::Error::custom(format!(
                "active v3 proposal_result is missing `{field}`"
            )));
        }
    }
    serde_json::from_value(value).map_err(serde::de::Error::custom)
}

fn is_lowercase_sha256(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}

fn proposal_digest(proposal: &ActionProposal) -> Result<String, String> {
    let value = serde_json::to_value(proposal).map_err(|error| error.to_string())?;
    let canonical = car_inference::catalog_identity::canonical_json(&value)?;
    Ok(format!("{:x}", Sha256::digest(canonical.as_bytes())))
}

fn validate_original_submission(
    submission: &Value,
    proposal: &ActionProposal,
) -> std::io::Result<()> {
    let invalid = |message: String| std::io::Error::new(std::io::ErrorKind::InvalidData, message);
    let object = submission.as_object().ok_or_else(|| {
        invalid("active proposal original submission must be an object".to_string())
    })?;
    if object.get("id").and_then(Value::as_str) != Some(proposal.id.as_str()) {
        return Err(invalid(
            "active proposal raw submission requires an exact string id".to_string(),
        ));
    }
    let raw_actions = object.get("actions").ok_or_else(|| {
        invalid("active proposal raw submission is missing its action array".to_string())
    })?;
    let actions: Vec<car_ir::Action> = serde_json::from_value(raw_actions.clone())
        .map_err(|error| invalid(format!("raw submission actions are invalid: {error}")))?;
    if actions != proposal.actions {
        return Err(invalid(
            "raw submission actions do not match the accepted normal-serde proposal".to_string(),
        ));
    }
    if object
        .get("source")
        .is_some_and(|source| source.as_str() != Some(proposal.source.as_str()))
    {
        return Err(invalid(
            "raw submission source does not match the accepted proposal".to_string(),
        ));
    }
    if let Some(context) = object.get("context") {
        let context: HashMap<String, Value> = serde_json::from_value(context.clone())
            .map_err(|error| invalid(format!("raw submission context is invalid: {error}")))?;
        if context != proposal.context {
            return Err(invalid(
                "raw submission context does not match the accepted proposal".to_string(),
            ));
        }
    }
    if let Some(timestamp) = object.get("timestamp") {
        let timestamp: DateTime<Utc> = serde_json::from_value(timestamp.clone())
            .map_err(|error| invalid(format!("raw submission timestamp is invalid: {error}")))?;
        if timestamp != proposal.timestamp {
            return Err(invalid(
                "raw submission timestamp does not match the accepted proposal".to_string(),
            ));
        }
    }
    Ok(())
}

/// Fsynced before runtime dispatch. If CAR restarts with this marker and no
/// exact finalization payload, the action outcome is unknown: the server must
/// quarantine the run instead of guessing that redispatch is safe.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalExecutionMarker {
    pub run_id: String,
    pub client_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_policy_session_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_session_id: Option<String>,
    pub original_proposal_id: String,
    pub original_submission: Value,
    pub original_proposal: Value,
    pub proposal_digest: String,
}

impl ProposalExecutionMarker {
    pub fn validate(&self) -> std::io::Result<()> {
        let invalid =
            |message: String| std::io::Error::new(std::io::ErrorKind::InvalidData, message);
        if self.run_id.is_empty()
            || self.client_id.is_empty()
            || self.original_proposal_id.is_empty()
        {
            return Err(invalid(
                "proposal execution marker requires non-empty run/client/proposal identities"
                    .to_string(),
            ));
        }
        if self.policy_session_id.is_some()
            && self.policy_session_id != self.requested_policy_session_id
        {
            return Err(invalid(
                "authenticated policy session is not the caller-requested policy session"
                    .to_string(),
            ));
        }
        let proposal: ActionProposal = serde_json::from_value(self.original_proposal.clone())
            .map_err(|error| invalid(format!("execution marker proposal is invalid: {error}")))?;
        if proposal.id != self.original_proposal_id {
            return Err(invalid(
                "execution marker proposal id does not match original proposal identity"
                    .to_string(),
            ));
        }
        let digest = proposal_digest(&proposal)
            .map_err(|error| invalid(format!("execution marker proposal JCS failed: {error}")))?;
        if self.proposal_digest != digest || !is_lowercase_sha256(&self.proposal_digest) {
            return Err(invalid(
                "execution marker digest does not bind its exact proposal preimage".to_string(),
            ));
        }
        validate_original_submission(&self.original_submission, &proposal)
    }
}

impl PendingProposalFinalization {
    pub fn validate(&self) -> std::io::Result<()> {
        let invalid =
            |message: String| std::io::Error::new(std::io::ErrorKind::InvalidData, message);
        if self.run_id.is_empty()
            || self.client_id.is_empty()
            || self.original_proposal_id.is_empty()
            || self.final_proposal_id.is_empty()
        {
            return Err(invalid(
                "proposal finalization requires non-empty run/client/proposal identities"
                    .to_string(),
            ));
        }
        if self.policy_session_id.is_some()
            && self.policy_session_id != self.requested_policy_session_id
        {
            return Err(invalid(
                "authenticated pending policy session is not the requested policy session"
                    .to_string(),
            ));
        }
        if self.original_proposal.id != self.original_proposal_id
            || self.proposal_result.original_proposal_id != self.original_proposal_id
        {
            return Err(invalid(
                "proposal finalization original proposal identities do not match".to_string(),
            ));
        }
        if self.final_proposal.id != self.final_proposal_id
            || self.proposal_result.proposal_id != self.final_proposal_id
            || self.proposal_result.final_proposal.as_ref() != Some(&self.final_proposal)
        {
            return Err(invalid(
                "active v3 proposal finalization final proposal preimage/id do not match"
                    .to_string(),
            ));
        }
        validate_original_submission(&self.original_submission, &self.original_proposal)?;

        let result_value = serde_json::to_value(&self.proposal_result)
            .map_err(|error| invalid(format!("proposal result serialization failed: {error}")))?;
        let canonical = car_inference::catalog_identity::canonical_json(&result_value)
            .map_err(|error| invalid(format!("proposal result JCS failed: {error}")))?;
        let result_digest = format!("{:x}", Sha256::digest(canonical.as_bytes()));
        if self.result_digest != result_digest || !is_lowercase_sha256(&self.result_digest) {
            return Err(invalid(
                "proposal finalization result digest does not match typed result".to_string(),
            ));
        }

        let lineage = &self.proposal_result.replan_lineage;
        if lineage.is_empty() {
            return Err(invalid(
                "active v3 proposal result is missing generation-zero lineage".to_string(),
            ));
        }
        let original_digest = proposal_digest(&self.original_proposal)
            .map_err(|error| invalid(format!("original proposal JCS failed: {error}")))?;
        if lineage[0].generation != 0
            || lineage[0].proposal_id != self.original_proposal_id
            || lineage[0].proposal_digest.as_deref() != Some(original_digest.as_str())
        {
            return Err(invalid(
                "generation-zero lineage does not bind the exact original proposal preimage"
                    .to_string(),
            ));
        }
        if lineage[0].status == ProposalLineageStatus::Rejected && lineage.len() != 1 {
            return Err(invalid(
                "a generation-zero rejection cannot be followed by another generation".to_string(),
            ));
        }

        let mut accepted_by_generation = HashMap::new();
        for accepted in &self.accepted_proposal_preimages {
            if accepted_by_generation
                .insert(accepted.generation, &accepted.proposal)
                .is_some()
            {
                return Err(invalid(format!(
                    "duplicate accepted proposal preimage for generation {}",
                    accepted.generation
                )));
            }
        }
        for (index, entry) in lineage.iter().enumerate() {
            if entry.generation != u32::try_from(index).unwrap_or(u32::MAX) {
                return Err(invalid(
                    "proposal lineage generations are not contiguous from zero".to_string(),
                ));
            }
            match entry.status {
                ProposalLineageStatus::Accepted => {
                    if entry.rejection_reason.is_some() {
                        return Err(invalid(format!(
                            "accepted lineage generation {} cannot carry a rejection reason",
                            entry.generation
                        )));
                    }
                    let proposal =
                        accepted_by_generation
                            .get(&entry.generation)
                            .ok_or_else(|| {
                                invalid(format!(
                            "accepted lineage generation {} is missing its exact proposal preimage",
                            entry.generation
                        ))
                            })?;
                    let digest = proposal_digest(proposal).map_err(|error| {
                        invalid(format!(
                            "accepted proposal generation {} JCS failed: {error}",
                            entry.generation
                        ))
                    })?;
                    if proposal.id != entry.proposal_id
                        || entry.proposal_digest.as_deref() != Some(digest.as_str())
                        || !is_lowercase_sha256(&digest)
                    {
                        return Err(invalid(format!(
                            "accepted lineage generation {} does not bind its exact lowercase-JCS preimage",
                            entry.generation
                        )));
                    }
                }
                ProposalLineageStatus::Rejected => {
                    if entry
                        .rejection_reason
                        .as_deref()
                        .is_none_or(|reason| reason.trim().is_empty())
                    {
                        return Err(invalid(format!(
                            "rejected lineage generation {} is missing its exact rejection reason",
                            entry.generation
                        )));
                    }
                    if entry
                        .proposal_digest
                        .as_deref()
                        .is_some_and(|digest| !is_lowercase_sha256(digest))
                    {
                        return Err(invalid(format!(
                            "rejected lineage generation {} has an invalid proposal digest",
                            entry.generation
                        )));
                    }
                    if accepted_by_generation.contains_key(&entry.generation) {
                        return Err(invalid(format!(
                            "rejected lineage generation {} cannot carry an accepted preimage",
                            entry.generation
                        )));
                    }
                }
            }
        }
        if accepted_by_generation.len()
            != lineage
                .iter()
                .filter(|entry| entry.status == ProposalLineageStatus::Accepted)
                .count()
        {
            return Err(invalid(
                "proposal finalization contains an unbound accepted proposal preimage".to_string(),
            ));
        }

        if let Some(last_accepted) = lineage
            .iter()
            .rev()
            .find(|entry| entry.status == ProposalLineageStatus::Accepted)
        {
            let final_preimage = accepted_by_generation
                .get(&last_accepted.generation)
                .expect("accepted lineage was validated above");
            if *final_preimage != &self.final_proposal {
                return Err(invalid(
                    "most recent accepted proposal is not the active v3 final proposal".to_string(),
                ));
            }
        } else if lineage.len() != 1
            || lineage[0].status != ProposalLineageStatus::Rejected
            || self.final_proposal != self.original_proposal
        {
            return Err(invalid(
                "a result without an accepted generation must be a generation-zero rejection"
                    .to_string(),
            ));
        }

        let final_action_ids: std::collections::HashSet<_> = self
            .final_proposal
            .actions
            .iter()
            .map(|action| action.id.as_str())
            .collect();
        let result_action_ids: std::collections::HashSet<_> = self
            .proposal_result
            .results
            .iter()
            .map(|result| result.action_id.as_str())
            .collect();
        if final_action_ids.len() != self.final_proposal.actions.len()
            || result_action_ids.len() != self.proposal_result.results.len()
            || final_action_ids != result_action_ids
        {
            return Err(invalid(
                "typed proposal results do not match the final proposal action identities"
                    .to_string(),
            ));
        }
        Ok(())
    }

    fn validate_provenance(
        &self,
        started: &car_proto::RunStarted,
        marker: &ProposalExecutionMarker,
    ) -> std::io::Result<()> {
        let invalid =
            |message: String| std::io::Error::new(std::io::ErrorKind::InvalidData, message);
        let started_client = started.client_id.as_deref().ok_or_else(|| {
            invalid("durable RunStarted is missing its client identity".to_string())
        })?;
        if started.run_id != self.run_id || started_client != self.client_id {
            return Err(invalid(
                "pending run/client identity does not match durable RunStarted".to_string(),
            ));
        }
        let original_proposal = serde_json::to_value(&self.original_proposal).map_err(|error| {
            invalid(format!(
                "pending original proposal serialization failed: {error}"
            ))
        })?;
        let original_digest = proposal_digest(&self.original_proposal)
            .map_err(|error| invalid(format!("pending original proposal JCS failed: {error}")))?;
        if marker.run_id != self.run_id
            || marker.client_id != self.client_id
            || marker.requested_policy_session_id != self.requested_policy_session_id
            || marker.policy_session_id != self.policy_session_id
            || marker.original_proposal_id != self.original_proposal_id
            || marker.original_submission != self.original_submission
            || marker.original_proposal != original_proposal
            || marker.proposal_digest != original_digest
        {
            return Err(invalid(
                "pending finalization identity does not match durable execution marker".to_string(),
            ));
        }
        Ok(())
    }

    pub fn event_data(&self) -> HashMap<String, Value> {
        HashMap::from([
            (
                "original_submission_id".to_string(),
                Value::from(self.original_proposal_id.clone()),
            ),
            (
                "final_proposal_id".to_string(),
                Value::from(self.final_proposal_id.clone()),
            ),
            (
                "original_proposal".to_string(),
                serde_json::to_value(&self.original_proposal).unwrap_or(Value::Null),
            ),
            (
                "final_proposal".to_string(),
                serde_json::to_value(&self.final_proposal).unwrap_or(Value::Null),
            ),
            (
                "original_submission".to_string(),
                self.original_submission.clone(),
            ),
            (
                "replan_lineage".to_string(),
                serde_json::to_value(&self.proposal_result.replan_lineage).unwrap_or(Value::Null),
            ),
            (
                "all_succeeded".to_string(),
                Value::from(self.proposal_result.all_succeeded()),
            ),
            (
                "action_count".to_string(),
                Value::from(self.proposal_result.results.len()),
            ),
            (
                "proposal_result".to_string(),
                serde_json::to_value(&self.proposal_result).unwrap_or(Value::Null),
            ),
            (
                "result_digest".to_string(),
                Value::from(self.result_digest.clone()),
            ),
        ])
    }
}

/// Retention policy for the run store (R6). Defaults are the restrictive
/// 50-per-agent / 30-day caps; `~/.car/config.toml [runs]` overrides.
#[derive(Debug, Clone, Copy)]
pub struct RetentionConfig {
    pub max_per_agent: usize,
    pub max_age_days: i64,
}

impl Default for RetentionConfig {
    fn default() -> Self {
        Self {
            max_per_agent: DEFAULT_MAX_RUNS_PER_AGENT,
            max_age_days: DEFAULT_MAX_AGE_DAYS,
        }
    }
}

/// `[runs]` section of `~/.car/config.toml`. Both keys optional; an
/// absent key keeps the restrictive default.
#[derive(Debug, Clone, Default, Deserialize)]
struct RunsConfigFile {
    #[serde(default)]
    runs: RunsSection,
}

#[derive(Debug, Clone, Default, Deserialize)]
struct RunsSection {
    #[serde(default)]
    max_per_agent: Option<usize>,
    #[serde(default)]
    max_age_days: Option<i64>,
}

impl RetentionConfig {
    /// Load the retention policy from `<car_dir>/config.toml`'s `[runs]`
    /// section, falling back to the restrictive default for any missing
    /// key or an unreadable/malformed file (config errors must never make
    /// the daemon refuse to start — same posture as the rest of `.car`).
    pub fn from_car_dir(car_dir: &Path) -> Self {
        let mut cfg = Self::default();
        let path = car_dir.join("config.toml");
        let Ok(text) = std::fs::read_to_string(&path) else {
            return cfg;
        };
        let Ok(parsed) = toml::from_str::<RunsConfigFile>(&text) else {
            return cfg;
        };
        if let Some(n) = parsed.runs.max_per_agent {
            cfg.max_per_agent = n;
        }
        if let Some(d) = parsed.runs.max_age_days {
            cfg.max_age_days = d;
        }
        cfg
    }
}

/// JSONL run-trace store rooted at `<car_dir>/runs/`.
///
/// Stateless across calls — each append opens, writes, and closes the
/// run's file. Flush points are sparse (turn granularity), so there is no
/// long-lived file handle to manage, and a concurrently-restarting daemon
/// always sees a consistent on-disk tail.
#[derive(Debug, Clone)]
pub struct RunStore {
    /// `<car_dir>/runs` — the tree root, created `0700`.
    root: PathBuf,
    retention: RetentionConfig,
    failures: RunStoreFailureInjector,
    summary_read_gate: Option<RunStoreSummaryReadGate>,
    summary_write_gate: Option<RunStoreSummaryWriteGate>,
    append_gate: Option<RunStoreAppendGate>,
    lookup_gate: Option<RunStoreLookupGate>,
    private_path_failures: Option<car_secrets::PrivatePathDurabilityFailureInjector>,
    append_locks: Arc<Mutex<HashMap<PathBuf, Weak<Mutex<()>>>>>,
    trace_corruptions: Arc<Mutex<HashMap<(String, String), RunTraceCorruption>>>,
}

#[derive(Debug, Default)]
struct SummaryReadGateState {
    armed: bool,
    entered: bool,
}

/// Deterministic test/embedder seam for proving summary reads do not hold
/// async runtime locks. It is inert unless explicitly armed.
#[derive(Debug, Clone, Default)]
pub struct RunStoreSummaryReadGate {
    state: Arc<(Mutex<SummaryReadGateState>, Condvar)>,
}

pub type RunStoreAppendGate = RunStoreSummaryReadGate;
pub type RunStoreLookupGate = RunStoreSummaryReadGate;
#[doc(hidden)]
pub type RunStoreSummaryWriteGate = RunStoreSummaryReadGate;

impl RunStoreSummaryReadGate {
    pub fn block_next(&self) {
        let (lock, _) = &*self.state;
        let mut state = lock.lock().expect("run-store gate mutex poisoned");
        state.armed = true;
        state.entered = false;
    }

    pub fn wait_until_entered(&self, timeout: std::time::Duration) -> bool {
        let (lock, ready) = &*self.state;
        let state = lock.lock().expect("run-store gate mutex poisoned");
        let (state, _) = ready
            .wait_timeout_while(state, timeout, |state| !state.entered)
            .expect("run-store gate mutex poisoned while waiting");
        state.entered
    }

    pub fn release(&self) {
        let (lock, ready) = &*self.state;
        let mut state = lock.lock().expect("run-store gate mutex poisoned");
        state.armed = false;
        ready.notify_all();
    }

    fn wait_if_armed(&self) {
        let (lock, ready) = &*self.state;
        let mut state = lock.lock().expect("run-store gate mutex poisoned");
        if !state.armed || state.entered {
            return;
        }
        state.entered = true;
        ready.notify_all();
        while state.armed {
            state = ready
                .wait(state)
                .expect("run-store gate mutex poisoned while blocked");
        }
    }
}

#[derive(Debug, Clone)]
pub struct ProposalTraceEnsure {
    pub records: Vec<RunRecord>,
    pub appended: bool,
}

/// Exact durable append boundary used by deterministic fault-injection tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunStoreFailurePoint {
    MarkerWrite,
    Write,
    Flush,
    Fsync,
    PendingUnlink,
    MarkerUnlink,
    DirectoryFsync,
    ResponseSerialization,
    SummaryWrite,
    CorruptionMarkerWrite,
    CorruptionSummaryInvalidate,
}

#[derive(Debug, Clone, Default)]
pub struct RunStoreFailureInjector {
    failures: Arc<Mutex<VecDeque<RunStoreFailurePoint>>>,
}

fn injected_storage_full() -> std::io::Error {
    std::io::Error::new(
        std::io::ErrorKind::StorageFull,
        "injected run-store storage full",
    )
}

impl RunStoreFailureInjector {
    pub fn fail_next(&self, point: RunStoreFailurePoint) {
        self.failures
            .lock()
            .expect("run-store failure injector mutex poisoned")
            .push_back(point);
    }

    fn take(&self, point: RunStoreFailurePoint) -> bool {
        let mut failures = self
            .failures
            .lock()
            .expect("run-store failure injector mutex poisoned");
        if failures.front() == Some(&point) {
            failures.pop_front();
            true
        } else {
            false
        }
    }
}

impl RunStore {
    /// Construct a store rooted at `runs_root` (the `runs/` dir itself).
    /// Use [`RunStore::from_journal_dir`] from the daemon, which derives
    /// the root from the configured journal dir; this constructor is the
    /// test/embedder seam.
    pub fn new(runs_root: PathBuf, retention: RetentionConfig) -> Self {
        Self {
            root: runs_root,
            retention,
            failures: RunStoreFailureInjector::default(),
            summary_read_gate: None,
            summary_write_gate: None,
            append_gate: None,
            lookup_gate: None,
            private_path_failures: None,
            append_locks: Arc::new(Mutex::new(HashMap::new())),
            trace_corruptions: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub fn with_failure_injector(mut self, failures: RunStoreFailureInjector) -> Self {
        self.failures = failures;
        self
    }

    pub fn with_summary_read_gate(mut self, gate: RunStoreSummaryReadGate) -> Self {
        self.summary_read_gate = Some(gate);
        self
    }

    #[doc(hidden)]
    pub fn with_summary_write_gate(mut self, gate: RunStoreSummaryWriteGate) -> Self {
        self.summary_write_gate = Some(gate);
        self
    }

    pub fn with_append_gate(mut self, gate: RunStoreAppendGate) -> Self {
        self.append_gate = Some(gate);
        self
    }

    pub fn with_lookup_gate(mut self, gate: RunStoreLookupGate) -> Self {
        self.lookup_gate = Some(gate);
        self
    }

    /// Test/embedder seam for deterministic first-use directory-entry faults.
    pub fn with_private_path_failure_injector(
        mut self,
        failures: car_secrets::PrivatePathDurabilityFailureInjector,
    ) -> Self {
        self.private_path_failures = Some(failures);
        self
    }

    fn ensure_private_dir(&self, path: &Path) -> std::io::Result<()> {
        match self.private_path_failures.as_ref() {
            Some(failures) => car_secrets::ensure_private_dir_with_failure_injector(path, failures),
            None => car_secrets::ensure_private_dir(path),
        }
    }

    fn create_private_file(&self, path: &Path) -> std::io::Result<File> {
        match self.private_path_failures.as_ref() {
            Some(failures) => {
                car_secrets::create_private_file_with_failure_injector(path, failures)
            }
            None => car_secrets::create_private_file(path),
        }
    }

    fn open_private_append(&self, path: &Path) -> std::io::Result<File> {
        match self.private_path_failures.as_ref() {
            Some(failures) => {
                car_secrets::open_private_append_with_failure_injector(path, failures)
            }
            None => car_secrets::open_private_append(path),
        }
    }

    /// Derive the store from the daemon's journal dir. The journal lives
    /// at `~/.car/journals`, so the run store is its sibling
    /// `~/.car/runs`; retention is read from `~/.car/config.toml`. When
    /// the journal dir has no parent (a bare relative path), the store
    /// falls back to `journal_dir/../runs` resolved lexically.
    pub fn from_journal_dir(journal_dir: &Path) -> Self {
        let car_dir = journal_dir
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("."));
        let root = car_dir.join("runs");
        let retention = RetentionConfig::from_car_dir(&car_dir);
        Self::new(root, retention)
    }

    /// The `runs/` tree root.
    pub fn root(&self) -> &Path {
        &self.root
    }

    fn proposal_outbox_root(&self) -> PathBuf {
        self.root
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join("proposal-finalization")
    }

    fn proposal_outbox_path(&self, run_id: &str) -> PathBuf {
        let key = format!("{:x}", Sha256::digest(run_id.as_bytes()));
        self.proposal_outbox_root().join(format!("{key}.json"))
    }

    fn proposal_execution_root(&self) -> PathBuf {
        self.root
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join("proposal-execution")
    }

    fn proposal_execution_path(&self, run_id: &str) -> PathBuf {
        let key = format!("{:x}", Sha256::digest(run_id.as_bytes()));
        self.proposal_execution_root().join(format!("{key}.json"))
    }

    fn proposal_retry_rollback_root(&self) -> PathBuf {
        self.root
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join("proposal-retry-rollbacks")
    }

    fn proposal_retry_rollback_path(&self, run_id: &str) -> PathBuf {
        let key = format!("{:x}", Sha256::digest(run_id.as_bytes()));
        self.proposal_retry_rollback_root()
            .join(format!("{key}.json"))
    }

    fn proposal_id_claim_root(&self, run_id: &str) -> PathBuf {
        let run_key = format!("{:x}", Sha256::digest(run_id.as_bytes()));
        self.root
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join("proposal-id-claims")
            .join(run_key)
    }

    fn proposal_id_claim_path(&self, run_id: &str, proposal_id: &str) -> PathBuf {
        let proposal_key = format!("{:x}", Sha256::digest(proposal_id.as_bytes()));
        self.proposal_id_claim_root(run_id)
            .join(format!("{proposal_key}.json"))
    }

    fn completed_response_root(&self) -> PathBuf {
        self.root
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join("proposal-completed")
    }

    fn completed_response_run_root(&self, run_id: &str) -> PathBuf {
        let run_key = format!("{:x}", Sha256::digest(run_id.as_bytes()));
        self.completed_response_root().join(run_key)
    }

    fn completed_response_index_root(&self) -> PathBuf {
        self.root
            .parent()
            .unwrap_or_else(|| Path::new("."))
            .join("proposal-completed-index")
    }

    fn completed_response_index_migration_path(&self) -> PathBuf {
        self.completed_response_index_root()
            .join("owner-index-migration.json")
    }

    fn completed_response_owner_key(
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<String> {
        let key_preimage = serde_json::to_vec(&(requested_policy_session_id, original_submission))
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        Ok(format!("{:x}", Sha256::digest(key_preimage)))
    }

    fn completed_response_owner_path(
        &self,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<PathBuf> {
        Ok(self.completed_response_index_root().join(format!(
            "{}.json",
            Self::completed_response_owner_key(requested_policy_session_id, original_submission,)?
        )))
    }

    fn completed_response_key(
        client_id: &str,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<String> {
        let key_preimage =
            serde_json::to_vec(&(client_id, requested_policy_session_id, original_submission))
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        Ok(format!("{:x}", Sha256::digest(key_preimage)))
    }

    fn completed_response_path(
        &self,
        run_id: &str,
        client_id: &str,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<PathBuf> {
        Ok(self.completed_response_run_root(run_id).join(format!(
            "{}.json",
            Self::completed_response_key(
                client_id,
                requested_policy_session_id,
                original_submission,
            )?
        )))
    }

    /// Read the exact durable `RunStarted` boundary for `run_id` without
    /// collapsing absence into corruption. A zero-byte file left by an open
    /// that failed before its first write is still absent; any non-empty file
    /// without one valid, unambiguous `RunStarted` is invalid durable state.
    pub fn run_started(&self, run_id: &str) -> std::io::Result<Option<car_proto::RunStarted>> {
        if let Some(gate) = &self.lookup_gate {
            gate.wait_if_armed();
        }
        match self.open_root_for_read() {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        }
        let file_name = format!("{}.jsonl", sanitize(run_id));
        let mut found = None;
        for agent in std::fs::read_dir(&self.root)? {
            let agent = agent?;
            let file_type = agent.file_type()?;
            if !file_type.is_dir() || file_type.is_symlink() {
                continue;
            }
            car_secrets::ensure_private_dir(&agent.path())?;
            let path = agent.path().join(&file_name);
            match car_secrets::open_private_read(&path) {
                Ok(file) if found.is_none() => found = Some((path, file)),
                Ok(_) => {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!("durable run `{run_id}` exists under multiple agents"),
                    ))
                }
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
                Err(error) => return Err(error),
            }
        }
        let Some((path, file)) = found else {
            return Ok(None);
        };
        let file_len = file.metadata()?.len();
        let records = load_private_records(&path, &file)?;
        if records.is_empty() && file_len == 0 {
            return Ok(None);
        }
        let mut started_rows = records.iter().filter_map(|record| match record {
            RunRecord::Started(started) => Some(started),
            _ => None,
        });
        let started = started_rows.next().ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("durable run record for `{run_id}` has no RunStarted"),
            )
        })?;
        if started_rows.next().is_some()
            || started.run_id != run_id
            || started.client_id.as_deref().is_none_or(str::is_empty)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("durable RunStarted identity for `{run_id}` is ambiguous or invalid"),
            ));
        }
        Ok(Some(started.clone()))
    }

    fn durable_run_started(&self, run_id: &str) -> std::io::Result<car_proto::RunStarted> {
        self.run_started(run_id)?.ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                format!("durable RunStarted for run `{run_id}` is absent"),
            )
        })
    }

    /// Remove only the zero-byte trace created when `runs.start` opened its
    /// destination but failed before writing `RunStarted`. The full expected
    /// identity is accepted so callers cannot use this as a broad delete
    /// primitive. Any bytes or parsed rows make rollback fail closed.
    pub fn rollback_empty_run_start(&self, started: &car_proto::RunStarted) -> std::io::Result<()> {
        let dir = match self.open_agent_dir_for_read(&started.agent_id) {
            Ok(dir) => dir,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(error) => return Err(error),
        };
        let path = self.run_path(&started.agent_id, &started.run_id);
        let append_lock = self.append_lock(&path);
        let _guard = append_lock
            .lock()
            .map_err(|_| std::io::Error::other("run append lock poisoned"))?;
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(error) => return Err(error),
        };
        car_secrets::revalidate_private_path(&path, &file)?;
        if file.metadata()?.len() != 0 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::AlreadyExists,
                format!(
                    "run `{}` acquired durable bytes while empty-start rollback was pending",
                    started.run_id
                ),
            ));
        }
        drop(file);
        std::fs::remove_file(&path)?;
        sync_directory(dir)
    }

    pub fn pending_provenance(
        &self,
        pending: &PendingProposalFinalization,
    ) -> std::io::Result<(car_proto::RunStarted, ProposalExecutionMarker)> {
        pending.validate()?;
        let started = self.durable_run_started(&pending.run_id)?;
        let marker = self.execution_marker(&pending.run_id)?.ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "pending finalization is missing its durable execution marker",
            )
        })?;
        pending.validate_provenance(&started, &marker)?;
        Ok((started, marker))
    }

    /// Write the durable `execution_in_progress` marker before tool dispatch.
    pub fn write_execution_marker(&self, marker: &ProposalExecutionMarker) -> std::io::Result<()> {
        marker.validate()?;
        if self.failures.take(RunStoreFailurePoint::MarkerWrite) {
            return Err(std::io::Error::other(
                "injected proposal execution marker write failure",
            ));
        }
        let root = self.proposal_execution_root();
        self.ensure_private_dir(&root)?;
        ensure_backup_excluded(&root)?;
        let path = self.proposal_execution_path(&marker.run_id);
        match car_secrets::open_private_read(&path) {
            Ok(file) => {
                let existing: ProposalExecutionMarker = serde_json::from_reader(file)
                    .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
                if existing == *marker {
                    return Ok(());
                }
                return Err(std::io::Error::new(
                    std::io::ErrorKind::AlreadyExists,
                    "run already has a different execution-in-progress marker",
                ));
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
        let temp = root.join(format!(
            ".{}.{}.tmp",
            path.file_stem()
                .and_then(|value| value.to_str())
                .unwrap_or("proposal"),
            uuid::Uuid::new_v4().simple()
        ));
        let write_result = (|| {
            let mut file = self.create_private_file(&temp)?;
            serde_json::to_writer(&mut file, marker)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
            file.flush()?;
            file.sync_all()?;
            car_secrets::revalidate_private_path(&temp, &file)?;
            drop(file);
            car_secrets::atomic_replace_private_file(&temp, &path)?;
            sync_directory(&root)
        })();
        if write_result.is_err() {
            let _ = std::fs::remove_file(&temp);
        }
        write_result
    }

    pub fn execution_marker(
        &self,
        run_id: &str,
    ) -> std::io::Result<Option<ProposalExecutionMarker>> {
        let path = self.proposal_execution_path(run_id);
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let marker: ProposalExecutionMarker = serde_json::from_reader(file)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        if marker.run_id != run_id {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "proposal execution marker run_id `{}` does not match requested run `{run_id}`",
                    marker.run_id
                ),
            ));
        }
        marker.validate()?;
        Ok(Some(marker))
    }

    /// Persist the pre-execution rollback authority before acquiring the
    /// content-addressed retry owner. Exact rewrites are idempotent; a
    /// conflicting preimage for the same run fails closed.
    pub fn write_proposal_retry_rollback(
        &self,
        rollback: &ProposalRetryRollback,
    ) -> std::io::Result<()> {
        rollback.validate()?;
        let root = self.proposal_retry_rollback_root();
        self.ensure_private_dir(&root)?;
        ensure_backup_excluded(&root)?;
        let path = self.proposal_retry_rollback_path(&rollback.run_id);
        match car_secrets::open_private_read(&path) {
            Ok(file) => {
                let existing: ProposalRetryRollback = serde_json::from_reader(file)
                    .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
                existing.validate()?;
                if existing == *rollback {
                    return Ok(());
                }
                return Err(std::io::Error::new(
                    std::io::ErrorKind::AlreadyExists,
                    "run already has a different proposal retry rollback intent",
                ));
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
        self.write_private_json_atomic(&root, &path, rollback)
    }

    pub fn proposal_retry_rollback(
        &self,
        run_id: &str,
    ) -> std::io::Result<Option<ProposalRetryRollback>> {
        let path = self.proposal_retry_rollback_path(run_id);
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let rollback: ProposalRetryRollback = serde_json::from_reader(file)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        rollback.validate()?;
        if rollback.run_id != run_id || path != self.proposal_retry_rollback_path(&rollback.run_id)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "proposal retry rollback path does not match its run identity",
            ));
        }
        Ok(Some(rollback))
    }

    pub fn clear_proposal_retry_rollback(
        &self,
        expected: &ProposalRetryRollback,
    ) -> std::io::Result<()> {
        let Some(existing) = self.proposal_retry_rollback(&expected.run_id)? else {
            return Ok(());
        };
        if existing != *expected {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proposal retry rollback does not match the exact authority",
            ));
        }
        let root = self.proposal_retry_rollback_root();
        std::fs::remove_file(self.proposal_retry_rollback_path(&expected.run_id))?;
        sync_directory(root)
    }

    /// Resolve every crash-left rollback intent. The intent is removed last:
    /// a second crash at any earlier boundary leaves enough authority for the
    /// next startup to repeat the exact cleanup.
    pub fn reconcile_proposal_retry_rollbacks(&self) -> std::io::Result<usize> {
        let root = self.proposal_retry_rollback_root();
        let entries = match std::fs::read_dir(&root) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(0),
            Err(error) => return Err(error),
        };
        let mut reconciled = 0usize;
        for entry in entries {
            let entry = entry?;
            if entry.path().extension().and_then(|value| value.to_str()) != Some("json") {
                continue;
            }
            let file = car_secrets::open_private_read(&entry.path())?;
            let rollback: ProposalRetryRollback = serde_json::from_reader(file)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
            rollback.validate()?;
            if entry.path() != self.proposal_retry_rollback_path(&rollback.run_id) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "proposal retry rollback filename does not match its run identity",
                ));
            }
            if self.execution_marker(&rollback.run_id)?.is_none()
                && self.completed_proposal_retry_owner(
                    rollback.requested_policy_session_id.as_deref(),
                    &rollback.original_submission,
                )? == Some((rollback.run_id.clone(), rollback.client_id.clone()))
            {
                self.release_proposal_retry_owner(
                    &rollback.run_id,
                    &rollback.client_id,
                    rollback.requested_policy_session_id.as_deref(),
                    &rollback.original_submission,
                )?;
            }
            self.clear_proposal_retry_rollback(&rollback)?;
            reconciled = reconciled.saturating_add(1);
        }
        Ok(reconciled)
    }

    /// Claim a proposal identifier inside one authenticated run before any
    /// dispatch. Exact-submission retries are idempotent; reusing the same id
    /// for changed bytes is rejected durably, including after restart.
    pub fn claim_proposal_id(
        &self,
        run_id: &str,
        client_id: &str,
        proposal_id: &str,
        original_submission: &Value,
    ) -> std::io::Result<ProposalIdClaimOutcome> {
        if run_id.is_empty() || client_id.is_empty() || proposal_id.is_empty() {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proposal id claim requires non-empty run/client/proposal identities",
            ));
        }
        let expected = ProposalIdClaim {
            run_id: run_id.to_string(),
            client_id: client_id.to_string(),
            proposal_id: proposal_id.to_string(),
            original_submission: original_submission.clone(),
        };
        let root = self.proposal_id_claim_root(run_id);
        self.ensure_private_dir(&root)?;
        ensure_backup_excluded(&root)?;
        let path = self.proposal_id_claim_path(run_id, proposal_id);
        let lock = self.append_lock(&path);
        let _guard = lock
            .lock()
            .map_err(|_| std::io::Error::other("proposal id claim lock poisoned"))?;
        match car_secrets::open_private_read(&path) {
            Ok(file) => {
                let existing: ProposalIdClaim = serde_json::from_reader(file)
                    .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
                if existing == expected {
                    return Ok(ProposalIdClaimOutcome::ExistingExact);
                }
                return Err(std::io::Error::new(
                    std::io::ErrorKind::AlreadyExists,
                    "proposal id is already bound to a different submission in this run",
                ));
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
        self.write_private_json_atomic(&root, &path, &expected)?;
        Ok(ProposalIdClaimOutcome::Acquired)
    }

    fn write_private_json_atomic<T: Serialize>(
        &self,
        root: &Path,
        path: &Path,
        value: &T,
    ) -> std::io::Result<()> {
        let temp = root.join(format!(
            ".{}.{}.tmp",
            path.file_stem()
                .and_then(|value| value.to_str())
                .unwrap_or("record"),
            uuid::Uuid::new_v4().simple()
        ));
        let write_result = (|| {
            let mut file = self.create_private_file(&temp)?;
            serde_json::to_writer(&mut file, value)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
            file.flush()?;
            file.sync_all()?;
            car_secrets::revalidate_private_path(&temp, &file)?;
            drop(file);
            car_secrets::atomic_replace_private_file(&temp, path)?;
            sync_directory(root)
        })();
        if write_result.is_err() {
            let _ = std::fs::remove_file(&temp);
        }
        write_result
    }

    pub fn clear_execution_marker(
        &self,
        expected: &ProposalExecutionMarker,
    ) -> std::io::Result<()> {
        let Some(existing) = self.execution_marker(&expected.run_id)? else {
            return Ok(());
        };
        if existing != *expected {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proposal execution marker does not match the full expected identity tuple",
            ));
        }
        let root = self.proposal_execution_root();
        std::fs::remove_file(self.proposal_execution_path(&expected.run_id))?;
        sync_directory(root)
    }

    /// Persist one exact proposal-finalization transaction with private
    /// permissions and an fsynced atomic replacement. Exact retries are
    /// idempotent; a conflicting preimage for the same run is rejected.
    pub fn write_pending_proposal(
        &self,
        pending: &PendingProposalFinalization,
    ) -> std::io::Result<()> {
        self.pending_provenance(pending)?;
        if pending.run_id.is_empty()
            || pending.client_id.is_empty()
            || pending.original_proposal_id.is_empty()
            || pending.final_proposal_id.is_empty()
            || pending.result_digest.len() != 64
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proposal finalization requires run/client/proposal identities and a SHA-256 digest",
            ));
        }
        let root = self.proposal_outbox_root();
        self.ensure_private_dir(&root)?;
        ensure_backup_excluded(&root)?;
        let path = self.proposal_outbox_path(&pending.run_id);
        match car_secrets::open_private_read(&path) {
            Ok(file) => {
                let existing: PendingProposalFinalization = serde_json::from_reader(file)
                    .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
                if existing == *pending {
                    return Ok(());
                }
                return Err(std::io::Error::new(
                    std::io::ErrorKind::AlreadyExists,
                    "run already has a different pending proposal finalization",
                ));
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }

        let temp = root.join(format!(
            ".{}.{}.tmp",
            path.file_stem()
                .and_then(|value| value.to_str())
                .unwrap_or("proposal"),
            uuid::Uuid::new_v4().simple()
        ));
        let write_result = (|| {
            let mut file = self.create_private_file(&temp)?;
            serde_json::to_writer(&mut file, pending)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
            file.flush()?;
            file.sync_all()?;
            car_secrets::revalidate_private_path(&temp, &file)?;
            drop(file);
            car_secrets::atomic_replace_private_file(&temp, &path)?;
            sync_directory(&root)
        })();
        if write_result.is_err() {
            let _ = std::fs::remove_file(&temp);
        }
        write_result
    }

    pub fn pending_proposal(
        &self,
        run_id: &str,
    ) -> std::io::Result<Option<PendingProposalFinalization>> {
        let path = self.proposal_outbox_path(run_id);
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let pending: PendingProposalFinalization = serde_json::from_reader(file)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        if pending.run_id != run_id {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "proposal finalization run_id `{}` does not match requested run `{run_id}`",
                    pending.run_id
                ),
            ));
        }
        self.pending_provenance(&pending)?;
        Ok(Some(pending))
    }

    pub fn all_pending_proposals(&self) -> std::io::Result<Vec<PendingProposalFinalization>> {
        let root = self.proposal_outbox_root();
        let entries = match std::fs::read_dir(root) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(error) => return Err(error),
        };
        let mut pending = Vec::new();
        for entry in entries {
            let entry = entry?;
            if entry.path().extension().and_then(|ext| ext.to_str()) != Some("json") {
                continue;
            }
            let file = car_secrets::open_private_read(&entry.path())?;
            let row: PendingProposalFinalization = serde_json::from_reader(file)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
            if entry.path() != self.proposal_outbox_path(&row.run_id) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "proposal finalization filename does not match internal run_id `{}`",
                        row.run_id
                    ),
                ));
            }
            self.pending_provenance(&row)?;
            pending.push(row);
        }
        Ok(pending)
    }

    /// Remove only the exact, provenance-validated transaction whose terminal
    /// was acknowledged. The caller clears this before its matching execution
    /// marker so provenance remains available for the check.
    pub fn clear_pending_proposal(
        &self,
        expected: &PendingProposalFinalization,
    ) -> std::io::Result<()> {
        self.pending_provenance(expected)?;
        let existing = self.pending_proposal(&expected.run_id)?.ok_or_else(|| {
            std::io::Error::new(
                std::io::ErrorKind::NotFound,
                "proposal finalization outbox row is absent",
            )
        })?;
        if existing != *expected {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proposal finalization outbox does not match the full expected transaction",
            ));
        }
        let root = self.proposal_outbox_root();
        std::fs::remove_file(self.proposal_outbox_path(&expected.run_id))?;
        sync_directory(root)
    }

    /// Validate only the receipt's self-contained typed preimages. The sole
    /// creation path separately requires [`Self::pending_provenance`] before
    /// publishing, while retained reads cannot depend on a GC-eligible trace.
    fn validate_completed_response(
        &self,
        receipt: &CompletedProposalResponse,
    ) -> std::io::Result<()> {
        receipt.validate()?;
        Ok(())
    }

    fn read_completed_proposal_owner(
        &self,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<Option<CompletedProposalOwnership>> {
        let path =
            self.completed_response_owner_path(requested_policy_session_id, original_submission)?;
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let owner: CompletedProposalOwnership = serde_json::from_reader(file)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        if owner.requested_policy_session_id.as_deref() != requested_policy_session_id
            || owner.original_submission != *original_submission
            || path
                != self.completed_response_owner_path(
                    owner.requested_policy_session_id.as_deref(),
                    &owner.original_submission,
                )?
            || owner.run_id.is_empty()
            || owner.client_id.is_empty()
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "completed proposal ownership index does not match its retry tuple",
            ));
        }
        Ok(Some(owner))
    }

    /// Atomically reserve the process-wide retry tuple before any execution
    /// marker or runtime invocation. Direct exclusive creation is the linear
    /// point: one run/client wins, every concurrent or restarted contender
    /// observes that durable owner, and a partial claim fails closed.
    pub fn reserve_proposal_retry_owner(
        &self,
        run_id: &str,
        client_id: &str,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<ProposalRetryReservation> {
        if run_id.is_empty() || client_id.is_empty() || requested_policy_session_id == Some("") {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proposal retry reservation requires non-empty run/client/policy identities",
            ));
        }
        let expected = CompletedProposalOwnership::new(
            run_id,
            client_id,
            requested_policy_session_id,
            original_submission,
        );
        let root = self.completed_response_index_root();
        self.ensure_private_dir(&root)?;
        ensure_backup_excluded(&root)?;
        sync_directory(root.parent().unwrap_or_else(|| Path::new(".")))?;
        let path =
            self.completed_response_owner_path(requested_policy_session_id, original_submission)?;
        let lock = self.append_lock(&path);
        let _guard = lock
            .lock()
            .map_err(|_| std::io::Error::other("proposal retry reservation lock poisoned"))?;
        if let Some(existing) =
            self.read_completed_proposal_owner(requested_policy_session_id, original_submission)?
        {
            return Ok(ProposalRetryReservation::Existing {
                run_id: existing.run_id,
                client_id: existing.client_id,
            });
        }

        let mut file = match self.create_private_file(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
                let existing = self
                    .read_completed_proposal_owner(
                        requested_policy_session_id,
                        original_submission,
                    )?
                    .ok_or_else(|| {
                        std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "proposal retry reservation appeared without a readable owner",
                        )
                    })?;
                return Ok(ProposalRetryReservation::Existing {
                    run_id: existing.run_id,
                    client_id: existing.client_id,
                });
            }
            Err(error) => return Err(error),
        };
        serde_json::to_writer(&mut file, &expected)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        file.flush()?;
        file.sync_all()?;
        car_secrets::revalidate_private_path(&path, &file)?;
        sync_directory(&root)?;
        Ok(ProposalRetryReservation::Acquired)
    }

    /// Release only the exact pre-dispatch retry owner. This is used when
    /// execution never became admissible (marker durability or policy bind
    /// failed), so a later scheduled run may safely submit the same proposal.
    /// The content-addressed owner is validated before unlink and the owner
    /// directory is fsynced before success is reported.
    pub fn release_proposal_retry_owner(
        &self,
        run_id: &str,
        client_id: &str,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<()> {
        let path =
            self.completed_response_owner_path(requested_policy_session_id, original_submission)?;
        let lock = self.append_lock(&path);
        let _guard = lock
            .lock()
            .map_err(|_| std::io::Error::other("proposal retry release lock poisoned"))?;
        let Some(existing) =
            self.read_completed_proposal_owner(requested_policy_session_id, original_submission)?
        else {
            return Ok(());
        };
        if existing.run_id != run_id || existing.client_id != client_id {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "proposal retry owner does not match the exact rollback authority",
            ));
        }
        let root = self.completed_response_index_root();
        std::fs::remove_file(path)?;
        sync_directory(root)
    }

    /// Verify or backfill the pre-execution owner before publishing a
    /// completed response. Startup uses the same operation to migrate legacy
    /// receipts that predate reservations.
    fn claim_completed_proposal_owner(
        &self,
        pending: &PendingProposalFinalization,
    ) -> std::io::Result<()> {
        match self.reserve_proposal_retry_owner(
            &pending.run_id,
            &pending.client_id,
            pending.requested_policy_session_id.as_deref(),
            &pending.original_submission,
        )? {
            ProposalRetryReservation::Acquired => Ok(()),
            ProposalRetryReservation::Existing { run_id, client_id }
                if run_id == pending.run_id && client_id == pending.client_id =>
            {
                Ok(())
            }
            ProposalRetryReservation::Existing { .. } => Err(std::io::Error::new(
                std::io::ErrorKind::AlreadyExists,
                "proposal retry tuple already belongs to a different completed response",
            )),
        }
    }

    /// Persist an exact typed response only after the matching critical
    /// `proposal_completed` append acknowledged. The finalization outbox and
    /// execution marker must still be present and provenance-valid here, so a
    /// forged receipt cannot become a cleanup authority.
    pub fn write_completed_proposal(
        &self,
        pending: &PendingProposalFinalization,
    ) -> std::io::Result<CompletedProposalResponse> {
        self.pending_provenance(pending)?;
        let receipt = CompletedProposalResponse {
            finalization: pending.clone(),
        };
        self.validate_completed_response(&receipt)?;
        self.claim_completed_proposal_owner(pending)?;
        let root = self.completed_response_root();
        self.ensure_private_dir(&root)?;
        ensure_backup_excluded(&root)?;
        sync_directory(root.parent().unwrap_or_else(|| Path::new(".")))?;
        let run_root = self.completed_response_run_root(&pending.run_id);
        self.ensure_private_dir(&run_root)?;
        sync_directory(&root)?;
        let path = self.completed_response_path(
            &pending.run_id,
            &pending.client_id,
            pending.requested_policy_session_id.as_deref(),
            &pending.original_submission,
        )?;
        match car_secrets::open_private_read(&path) {
            Ok(file) => {
                let existing: CompletedProposalResponse = serde_json::from_reader(file)
                    .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
                self.validate_completed_response(&existing)?;
                if existing == receipt {
                    return Ok(existing);
                }
                return Err(std::io::Error::new(
                    std::io::ErrorKind::AlreadyExists,
                    "exact proposal retry key already has a different completed response",
                ));
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }

        let temp = run_root.join(format!(".response.{}.tmp", uuid::Uuid::new_v4().simple()));
        let write_result = (|| {
            let mut file = self.create_private_file(&temp)?;
            serde_json::to_writer(&mut file, &receipt)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
            file.flush()?;
            file.sync_all()?;
            car_secrets::revalidate_private_path(&temp, &file)?;
            drop(file);
            car_secrets::atomic_replace_private_file(&temp, &path)?;
            sync_directory(&run_root)
        })();
        if write_result.is_err() {
            let _ = std::fs::remove_file(&temp);
        }
        write_result.map(|()| receipt)
    }

    /// Load only the receipt whose immutable retry tuple exactly matches this
    /// bound run/client/policy/raw submission. Absence permits a new proposal;
    /// a present corrupt or self-inconsistent receipt fails closed.
    pub fn completed_proposal(
        &self,
        run_id: &str,
        client_id: &str,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<Option<CompletedProposalResponse>> {
        let path = self.completed_response_path(
            run_id,
            client_id,
            requested_policy_session_id,
            original_submission,
        )?;
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let receipt: CompletedProposalResponse = serde_json::from_reader(file)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        self.validate_completed_response(&receipt)?;
        let pending = &receipt.finalization;
        if pending.run_id != run_id
            || pending.client_id != client_id
            || pending.requested_policy_session_id.as_deref() != requested_policy_session_id
            || pending.original_submission != *original_submission
            || path
                != self.completed_response_path(
                    &pending.run_id,
                    &pending.client_id,
                    pending.requested_policy_session_id.as_deref(),
                    &pending.original_submission,
                )?
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "completed proposal response does not match its exact retry key",
            ));
        }
        Ok(Some(receipt))
    }

    /// Recover the sole retained response for an exact proposal after an
    /// authenticated run owner reconnects with a newly minted policy session.
    ///
    /// The lookup is deliberately bounded to one run and one durable client.
    /// It never treats the replacement policy-session id as durable identity,
    /// and ambiguity fails closed instead of selecting an arbitrary receipt.
    pub fn completed_proposal_for_resumed_owner(
        &self,
        run_id: &str,
        durable_client_id: &str,
        original_submission: &Value,
    ) -> std::io::Result<Option<CompletedProposalResponse>> {
        let run_root = self.completed_response_run_root(run_id);
        let entries = match std::fs::read_dir(&run_root) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        car_secrets::ensure_private_dir(&run_root)?;

        let mut receipt_paths = Vec::new();
        for entry in entries {
            let entry = entry?;
            if entry.path().extension().and_then(|ext| ext.to_str()) != Some("json") {
                continue;
            }
            if receipt_paths.len() >= MAX_RESUMED_PROPOSAL_RECEIPTS_PER_RUN {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "resumed proposal recovery exceeded the per-run receipt count limit",
                ));
            }
            receipt_paths.push(entry.path());
        }

        let mut matching = None;
        let mut scanned_bytes = 0_u64;
        for path in receipt_paths {
            let file = car_secrets::open_private_read(&path)?;
            scanned_bytes = scanned_bytes
                .checked_add(file.metadata()?.len())
                .filter(|total| *total <= MAX_RESUMED_PROPOSAL_RECEIPT_BYTES_PER_RUN)
                .ok_or_else(|| {
                    std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "resumed proposal recovery exceeded the per-run receipt byte limit",
                    )
                })?;
            let receipt: CompletedProposalResponse = serde_json::from_reader(file)
                .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
            self.validate_completed_response(&receipt)?;
            let pending = &receipt.finalization;
            if pending.run_id != run_id
                || path
                    != self.completed_response_path(
                        &pending.run_id,
                        &pending.client_id,
                        pending.requested_policy_session_id.as_deref(),
                        &pending.original_submission,
                    )?
            {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "completed proposal response path does not match its typed identity",
                ));
            }
            if pending.client_id != durable_client_id
                || pending.original_submission != *original_submission
            {
                continue;
            }
            if matching.replace(receipt).is_some() {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "resumed proposal recovery is ambiguous for the exact durable owner and submission",
                ));
            }
        }
        Ok(matching)
    }

    pub fn all_completed_proposals(&self) -> std::io::Result<Vec<CompletedProposalResponse>> {
        let root = self.completed_response_root();
        let run_dirs = match std::fs::read_dir(&root) {
            Ok(entries) => entries,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(error) => return Err(error),
        };
        let mut receipts = Vec::new();
        for run_dir in run_dirs {
            let run_dir = run_dir?;
            if !run_dir.file_type()?.is_dir() || run_dir.file_type()?.is_symlink() {
                continue;
            }
            car_secrets::ensure_private_dir(&run_dir.path())?;
            for entry in std::fs::read_dir(run_dir.path())? {
                let entry = entry?;
                if entry.path().extension().and_then(|ext| ext.to_str()) != Some("json") {
                    continue;
                }
                let file = car_secrets::open_private_read(&entry.path())?;
                let receipt: CompletedProposalResponse = serde_json::from_reader(file)
                    .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
                self.validate_completed_response(&receipt)?;
                let pending = &receipt.finalization;
                if run_dir.path() != self.completed_response_run_root(&pending.run_id)
                    || entry.path()
                        != self.completed_response_path(
                            &pending.run_id,
                            &pending.client_id,
                            pending.requested_policy_session_id.as_deref(),
                            &pending.original_submission,
                        )?
                {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "completed proposal response path does not match its typed identity",
                    ));
                }
                self.claim_completed_proposal_owner(pending)?;
                receipts.push(receipt);
            }
        }
        Ok(receipts)
    }

    /// Backfill the content-addressed retry-owner index exactly once for
    /// receipts written before that index existed. Permanent receipts grow
    /// without bound by design, so normal daemon startup must never enumerate
    /// them. After this versioned checkpoint is durable, crash cleanup is
    /// driven by the bounded pending-finalization outbox instead.
    pub fn reconcile_completed_proposal_migration(&self) -> std::io::Result<()> {
        let checkpoint_path = self.completed_response_index_migration_path();
        match car_secrets::open_private_read(&checkpoint_path) {
            Ok(file) => {
                let checkpoint: CompletedProposalOwnerIndexMigration =
                    serde_json::from_reader(file).map_err(|error| {
                        std::io::Error::new(std::io::ErrorKind::InvalidData, error)
                    })?;
                if checkpoint.version > COMPLETED_PROPOSAL_OWNER_INDEX_MIGRATION_VERSION {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        format!(
                            "unsupported completed-proposal owner-index migration version {}",
                            checkpoint.version
                        ),
                    ));
                }
                if checkpoint.version == COMPLETED_PROPOSAL_OWNER_INDEX_MIGRATION_VERSION {
                    return Ok(());
                }
                // An older checkpoint indexed owners but did not guarantee
                // trace backfill plus authorized guard cleanup. Re-run the
                // streamed migration and publish v2 only after both finish.
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }

        // Stream permanent receipts one at a time. A corrupt or unexpectedly
        // large legacy row fails closed before the checkpoint, making the
        // migration crash-resumable without an unbounded all-receipts Vec.
        const MAX_LEGACY_RECEIPT_BYTES: u64 = 16 * 1024 * 1024;
        let receipts_root = self.completed_response_root();
        match std::fs::read_dir(&receipts_root) {
            Ok(run_dirs) => {
                for run_dir in run_dirs {
                    let run_dir = run_dir?;
                    if !run_dir.file_type()?.is_dir() || run_dir.file_type()?.is_symlink() {
                        continue;
                    }
                    car_secrets::ensure_private_dir(&run_dir.path())?;
                    for entry in std::fs::read_dir(run_dir.path())? {
                        let entry = entry?;
                        if entry.path().extension().and_then(|ext| ext.to_str()) != Some("json") {
                            continue;
                        }
                        let file = car_secrets::open_private_read(&entry.path())?;
                        if file.metadata()?.len() > MAX_LEGACY_RECEIPT_BYTES {
                            return Err(std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "completed proposal receipt exceeds migration byte limit",
                            ));
                        }
                        let receipt: CompletedProposalResponse = serde_json::from_reader(file)
                            .map_err(|error| {
                                std::io::Error::new(std::io::ErrorKind::InvalidData, error)
                            })?;
                        self.validate_completed_response(&receipt)?;
                        let pending = &receipt.finalization;
                        if run_dir.path() != self.completed_response_run_root(&pending.run_id)
                            || entry.path()
                                != self.completed_response_path(
                                    &pending.run_id,
                                    &pending.client_id,
                                    pending.requested_policy_session_id.as_deref(),
                                    &pending.original_submission,
                                )?
                        {
                            return Err(std::io::Error::new(
                                std::io::ErrorKind::InvalidData,
                                "completed proposal response path does not match its typed identity",
                            ));
                        }
                        self.claim_completed_proposal_owner(pending)?;
                        if self.run_started(&pending.run_id)?.is_some() {
                            self.ensure_proposal_turns(pending)?;
                        }
                        // Cleanup is part of the authorized migration. The
                        // checkpoint is deliberately published only after
                        // every receipt's guards have been durably cleared.
                        self.cleanup_completed_proposal_guards(&receipt)?;
                    }
                }
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
        let root = self.completed_response_index_root();
        self.ensure_private_dir(&root)?;
        ensure_backup_excluded(&root)?;
        sync_directory(root.parent().unwrap_or_else(|| Path::new(".")))?;
        let temp = root.join(format!(
            ".owner-index-migration.{}.tmp",
            uuid::Uuid::new_v4().simple()
        ));
        let write_result = (|| {
            let mut file = self.create_private_file(&temp)?;
            serde_json::to_writer(
                &mut file,
                &CompletedProposalOwnerIndexMigration {
                    version: COMPLETED_PROPOSAL_OWNER_INDEX_MIGRATION_VERSION,
                },
            )
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
            file.flush()?;
            file.sync_all()?;
            car_secrets::revalidate_private_path(&temp, &file)?;
            drop(file);
            car_secrets::atomic_replace_private_file(&temp, &checkpoint_path)?;
            sync_directory(&root)
        })();
        if write_result.is_err() {
            let _ = std::fs::remove_file(&temp);
        }
        write_result
    }

    pub fn completed_proposal_retry_owner(
        &self,
        requested_policy_session_id: Option<&str>,
        original_submission: &Value,
    ) -> std::io::Result<Option<(String, String)>> {
        Ok(self
            .read_completed_proposal_owner(requested_policy_session_id, original_submission)?
            .map(|owner| (owner.run_id, owner.client_id)))
    }

    /// Remove leftover pre-response guards only under a completed receipt's
    /// exact typed authority. Each deletion is independently durable; a fault
    /// leaves the receipt and any remaining guard for safe retry/restart.
    pub fn cleanup_completed_proposal_guards(
        &self,
        receipt: &CompletedProposalResponse,
    ) -> std::io::Result<()> {
        self.validate_completed_response(receipt)?;
        let pending = &receipt.finalization;
        // Remove the execution marker first. If either unlink boundary is
        // interrupted, the pending-finalization outbox remains as the bounded
        // startup cleanup index. Removing pending first could leave a lone
        // marker that was discoverable only by rescanning every permanent
        // completed receipt.
        let expected_marker = receipt.execution_marker()?;
        if let Some(existing) = self.execution_marker(&pending.run_id)? {
            if existing != expected_marker {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "completed response does not authorize this execution marker cleanup",
                ));
            }
            if self.failures.take(RunStoreFailurePoint::MarkerUnlink) {
                return Err(std::io::Error::other(
                    "injected execution marker unlink failure",
                ));
            }
            std::fs::remove_file(self.proposal_execution_path(&pending.run_id))?;
            self.sync_cleanup_directory(&self.proposal_execution_root())?;
        }

        let pending_path = self.proposal_outbox_path(&pending.run_id);
        match car_secrets::open_private_read(&pending_path) {
            Ok(file) => {
                let existing: PendingProposalFinalization = serde_json::from_reader(file)
                    .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
                existing.validate()?;
                if existing != *pending {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "completed response does not authorize this pending finalization cleanup",
                    ));
                }
                if self.failures.take(RunStoreFailurePoint::PendingUnlink) {
                    return Err(std::io::Error::other(
                        "injected pending proposal unlink failure",
                    ));
                }
                std::fs::remove_file(&pending_path)?;
                self.sync_cleanup_directory(&self.proposal_outbox_root())?;
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }
        Ok(())
    }

    fn sync_cleanup_directory(&self, root: &Path) -> std::io::Result<()> {
        if self.failures.take(RunStoreFailurePoint::DirectoryFsync) {
            return Err(std::io::Error::other(
                "injected proposal cleanup directory fsync failure",
            ));
        }
        sync_directory(root)
    }

    pub fn completed_proposal_response_value(
        &self,
        receipt: &CompletedProposalResponse,
    ) -> std::io::Result<Value> {
        self.validate_completed_response(receipt)?;
        if self
            .failures
            .take(RunStoreFailurePoint::ResponseSerialization)
        {
            return Err(std::io::Error::other(
                "injected completed proposal response serialization failure",
            ));
        }
        serde_json::to_value(receipt.proposal_result())
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))
    }

    /// Prepare the CAR-owned run tree for daemon startup. This is intentionally
    /// fallible: the daemon must refuse adoption/listening when the root or
    /// backup marker cannot be proven owner-private.
    pub fn prepare_storage(&self) -> std::io::Result<()> {
        self.ensure_root()
    }

    /// Path to a run's JSONL file: `runs/{agent_id}/{run_id}.jsonl`.
    fn run_path(&self, agent_id: &str, run_id: &str) -> PathBuf {
        self.root
            .join(sanitize(agent_id))
            .join(format!("{}.jsonl", sanitize(run_id)))
    }

    fn run_summary_index_path(agent_path: &Path) -> PathBuf {
        agent_path.join(RUN_SUMMARY_INDEX_FILE)
    }

    fn run_summary_sidecar_root(agent_path: &Path) -> PathBuf {
        agent_path.join(RUN_SUMMARY_SIDECAR_DIR)
    }

    fn run_summary_key(run_id: &str) -> [u8; RUN_SUMMARY_KEY_BYTES] {
        Sha256::digest(run_id.as_bytes()).into()
    }

    fn run_summary_sidecar_path(agent_path: &Path, key: &[u8; 32]) -> PathBuf {
        let name = key
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>();
        Self::run_summary_sidecar_root(agent_path).join(format!("{name}.json"))
    }

    fn run_trace_corruption_sidecar_root(agent_path: &Path) -> PathBuf {
        agent_path.join(RUN_TRACE_CORRUPTION_SIDECAR_DIR)
    }

    fn run_trace_corruption_sidecar_path(agent_path: &Path, key: &[u8; 32]) -> PathBuf {
        let name = key
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>();
        Self::run_trace_corruption_sidecar_root(agent_path).join(format!("{name}.json"))
    }

    fn read_run_trace_corruption_marker(
        &self,
        agent_path: &Path,
        agent_id: &str,
        run_id: &str,
    ) -> std::io::Result<Option<RunTraceCorruption>> {
        let key = Self::run_summary_key(run_id);
        let path = Self::run_trace_corruption_sidecar_path(agent_path, &key);
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let marker: RunTraceCorruptionMarker = serde_json::from_reader(file)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        if marker.run_id != run_id || marker.agent_id != agent_id {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "run trace corruption marker identity does not match its path",
            ));
        }
        Ok(Some(marker.corruption))
    }

    fn write_run_trace_corruption_marker(
        &self,
        agent_path: &Path,
        agent_id: &str,
        run_id: &str,
        corruption: &RunTraceCorruption,
    ) -> std::io::Result<()> {
        if let Some(existing) =
            self.read_run_trace_corruption_marker(agent_path, agent_id, run_id)?
        {
            if existing == *corruption {
                return Ok(());
            }
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "run trace corruption marker conflicts with an existing marker",
            ));
        }
        if self
            .failures
            .take(RunStoreFailurePoint::CorruptionMarkerWrite)
        {
            return Err(injected_storage_full());
        }
        let root = Self::run_trace_corruption_sidecar_root(agent_path);
        self.ensure_private_dir(&root)?;
        let path =
            Self::run_trace_corruption_sidecar_path(agent_path, &Self::run_summary_key(run_id));
        self.write_private_json_atomic(
            &root,
            &path,
            &RunTraceCorruptionMarker {
                run_id: run_id.to_string(),
                agent_id: agent_id.to_string(),
                corruption: corruption.clone(),
            },
        )
    }

    fn persist_run_trace_corruption_marker(
        &self,
        agent_path: &Path,
        agent_id: &str,
        run_id: &str,
        corruption: &RunTraceCorruption,
    ) -> std::io::Result<()> {
        let error = match self
            .write_run_trace_corruption_marker(agent_path, agent_id, run_id, corruption)
        {
            Ok(()) => return Ok(()),
            Err(error) => error,
        };
        if self
            .read_run_trace_corruption_marker(agent_path, agent_id, run_id)
            .ok()
            .flatten()
            .is_some()
        {
            return Err(error);
        }

        // If the independent marker cannot be made durable, invalidate the
        // derived healthy summary. The bounded list path then fails closed
        // instead of trusting stale state; the authoritative JSONL remains.
        let sidecar_root = Self::run_summary_sidecar_root(agent_path);
        let sidecar = Self::run_summary_sidecar_path(agent_path, &Self::run_summary_key(run_id));
        if self
            .failures
            .take(RunStoreFailurePoint::CorruptionSummaryInvalidate)
        {
            return Err(std::io::Error::new(
                error.kind(),
                format!("{error}; stale run summary invalidation also failed: permission denied"),
            ));
        }
        match std::fs::remove_file(&sidecar) {
            Ok(()) => sync_directory(&sidecar_root)?,
            Err(remove_error) if remove_error.kind() == std::io::ErrorKind::NotFound => {}
            Err(remove_error) => {
                return Err(std::io::Error::new(
                    error.kind(),
                    format!("{error}; stale run summary invalidation also failed: {remove_error}"),
                ));
            }
        }
        Err(error)
    }

    fn remember_run_trace_corruption(
        &self,
        agent_id: &str,
        run_id: &str,
        corruption: &RunTraceCorruption,
    ) {
        self.trace_corruptions
            .lock()
            .expect("run trace corruption registry poisoned")
            .insert(
                (agent_id.to_string(), run_id.to_string()),
                corruption.clone(),
            );
    }

    fn known_run_trace_corruption(
        &self,
        agent_id: &str,
        run_id: &str,
    ) -> Option<RunTraceCorruption> {
        self.trace_corruptions
            .lock()
            .expect("run trace corruption registry poisoned")
            .get(&(agent_id.to_string(), run_id.to_string()))
            .cloned()
    }

    /// Publish corruption discovered by a trust-bearing read through the same
    /// marker/summary fail-closed boundary used by writers. The in-process
    /// registry is updated first so even marker ENOSPC cannot make a later
    /// read or write treat the run as healthy in this process.
    fn publish_strict_read_corruption(
        &self,
        agent_path: &Path,
        agent_id: &str,
        run_id: &str,
        error: std::io::Error,
    ) -> std::io::Error {
        let Some(corruption) = trace_corruption_from_error(&error) else {
            return error;
        };
        self.remember_run_trace_corruption(agent_id, run_id, &corruption);
        match self.persist_run_trace_corruption_marker(agent_path, agent_id, run_id, &corruption) {
            Ok(()) => error,
            Err(source) => summary_refresh_error(source, corruption),
        }
    }

    fn apply_run_trace_corruption_marker(
        &self,
        agent_path: &Path,
        summary: &mut RunSummary,
    ) -> std::io::Result<()> {
        let corruption = match self.known_run_trace_corruption(&summary.agent_id, &summary.run_id) {
            Some(corruption) => Some(corruption),
            None => self.read_run_trace_corruption_marker(
                agent_path,
                &summary.agent_id,
                &summary.run_id,
            )?,
        };
        if let Some(corruption) = corruption {
            summary.status = RunStatus::Incomplete;
            summary.trace_corruption = Some(corruption);
        }
        Ok(())
    }

    fn read_summary_sidecar(
        &self,
        agent_path: &Path,
        key: &[u8; 32],
    ) -> std::io::Result<RunSummary> {
        let path = Self::run_summary_sidecar_path(agent_path, key);
        let file = car_secrets::open_private_read(&path)?;
        let summary: RunSummary = serde_json::from_reader(file)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        if Self::run_summary_key(&summary.run_id) != *key {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "run summary sidecar identity does not match its index key",
            ));
        }
        Ok(summary)
    }

    fn write_summary_sidecar(
        &self,
        agent_path: &Path,
        summary: &RunSummary,
    ) -> std::io::Result<()> {
        if let Some(gate) = &self.summary_write_gate {
            gate.wait_if_armed();
        }
        if self.failures.take(RunStoreFailurePoint::SummaryWrite) {
            return Err(injected_storage_full());
        }
        let root = Self::run_summary_sidecar_root(agent_path);
        self.ensure_private_dir(&root)?;
        let path =
            Self::run_summary_sidecar_path(agent_path, &Self::run_summary_key(&summary.run_id));
        self.write_private_json_atomic(&root, &path, summary)
    }

    fn write_summary_index(
        &self,
        agent_path: &Path,
        summaries: &[RunSummary],
    ) -> std::io::Result<()> {
        let mut ordered = summaries.to_vec();
        let mut next_sequence = ordered.iter().map(|row| row.sequence).max().unwrap_or(0);
        let mut missing = ordered
            .iter_mut()
            .filter(|row| row.sequence == 0)
            .collect::<Vec<_>>();
        missing.sort_by(|left, right| {
            left.started_at
                .cmp(&right.started_at)
                .then_with(|| right.run_id.cmp(&left.run_id))
        });
        for summary in missing {
            next_sequence = next_sequence.checked_add(1).ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "run summary sequence exhausted",
                )
            })?;
            summary.sequence = next_sequence;
        }
        ordered.sort_by(|left, right| right.sequence.cmp(&left.sequence));
        if ordered
            .windows(2)
            .any(|pair| pair[0].sequence == pair[1].sequence)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "run summary index contains duplicate sequences",
            ));
        }
        let sidecar_root = Self::run_summary_sidecar_root(agent_path);
        self.ensure_private_dir(&sidecar_root)?;
        let mut retained = std::collections::HashSet::new();
        let mut bytes = Vec::with_capacity(ordered.len() * RUN_SUMMARY_INDEX_RECORD_BYTES);
        for summary in &ordered {
            let key = Self::run_summary_key(&summary.run_id);
            retained.insert(key);
            self.write_summary_sidecar(agent_path, summary)?;
            bytes.extend_from_slice(&summary.sequence.to_be_bytes());
            bytes.extend_from_slice(&key);
        }
        if let Ok(entries) = std::fs::read_dir(&sidecar_root) {
            for entry in entries.flatten() {
                let path = entry.path();
                let Some(stem) = path.file_stem().and_then(|value| value.to_str()) else {
                    continue;
                };
                let is_retained = retained.iter().any(|key| {
                    key.iter()
                        .map(|byte| format!("{byte:02x}"))
                        .collect::<String>()
                        == stem
                });
                if !is_retained && path.extension().and_then(|value| value.to_str()) == Some("json")
                {
                    let _ = std::fs::remove_file(path);
                }
            }
        }
        let path = Self::run_summary_index_path(agent_path);
        let temp = agent_path.join(format!(
            ".run-summary-index-v2.{}.tmp",
            uuid::Uuid::new_v4().simple()
        ));
        let result = (|| {
            let mut file = self.create_private_file(&temp)?;
            file.write_all(&bytes)?;
            file.flush()?;
            file.sync_all()?;
            car_secrets::revalidate_private_path(&temp, &file)?;
            drop(file);
            car_secrets::atomic_replace_private_file(&temp, &path)?;
            sync_directory(agent_path)
        })();
        if result.is_err() {
            let _ = std::fs::remove_file(temp);
        }
        result
    }

    fn refresh_run_summary(
        &self,
        agent_id: &str,
        run_id: &str,
        add_to_order: bool,
    ) -> std::io::Result<()> {
        let agent_path = self.open_agent_dir_for_read(agent_id)?;
        // Every summary refresh for an agent shares the index path as its
        // serialization key. Terminal refreshes update one sidecar; new-run
        // refreshes rewrite every retained sidecar plus the index. The lock
        // starts before the scan so a slower, older refresh cannot publish a
        // stale summary after a newer lifecycle boundary.
        let index_path = Self::run_summary_index_path(&agent_path);
        let index_lock = self.append_lock(&index_path);
        let _guard = index_lock
            .lock()
            .map_err(|_| std::io::Error::other("run summary index lock poisoned"))?;
        let path = self.run_path(agent_id, run_id);
        let scan = match summarize_file_checked(&path) {
            Ok(scan) => scan,
            Err(error) => {
                let Some(corruption) = trace_corruption_from_error(&error) else {
                    return Err(error);
                };
                self.remember_run_trace_corruption(agent_id, run_id, &corruption);
                self.persist_run_trace_corruption_marker(
                    &agent_path,
                    agent_id,
                    run_id,
                    &corruption,
                )
                .map_err(|source| summary_refresh_error(source, corruption))?;
                return Err(error);
            }
        };
        if let Some(corruption) = &scan.corruption {
            self.remember_run_trace_corruption(agent_id, run_id, corruption);
            self.persist_run_trace_corruption_marker(&agent_path, agent_id, run_id, corruption)
                .map_err(|source| summary_refresh_error(source, corruption.clone()))?;
        }
        let mut summary = scan.summary.ok_or_else(|| {
            let error = std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "durable trace cannot be summarized for the run index",
            );
            match scan.corruption.clone() {
                Some(corruption) => summary_refresh_error(error, corruption),
                None => error,
            }
        })?;
        self.apply_run_trace_corruption_marker(&agent_path, &mut summary)?;
        let corruption = summary.trace_corruption.clone();
        let update = (|| {
            if !add_to_order {
                let key = Self::run_summary_key(run_id);
                summary.sequence = self.read_summary_sidecar(&agent_path, &key)?.sequence;
                self.write_summary_sidecar(&agent_path, &summary)?;
                return Ok(());
            }
            let mut summaries = Vec::new();
            if let Ok(mut index) = car_secrets::open_private_read(&index_path) {
                let len = index.metadata()?.len() as usize;
                if !len.is_multiple_of(RUN_SUMMARY_INDEX_RECORD_BYTES) {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "run summary index has a partial record",
                    ));
                }
                let mut record = [0u8; RUN_SUMMARY_INDEX_RECORD_BYTES];
                while index.read_exact(&mut record).is_ok() {
                    let sequence = u64::from_be_bytes(record[..8].try_into().expect("eight bytes"));
                    let key: [u8; RUN_SUMMARY_KEY_BYTES] =
                        record[8..].try_into().expect("summary key bytes");
                    let existing = self.read_summary_sidecar(&agent_path, &key)?;
                    if existing.sequence != sequence {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "run summary sidecar sequence does not match its index record",
                        ));
                    }
                    if existing.run_id != run_id {
                        summaries.push(existing);
                    } else {
                        summary.sequence = sequence;
                    }
                }
            }
            summaries.push(summary.clone());
            self.write_summary_index(&agent_path, &summaries)
        })();
        preserve_summary_corruption(update, &corruption)?;
        reject_corrupt_summary(&summary)
    }

    /// Ensure the `runs/` root exists with `0700` perms and is marked
    /// backup-excluded. Idempotent. Called lazily on the first append so
    /// constructing a `RunStore` is free (no disk touch until a run is
    /// actually recorded).
    fn ensure_root(&self) -> std::io::Result<()> {
        self.ensure_private_dir(&self.root)?;
        ensure_backup_excluded(&self.root)?;
        Ok(())
    }

    /// Validate and harden an existing runs root without creating a missing
    /// store as a side effect of a replay/list request.
    fn open_root_for_read(&self) -> std::io::Result<()> {
        std::fs::symlink_metadata(&self.root)?;
        self.ensure_root()
    }

    /// Ensure an agent's run dir exists `0700`.
    fn ensure_agent_dir(&self, agent_id: &str) -> std::io::Result<PathBuf> {
        self.ensure_root()?;
        let dir = self.root.join(sanitize(agent_id));
        self.ensure_private_dir(&dir)?;
        Ok(dir)
    }

    /// Validate and harden an existing agent directory without creating an
    /// empty directory for an unknown replay/list key.
    fn open_agent_dir_for_read(&self, agent_id: &str) -> std::io::Result<PathBuf> {
        self.open_root_for_read()?;
        let dir = self.root.join(sanitize(agent_id));
        std::fs::symlink_metadata(&dir)?;
        self.ensure_private_dir(&dir)?;
        Ok(dir)
    }

    /// Append one or more `RunRecord`s to a run's file, creating it `0600`
    /// on first write. Records are written one JSONL line each, in order.
    ///
    /// This is the single low-level flush primitive the wiring calls at
    /// each boundary: `RunStarted` on `runs.start`, `RunTurn`s as the
    /// recorder produces them, and the terminal `RunEnded`/`Incomplete` on
    /// `runs.complete`/disconnect.
    pub fn append_records(
        &self,
        agent_id: &str,
        run_id: &str,
        records: &[RunRecord],
    ) -> std::io::Result<()> {
        if records.is_empty() {
            return Ok(());
        }
        self.ensure_agent_dir(agent_id)?;
        let path = self.run_path(agent_id, run_id);
        let append_lock = self.append_lock(&path);
        let _guard = append_lock
            .lock()
            .map_err(|_| std::io::Error::other("run append lock poisoned"))?;
        let existed_before_open = path.exists();
        let mut file = self.open_private_append(&path)?;
        if self.failures.take(RunStoreFailurePoint::Write) {
            return Err(injected_storage_full());
        }
        append_jsonl_batch_to_path(&path, &mut file, records)?;
        self.durable_receipt(&path, &mut file, existed_before_open)
    }

    /// Append the `RunStarted` line + create the run file (`runs.start`).
    pub fn write_started(&self, started: &car_proto::RunStarted) -> std::io::Result<()> {
        if started.run_id.is_empty()
            || started.agent_id.is_empty()
            || started.client_id.as_deref().is_none_or(str::is_empty)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "active RunStarted requires client_id",
            ));
        }
        self.ensure_boundary_record(
            &started.agent_id,
            &started.run_id,
            RunRecord::Started(started.clone()),
        )?;
        self.refresh_run_summary(&started.agent_id, &started.run_id, true)
    }

    /// Append `RunTurn` records (the recorder's per-proposal output).
    pub fn append_turns(
        &self,
        agent_id: &str,
        run_id: &str,
        turns: &[RunRecord],
    ) -> std::io::Result<()> {
        if let Some(gate) = &self.append_gate {
            gate.wait_if_armed();
        }
        self.append_records(agent_id, run_id, turns)?;
        if let Err(error) = self.refresh_run_summary(agent_id, run_id, false) {
            if is_trace_corruption_error(&error) {
                return Err(error);
            }
            tracing::error!(%agent_id, %run_id, %error, "run summary index update deferred until startup repair");
        }
        Ok(())
    }

    /// Read the durable summary's corruption marker without materializing the
    /// trace. Active subscribe reads this off the async lock path, then
    /// revalidates live state before it trusts a snapshot or registers.
    pub fn run_trace_corruption_for(
        &self,
        agent_id: &str,
        run_id: &str,
    ) -> std::io::Result<Option<RunTraceCorruption>> {
        if let Some(gate) = &self.summary_read_gate {
            gate.wait_if_armed();
        }
        if let Some(corruption) = self.known_run_trace_corruption(agent_id, run_id) {
            return Ok(Some(corruption));
        }
        let agent_path = match self.open_agent_dir_for_read(agent_id) {
            Ok(path) => path,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        if let Some(corruption) =
            self.read_run_trace_corruption_marker(&agent_path, agent_id, run_id)?
        {
            return Ok(Some(corruption));
        }
        let key = Self::run_summary_key(run_id);
        match self.read_summary_sidecar(&agent_path, &key) {
            Ok(summary) => {
                if summary.run_id != run_id || summary.agent_id != agent_id {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "run summary sidecar owner does not match requested run",
                    ));
                }
                Ok(summary.trace_corruption)
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// Ensure the exact action trace authenticated by a durable proposal
    /// finalization exists once before the terminal journal/receipt can
    /// advance. Existing exact rows make retries idempotent; partial or
    /// conflicting rows fail closed.
    pub fn ensure_proposal_turns(
        &self,
        pending: &PendingProposalFinalization,
    ) -> std::io::Result<ProposalTraceEnsure> {
        if let Some(gate) = &self.append_gate {
            gate.wait_if_armed();
        }
        pending.validate()?;
        let started = self.durable_run_started(&pending.run_id)?;
        match self.execution_marker(&pending.run_id)? {
            Some(marker) => pending.validate_provenance(&started, &marker)?,
            None => {
                let completed = self.completed_proposal(
                    &pending.run_id,
                    &pending.client_id,
                    pending.requested_policy_session_id.as_deref(),
                    &pending.original_submission,
                )?;
                if completed.as_ref().map(|receipt| &receipt.finalization) != Some(pending) {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "proposal trace has neither its execution marker nor an exact completed receipt",
                    ));
                }
            }
        }
        let mut expected = crate::run_trace::record_turns(
            &pending.final_proposal,
            &pending.proposal_result.results,
            0,
        );
        for record in &mut expected {
            let RunRecord::Turn(turn) = record else {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "proposal trace generator returned a non-turn record",
                ));
            };
            if !crate::handler::enforce_proposal_turn_byte_cap(turn) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "proposal turn exceeds the durable byte limit without changing authenticated parameters",
                ));
            }
        }
        if expected.is_empty() {
            return Ok(ProposalTraceEnsure {
                records: expected,
                appended: false,
            });
        }

        let path = self.run_path(&started.agent_id, &pending.run_id);
        let append_lock = self.append_lock(&path);
        let _guard = append_lock
            .lock()
            .map_err(|_| std::io::Error::other("proposal trace append lock poisoned"))?;
        let file = car_secrets::open_private_read(&path)?;
        let mut turn_count = 0usize;
        let mut matching = Vec::new();
        let scan = scan_records(&file, |record| {
            if let RunRecord::Turn(turn) = record {
                turn_count = turn_count.saturating_add(1);
                if turn.proposal_id.as_deref() == Some(pending.final_proposal_id.as_str()) {
                    matching.push(RunRecord::Turn(turn));
                }
            }
        });
        if let Err(error) = scan {
            let error = scan_error_to_io(error);
            let _ = self.refresh_run_summary(&started.agent_id, &pending.run_id, false);
            return Err(error);
        }
        car_secrets::revalidate_private_path(&path, &file)?;

        let to_append = if !matching.is_empty() {
            let start = matching
                .first()
                .and_then(|record| match record {
                    RunRecord::Turn(turn) => Some(turn.index),
                    _ => None,
                })
                .unwrap_or(0);
            for (offset, record) in expected.iter_mut().enumerate() {
                if let RunRecord::Turn(turn) = record {
                    turn.index = start + offset;
                }
            }
            let exact_prefix = matching.len() <= expected.len()
                && matching.iter().zip(&expected).all(|(left, right)| {
                    serde_json::to_value(left).ok() == serde_json::to_value(right).ok()
                });
            if !exact_prefix || turn_count != start.saturating_add(matching.len()) {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "durable proposal trace conflicts with final proposal identity or has later rows",
                ));
            }
            if matching.len() == expected.len() {
                return Ok(ProposalTraceEnsure {
                    records: matching,
                    appended: false,
                });
            }
            expected[matching.len()..].to_vec()
        } else {
            for (offset, record) in expected.iter_mut().enumerate() {
                if let RunRecord::Turn(turn) = record {
                    turn.index = turn_count + offset;
                }
            }
            expected.clone()
        };

        if turn_count.saturating_add(to_append.len()) > crate::session::RECORD_TURNS_RUN_CEILING {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "proposal trace would exceed the durable run turn ceiling",
            ));
        }

        let existed_before_open = path.exists();
        let mut append = self.open_private_append(&path)?;
        if self.failures.take(RunStoreFailurePoint::Write) {
            return Err(injected_storage_full());
        }
        append_jsonl_batch_to_path(&path, &mut append, &to_append)?;
        self.durable_receipt(&path, &mut append, existed_before_open)?;
        if let Err(error) = self.refresh_run_summary(&started.agent_id, &pending.run_id, false) {
            if is_trace_corruption_error(&error) {
                return Err(error);
            }
            tracing::error!(run_id = %pending.run_id, %error, "proposal trace summary update deferred until startup repair");
        }
        Ok(ProposalTraceEnsure {
            records: expected,
            appended: true,
        })
    }

    /// Append the terminal `RunEnded` line (`runs.complete` or the
    /// disconnect-`Incomplete` path).
    pub fn write_ended(&self, ended: &car_proto::RunEnded) -> std::io::Result<()> {
        if ended.run_id.is_empty()
            || ended.agent_id.is_empty()
            || ended.client_id.as_deref().is_none_or(str::is_empty)
            || ended.completion_digest.as_deref().is_none_or(str::is_empty)
        {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "active RunEnded requires client_id and completion_digest",
            ));
        }
        let expected_digest = crate::session::run_completion_digest(&ended.termination)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        if ended.completion_digest.as_deref() != Some(expected_digest.as_str()) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "RunEnded completion_digest does not match JCS RunTermination",
            ));
        }
        self.ensure_boundary_record(
            &ended.agent_id,
            &ended.run_id,
            RunRecord::Ended(ended.clone()),
        )?;
        self.refresh_run_summary(&ended.agent_id, &ended.run_id, false)
    }

    /// Durably append the body-free cancellation request before attempting
    /// control. The exact key/preimage is idempotent; another key cannot race
    /// the active request.
    pub fn write_cancellation_requested(
        &self,
        agent_id: &str,
        requested: &car_proto::RunCancellationRequested,
    ) -> std::io::Result<()> {
        self.ensure_boundary_record(
            agent_id,
            &requested.run_id,
            RunRecord::CancellationRequested(requested.clone()),
        )?;
        self.refresh_run_summary(agent_id, &requested.run_id, false)
    }

    /// Persist an unconfirmed cancellation receipt. Confirmed cancellation is
    /// represented by the terminal `RunEnded::Cancelled` row instead.
    pub fn write_cancellation_result(
        &self,
        agent_id: &str,
        result: &car_proto::RunCancelResponse,
    ) -> std::io::Result<()> {
        self.ensure_boundary_record(
            agent_id,
            &result.run_id,
            RunRecord::CancellationResult(result.clone()),
        )?;
        self.refresh_run_summary(agent_id, &result.run_id, false)
    }

    fn append_lock(&self, path: &Path) -> Arc<Mutex<()>> {
        let mut locks = self
            .append_locks
            .lock()
            .expect("run append-lock registry poisoned");
        if let Some(lock) = locks.get(path).and_then(Weak::upgrade) {
            return lock;
        }
        locks.retain(|_, lock| lock.strong_count() > 0);
        let lock = Arc::new(Mutex::new(()));
        locks.insert(path.to_path_buf(), Arc::downgrade(&lock));
        lock
    }

    fn ensure_boundary_record(
        &self,
        agent_id: &str,
        run_id: &str,
        record: RunRecord,
    ) -> std::io::Result<()> {
        self.ensure_agent_dir(agent_id)?;
        let path = self.run_path(agent_id, run_id);
        let append_lock = self.append_lock(&path);
        let _guard = append_lock
            .lock()
            .map_err(|_| std::io::Error::other("run append lock poisoned"))?;
        let existed_before_open = path.exists();
        let mut file = self.open_private_append(&path)?;
        car_secrets::revalidate_private_path(&path, &file)?;
        let existing = match load_records(&file) {
            Ok(records) => records,
            Err(error) => {
                // Publish the fail-closed summary marker before returning the
                // corruption error to the attempted boundary writer.
                let _ = self.refresh_run_summary(agent_id, run_id, false);
                return Err(error);
            }
        };

        let exact_exists = match &record {
            RunRecord::Started(wanted) => {
                if let Some(found) = existing.iter().find_map(|row| match row {
                    RunRecord::Started(started) => Some(started),
                    _ => None,
                }) {
                    if found != wanted {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::AlreadyExists,
                            "run_id is already reserved by a different RunStarted owner/preimage",
                        ));
                    }
                    true
                } else {
                    if !existing.is_empty() {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "non-empty run trace is missing its RunStarted boundary",
                        ));
                    }
                    false
                }
            }
            RunRecord::Ended(wanted) => {
                let started = existing.iter().find_map(|row| match row {
                    RunRecord::Started(started) => Some(started),
                    _ => None,
                });
                let Some(started) = started else {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "RunEnded cannot precede RunStarted",
                    ));
                };
                if started.run_id != wanted.run_id
                    || started.agent_id != wanted.agent_id
                    || started.client_id != wanted.client_id
                {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::PermissionDenied,
                        "RunEnded owner does not match durable RunStarted",
                    ));
                }
                if let Some(found) = existing.iter().find_map(|row| match row {
                    RunRecord::Ended(ended) => Some(ended),
                    _ => None,
                }) {
                    if !same_run_ended(found, wanted) {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::AlreadyExists,
                            "run already has a different durable terminal",
                        ));
                    }
                    true
                } else {
                    false
                }
            }
            RunRecord::Turn(_) => false,
            RunRecord::CancellationRequested(wanted) => {
                let started = existing.iter().find_map(|row| match row {
                    RunRecord::Started(started) => Some(started),
                    _ => None,
                });
                let Some(started) = started else {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "cancellation request cannot precede RunStarted",
                    ));
                };
                if started.run_id != wanted.run_id || started.agent_id != agent_id {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::PermissionDenied,
                        "cancellation request owner does not match durable RunStarted",
                    ));
                }
                if existing
                    .iter()
                    .any(|row| matches!(row, RunRecord::Ended(_)))
                {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::AlreadyExists,
                        "run is already terminal",
                    ));
                }
                if let Some(found) = existing.iter().find_map(|row| match row {
                    RunRecord::CancellationRequested(row) => Some(row),
                    _ => None,
                }) {
                    if found != wanted {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::AlreadyExists,
                            "run already has a different cancellation request",
                        ));
                    }
                    true
                } else {
                    false
                }
            }
            RunRecord::CancellationResult(wanted) => {
                if wanted.status != car_proto::RunCancellationStatus::TerminationUnconfirmed
                    || wanted.terminal_digest.is_some()
                {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidInput,
                        "only body-free termination_unconfirmed receipts are nonterminal records",
                    ));
                }
                let request = existing.iter().find_map(|row| match row {
                    RunRecord::CancellationRequested(row) => Some(row),
                    _ => None,
                });
                let Some(request) = request else {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "cancellation result cannot precede its request",
                    ));
                };
                if request.run_id != wanted.run_id
                    || request.idempotency_key != wanted.idempotency_key
                    || request.reason_digest != wanted.reason_digest
                    || request.principal != wanted.principal
                    || request.action_id != wanted.action_id
                    || request.request_id != wanted.request_id
                {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "cancellation result conflicts with its durable request",
                    ));
                }
                if existing
                    .iter()
                    .any(|row| matches!(row, RunRecord::Ended(_)))
                {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::AlreadyExists,
                        "run is already terminal",
                    ));
                }
                if let Some(found) = existing.iter().find_map(|row| match row {
                    RunRecord::CancellationResult(row) => Some(row),
                    _ => None,
                }) {
                    if found != wanted {
                        return Err(std::io::Error::new(
                            std::io::ErrorKind::AlreadyExists,
                            "run already has a different cancellation result",
                        ));
                    }
                    true
                } else {
                    false
                }
            }
        };

        if !exact_exists {
            if self.failures.take(RunStoreFailurePoint::Write) {
                return Err(injected_storage_full());
            }
            append_jsonl_batch_to_path(&path, &mut file, &[record])?;
        }
        self.durable_receipt(&path, &mut file, existed_before_open)
    }

    fn durable_receipt(
        &self,
        path: &Path,
        file: &mut File,
        existed_before_open: bool,
    ) -> std::io::Result<()> {
        if self.failures.take(RunStoreFailurePoint::Flush) {
            return Err(std::io::Error::other("injected run-store flush failure"));
        }
        file.flush()?;
        if self.failures.take(RunStoreFailurePoint::Fsync) {
            return Err(std::io::Error::other("injected run-store fsync failure"));
        }
        file.sync_all()?;
        if !existed_before_open {
            if let Some(parent) = path.parent() {
                sync_directory(parent)?;
            }
        }
        car_secrets::revalidate_private_path(path, file)
    }

    /// Load a run's full ordered trace from disk by `run_id` — the U5
    /// `runs.get_trace` read path. Works after a restart when memory is
    /// empty. Resolves `run_id -> agent_id` by scanning the tree, then
    /// reads the JSONL. A malformed unterminated final crash tail is ignored;
    /// committed corruption makes this compatibility wrapper return `None`.
    /// Returns `None` when no file exists for the `run_id`.
    pub fn get_run_trace(&self, run_id: &str) -> Option<Vec<RunRecord>> {
        self.get_run_trace_checked(run_id).ok().flatten()
    }

    /// Strict replay read used by trust-bearing RPC surfaces. A malformed
    /// newline-terminated row rejects the trace; only a torn final row is
    /// ignored as an uncommitted crash tail.
    pub fn get_run_trace_checked(&self, run_id: &str) -> std::io::Result<Option<Vec<RunRecord>>> {
        let Some((path, file)) = self.resolve_run_file(run_id) else {
            return Ok(None);
        };
        let Some(agent_path) = path.parent() else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "run trace path has no owning agent directory",
            ));
        };
        let Some(agent_id) = agent_path.file_name().and_then(|value| value.to_str()) else {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "run trace path has no valid owning agent id",
            ));
        };
        load_private_records(&path, &file)
            .map(Some)
            .map_err(|error| {
                self.publish_strict_read_corruption(agent_path, agent_id, run_id, error)
            })
    }

    /// Load a run's trace given both keys (cheaper — no tree scan). Used
    /// by `list_runs` internally and available to callers that already
    /// know the owning agent.
    pub fn get_run_trace_for(&self, agent_id: &str, run_id: &str) -> Option<Vec<RunRecord>> {
        self.get_run_trace_for_checked(agent_id, run_id)
            .ok()
            .flatten()
    }

    pub fn get_run_trace_for_checked(
        &self,
        agent_id: &str,
        run_id: &str,
    ) -> std::io::Result<Option<Vec<RunRecord>>> {
        let agent_path = match self.open_agent_dir_for_read(agent_id) {
            Ok(path) => path,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let path = self.run_path(agent_id, run_id);
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        load_private_records(&path, &file)
            .map(Some)
            .map_err(|error| {
                self.publish_strict_read_corruption(&agent_path, agent_id, run_id, error)
            })
    }

    /// Stream one bounded page from a run's JSONL trace. `limit + 1`
    /// records are retained only to determine whether a continuation exists;
    /// accumulated history is never materialized by the dashboard read path.
    pub fn get_run_trace_page_for(
        &self,
        agent_id: &str,
        run_id: &str,
        cursor: usize,
        limit: usize,
    ) -> std::io::Result<Option<(Vec<RunRecord>, Option<usize>)>> {
        let agent_path = match self.open_agent_dir_for_read(agent_id) {
            Ok(path) => path,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let path = self.run_path(agent_id, run_id);
        let file = match car_secrets::open_private_read(&path) {
            Ok(file) => file,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let mut records = Vec::with_capacity(limit.saturating_add(1));
        let mut valid_index = 0usize;
        if let Err(error) = scan_records(&file, |record| {
            if valid_index >= cursor && records.len() <= limit {
                records.push(record);
            }
            valid_index = valid_index.saturating_add(1);
        }) {
            let error = scan_error_to_io(error);
            return Err(self.publish_strict_read_corruption(&agent_path, agent_id, run_id, error));
        }
        car_secrets::revalidate_private_path(&path, &file)?;
        let has_more = records.len() > limit;
        records.truncate(limit);
        let next_cursor = has_more.then_some(cursor.saturating_add(records.len()));
        Ok(Some((records, next_cursor)))
    }

    /// Stream a bounded turns-only page for `runs.subscribe`. The exact total
    /// comes from the durable summary sidecar, so returning `live_cursor` never
    /// requires materializing the trace.
    pub fn get_run_turn_page_for(
        &self,
        agent_id: &str,
        run_id: &str,
        cursor: usize,
        limit: usize,
    ) -> std::io::Result<Option<(Vec<RunRecord>, Option<usize>, usize, RunStatus)>> {
        let agent_path = match self.open_agent_dir_for_read(agent_id) {
            Ok(path) => path,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        let key = Self::run_summary_key(run_id);
        let mut summary = match self.read_summary_sidecar(&agent_path, &key) {
            Ok(summary) if summary.run_id == run_id && summary.agent_id == agent_id => summary,
            Ok(_) => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "run summary identity does not match the requested trace",
                ))
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        self.apply_run_trace_corruption_marker(&agent_path, &mut summary)?;
        reject_corrupt_summary(&summary)?;
        if cursor > summary.turn_count {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                format!(
                    "runs.subscribe cursor {cursor} exceeds live_cursor {}",
                    summary.turn_count
                ),
            ));
        }
        let path = self.run_path(agent_id, run_id);
        let file = car_secrets::open_private_read(&path)?;
        let mut turns = Vec::with_capacity(limit.saturating_add(1));
        let mut turn_index = 0usize;
        if let Err(error) = scan_records(&file, |record| {
            if !matches!(record, RunRecord::Turn(_)) {
                return;
            }
            if turn_index >= cursor && turns.len() <= limit {
                turns.push(record);
            }
            turn_index = turn_index.saturating_add(1);
        }) {
            let error = scan_error_to_io(error);
            return Err(self.publish_strict_read_corruption(&agent_path, agent_id, run_id, error));
        }
        car_secrets::revalidate_private_path(&path, &file)?;
        if turn_index < summary.turn_count && turns.len() <= limit {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "run trace ended before its durable summary turn count",
            ));
        }
        let has_more = turns.len() > limit;
        turns.truncate(limit);
        let next_cursor = has_more.then_some(cursor.saturating_add(turns.len()));
        Ok(Some((
            turns,
            next_cursor,
            summary.turn_count,
            summary.status,
        )))
    }

    /// Read a newest-first run-summary page through the durable fixed-record
    /// order index. The page performs at most `limit + 1` sidecar reads and no
    /// run-directory enumeration or trace scan.
    pub fn list_runs_page(
        &self,
        agent_id: &str,
        cursor: usize,
        limit: usize,
    ) -> std::io::Result<(Vec<RunSummary>, Option<usize>)> {
        let agent_path = match self.open_agent_dir_for_read(agent_id) {
            Ok(path) => path,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                return Ok((Vec::new(), None))
            }
            Err(error) => return Err(error),
        };
        let index_path = Self::run_summary_index_path(&agent_path);
        let mut index = car_secrets::open_private_read(&index_path)?;
        let byte_len = index.metadata()?.len() as usize;
        if !byte_len.is_multiple_of(RUN_SUMMARY_INDEX_RECORD_BYTES) {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "run summary index has a partial record",
            ));
        }
        let total = byte_len / RUN_SUMMARY_INDEX_RECORD_BYTES;
        if total == 0 {
            return Ok((Vec::new(), None));
        }

        // `0` means the current head. Every non-zero cursor is an exclusive
        // immutable sequence bound, so inserts at the head cannot shift a
        // continuation and duplicate/skip rows. Locate the first record with
        // sequence < cursor using O(log n) fixed-record seeks.
        let mut start = 0usize;
        if cursor != 0 {
            let cursor = u64::try_from(cursor).map_err(|_| {
                std::io::Error::new(std::io::ErrorKind::InvalidInput, "cursor overflow")
            })?;
            let mut low = 0usize;
            let mut high = total;
            while low < high {
                let mid = low + (high - low) / 2;
                index.seek(SeekFrom::Start(
                    (mid * RUN_SUMMARY_INDEX_RECORD_BYTES) as u64,
                ))?;
                let mut sequence = [0u8; 8];
                index.read_exact(&mut sequence)?;
                if u64::from_be_bytes(sequence) >= cursor {
                    low = mid + 1;
                } else {
                    high = mid;
                }
            }
            start = low;
        }
        if start >= total {
            return Ok((Vec::new(), None));
        }
        index.seek(SeekFrom::Start(
            (start * RUN_SUMMARY_INDEX_RECORD_BYTES) as u64,
        ))?;
        let count = limit.saturating_add(1).min(total - start);
        let mut summaries = Vec::with_capacity(count);
        for _ in 0..count {
            let mut record = [0u8; RUN_SUMMARY_INDEX_RECORD_BYTES];
            index.read_exact(&mut record)?;
            let sequence = u64::from_be_bytes(record[..8].try_into().expect("eight bytes"));
            let key: [u8; RUN_SUMMARY_KEY_BYTES] =
                record[8..].try_into().expect("summary key bytes");
            let mut summary = self.read_summary_sidecar(&agent_path, &key)?;
            if summary.agent_id != agent_id || summary.sequence != sequence {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "run summary index does not match its durable sidecar",
                ));
            }
            self.apply_run_trace_corruption_marker(&agent_path, &mut summary)?;
            summaries.push(summary);
        }
        let has_more = summaries.len() > limit;
        summaries.truncate(limit);
        let next_cursor = if has_more {
            summaries
                .last()
                .map(|summary| {
                    usize::try_from(summary.sequence).map_err(|_| {
                        std::io::Error::new(
                            std::io::ErrorKind::InvalidData,
                            "run summary sequence cannot be represented by the wire cursor",
                        )
                    })
                })
                .transpose()?
        } else {
            None
        };
        Ok((summaries, next_cursor))
    }

    /// List an agent's runs newest-first — the U5 `runs.list` read path.
    /// Each summary is built from the run file's records (head for
    /// `RunStarted`, tail for the terminal record, count of `Turn`s).
    /// Returns an empty Vec for an agent with no runs (the empty-state).
    pub fn list_runs(&self, agent_id: &str) -> Vec<RunSummary> {
        let Ok(dir) = self.open_agent_dir_for_read(agent_id) else {
            return Vec::new();
        };
        let mut out = Vec::new();
        let Ok(entries) = std::fs::read_dir(&dir) else {
            return out;
        };
        for entry in entries {
            let Ok(entry) = entry else {
                return Vec::new();
            };
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                continue;
            }
            if let Some(mut summary) = summarize_file(&path) {
                if self
                    .apply_run_trace_corruption_marker(&dir, &mut summary)
                    .is_err()
                {
                    return Vec::new();
                }
                out.push(summary);
            }
        }
        // Newest first by start time.
        out.sort_by(|a, b| {
            b.started_at
                .cmp(&a.started_at)
                .then_with(|| a.run_id.cmp(&b.run_id))
        });
        out
    }

    /// Visit only the durable lifecycle boundaries for one trace at a time.
    /// Startup reconciliation needs neither turns nor a process-wide snapshot;
    /// streaming each file prevents accumulated newsroom history from being
    /// materialized before the daemon can listen and schedule.
    pub fn visit_run_boundaries<F>(&self, mut visitor: F)
    where
        F: FnMut(
            car_proto::RunStarted,
            Option<car_proto::RunEnded>,
            Option<car_proto::RunCancellationRequested>,
            Option<car_proto::RunCancelResponse>,
        ),
    {
        if self.open_root_for_read().is_err() {
            return;
        }
        let Ok(agent_dirs) = std::fs::read_dir(&self.root) else {
            return;
        };
        for agent in agent_dirs.flatten() {
            let Ok(file_type) = agent.file_type() else {
                continue;
            };
            if !file_type.is_dir() || file_type.is_symlink() {
                continue;
            }
            let Ok(entries) = std::fs::read_dir(agent.path()) else {
                continue;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().and_then(|ext| ext.to_str()) != Some("jsonl") {
                    continue;
                }
                let Ok(file) = car_secrets::open_private_read(&path) else {
                    continue;
                };
                if let Some((started, ended, requested, result)) =
                    load_private_run_boundaries(&path, &file)
                {
                    visitor(started, ended, requested, result);
                }
            }
        }
    }

    /// Resolve `run_id -> path` by scanning `runs/*/{run_id}.jsonl`. U5's
    /// `runs.get_trace` takes only a `run_id`, so the owning agent must be
    /// discovered. Returns the first match (run ids are uuids — unique).
    fn resolve_run_file(&self, run_id: &str) -> Option<(PathBuf, File)> {
        self.open_root_for_read().ok()?;
        let file_name = format!("{}.jsonl", sanitize(run_id));
        let agent_dirs = std::fs::read_dir(&self.root).ok()?;
        for agent in agent_dirs {
            let agent = agent.ok()?;
            let file_type = agent.file_type().ok()?;
            if !file_type.is_dir() || file_type.is_symlink() {
                continue;
            }
            car_secrets::ensure_private_dir(&agent.path()).ok()?;
            let candidate = agent.path().join(&file_name);
            match car_secrets::open_private_read(&candidate) {
                Ok(file) => return Some((candidate, file)),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                Err(_) => return None,
            }
        }
        None
    }

    /// Resolve the owning `agent_id` for a `run_id` from disk. Mirrors
    /// [`Self::resolve_run_file`] but returns the agent dir name — U5's
    /// authorization check (KTD10) needs `run_id -> agent_id` to verify
    /// ownership before serving a trace.
    pub fn agent_for_run(&self, run_id: &str) -> Option<String> {
        let (path, _file) = self.resolve_run_file(run_id)?;
        path.parent()
            .and_then(Path::file_name)
            .and_then(|s| s.to_str())
            .map(str::to_string)
    }

    /// Retention GC (R6) — call on daemon boot. Per agent: keep the most
    /// recent `max_per_agent` **completed** runs and drop any completed
    /// run older than `max_age_days`, whichever is more restrictive. An
    /// in-progress run (no terminal record) is NEVER evicted. Returns the
    /// number of run files removed.
    pub fn gc(&self) -> usize {
        let mut removed = 0;
        if self.open_root_for_read().is_err() {
            return 0;
        }
        let Ok(agent_dirs) = std::fs::read_dir(&self.root) else {
            return 0;
        };
        let cutoff = Utc::now() - chrono::Duration::days(self.retention.max_age_days);
        for agent in agent_dirs {
            let Ok(agent) = agent else {
                return removed;
            };
            let Ok(file_type) = agent.file_type() else {
                return removed;
            };
            if !file_type.is_dir() || file_type.is_symlink() {
                continue;
            }
            let agent_path = agent.path();
            if car_secrets::ensure_private_dir(&agent_path).is_err() {
                return removed;
            }
            removed += self.gc_agent_dir(&agent_path, cutoff);
        }
        removed
    }

    /// Adopt crash-orphaned runs at boot (FIX 4). A daemon crash mid-run
    /// leaves an on-disk run with `RunStarted` (+ `Turn`s) but no terminal
    /// `RunEnded`, so it reads `InProgress` forever and the GC — which never
    /// evicts an in-progress run — can never reclaim it. The file leaks
    /// across every crash.
    ///
    /// This runs at store construction/boot, BEFORE `gc()`. At that moment
    /// the in-memory `runs` map is always empty, so any run that is
    /// `InProgress` on disk cannot have a live harness writing to it — it is
    /// necessarily a crashed prior process. We append an `Incomplete`
    /// terminal `RunEnded` marker to adopt it, making it terminal and thus
    /// age-GC-eligible (so a later `gc()` in the same boot can reclaim it).
    ///
    /// Returns the number of runs adopted. Best-effort: an unwritable file is
    /// skipped rather than failing startup.
    pub fn adopt_orphans(&self) -> usize {
        let mut adopted = 0;
        if self.open_root_for_read().is_err() {
            return 0;
        }
        let Ok(agent_dirs) = std::fs::read_dir(&self.root) else {
            return 0;
        };
        let now = Utc::now();
        for agent in agent_dirs {
            let Ok(agent) = agent else {
                return adopted;
            };
            let Ok(file_type) = agent.file_type() else {
                return adopted;
            };
            if !file_type.is_dir() || file_type.is_symlink() {
                continue;
            }
            let agent_path = agent.path();
            if car_secrets::ensure_private_dir(&agent_path).is_err() {
                return adopted;
            }
            let Ok(entries) = std::fs::read_dir(&agent_path) else {
                continue;
            };
            for entry in entries {
                let Ok(entry) = entry else {
                    return adopted;
                };
                let path = entry.path();
                if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                    continue;
                }
                let Some(summary) = summarize_file(&path) else {
                    continue;
                };
                if summary.status != RunStatus::InProgress {
                    continue;
                }
                // A pre-dispatch marker with no exact result means the daemon
                // may have died after an irreversible effect. Preserve the
                // open run as quarantined/outcome-unknown; an automatic
                // Incomplete terminal would hide the unresolved proposal and
                // invite an unsafe retry.
                let pending_state = self.pending_proposal(&summary.run_id);
                let execution_state = self.execution_marker(&summary.run_id);
                if !matches!(pending_state, Ok(None)) || !matches!(execution_state, Ok(None)) {
                    continue;
                }
                // No terminal record + memory empty at boot => crash orphan.
                let client_id = self
                    .get_run_trace_for(&summary.agent_id, &summary.run_id)
                    .and_then(|records| {
                        records.into_iter().find_map(|record| match record {
                            RunRecord::Started(started) => started.client_id,
                            _ => None,
                        })
                    });
                let termination = RunTermination::Incomplete;
                let completion_digest = crate::session::run_completion_digest(&termination).ok();
                let incomplete = RunRecord::Ended(car_proto::RunEnded {
                    run_id: summary.run_id.clone(),
                    client_id,
                    agent_id: summary.agent_id.clone(),
                    termination,
                    completion_digest,
                    ended_at: now,
                });
                if self
                    .append_records(&summary.agent_id, &summary.run_id, &[incomplete])
                    .is_ok()
                {
                    adopted += 1;
                }
            }
        }
        adopted
    }

    /// GC one agent's run dir against the retention caps.
    fn gc_agent_dir(&self, agent_path: &Path, age_cutoff: DateTime<Utc>) -> usize {
        // Collect (path, summary) for every run file, ignoring unreadable
        // ones (a malformed file with no RunStarted can't be summarized;
        // leave it rather than risk evicting something we can't classify).
        let mut runs: Vec<(PathBuf, RunSummary)> = Vec::new();
        let Ok(entries) = std::fs::read_dir(agent_path) else {
            return 0;
        };
        for entry in entries {
            let Ok(entry) = entry else {
                return 0;
            };
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                continue;
            }
            let file_run_id = path
                .file_stem()
                .and_then(|value| value.to_str())
                .unwrap_or_default();
            let key = Self::run_summary_key(file_run_id);
            let existing = self.read_summary_sidecar(agent_path, &key).ok();
            let scan = summarize_file_checked(&path);
            let mut summary = match scan {
                Ok(scan) => match scan.summary {
                    Some(summary) => {
                        if let Some(corruption) = &scan.corruption {
                            self.remember_run_trace_corruption(
                                &summary.agent_id,
                                file_run_id,
                                corruption,
                            );
                        }
                        summary
                    }
                    None => {
                        let Some(mut existing) = existing.clone() else {
                            continue;
                        };
                        let corruption = scan
                            .corruption
                            .or_else(|| {
                                self.known_run_trace_corruption(&existing.agent_id, file_run_id)
                            })
                            .or_else(|| {
                                self.read_run_trace_corruption_marker(
                                    agent_path,
                                    &existing.agent_id,
                                    file_run_id,
                                )
                                .ok()
                                .flatten()
                            });
                        let Some(corruption) = corruption else {
                            continue;
                        };
                        self.remember_run_trace_corruption(
                            &existing.agent_id,
                            file_run_id,
                            &corruption,
                        );
                        existing.status = RunStatus::Incomplete;
                        existing.trace_corruption = Some(corruption);
                        existing
                    }
                },
                Err(error) => {
                    let Some(corruption) = trace_corruption_from_error(&error) else {
                        continue;
                    };
                    let Some(mut existing) = existing.clone() else {
                        continue;
                    };
                    self.remember_run_trace_corruption(
                        &existing.agent_id,
                        file_run_id,
                        &corruption,
                    );
                    existing.status = RunStatus::Incomplete;
                    existing.trace_corruption = Some(corruption);
                    existing
                }
            };
            if let Some(existing) = existing {
                summary.sequence = existing.sequence;
            }
            if self
                .apply_run_trace_corruption_marker(agent_path, &mut summary)
                .is_err()
            {
                continue;
            }
            runs.push((path, summary));
        }
        // Newest-first so the most recent completed runs rank first.
        runs.sort_by(|a, b| b.1.started_at.cmp(&a.1.started_at));

        let mut removed = 0;
        // Rank among COMPLETED/Incomplete runs only — an in-progress run
        // must not consume a keeper slot, so the count cap is measured by
        // completed-run rank, not the combined sorted index (R6).
        let mut completed_rank = 0usize;
        for (path, summary) in runs.iter() {
            // Corruption is durable audit evidence, not an ordinary incomplete
            // run. Never age/count-evict it until an operator repairs it.
            if summary.trace_corruption.is_some() {
                continue;
            }
            // NEVER evict an in-progress run — it has no terminal record
            // and a live harness may still be writing to it (R6).
            if matches!(
                summary.status,
                RunStatus::InProgress | RunStatus::CancellationPending
            ) {
                continue;
            }
            let over_count = completed_rank >= self.retention.max_per_agent;
            completed_rank += 1;
            // Age the run by its TERMINAL time, not its start. A long run
            // that started >max_age_days ago but completed recently is still
            // a recent result and must not be evicted (FIX 2). Completed and
            // Incomplete runs always have an `ended_at`; fall back to
            // `started_at` only if a terminal record somehow lacks one.
            let term_time = summary.ended_at.unwrap_or(summary.started_at);
            let too_old = term_time < age_cutoff;
            if (over_count || too_old) && std::fs::remove_file(path).is_ok() {
                removed += 1;
            }
        }
        let retained: Vec<RunSummary> = runs
            .into_iter()
            .filter_map(|(path, summary)| path.exists().then_some(summary))
            .collect();
        if let Err(error) = self.write_summary_index(agent_path, &retained) {
            tracing::error!(path = %agent_path.display(), %error, "run summary index startup repair failed");
        }
        removed
    }
}

fn same_run_ended(left: &car_proto::RunEnded, right: &car_proto::RunEnded) -> bool {
    serde_json::to_value(left).ok() == serde_json::to_value(right).ok()
}

/// Serialize and append a complete batch through one already-validated file
/// descriptor. Tail inspection and repair deliberately use the same
/// descriptor as the `O_APPEND` write: swapping the path after open cannot
/// redirect any bytes into a symlink target or replacement inode.
fn append_jsonl_batch_on_descriptor(file: &mut File, records: &[RunRecord]) -> std::io::Result<()> {
    car_secrets::revalidate_private_file(file)?;
    // FIX 6/7: build the WHOLE batch into one buffer and write it with a
    // single `write_all`. With `O_APPEND` a single write is positioned and
    // appended atomically relative to other appenders, so two concurrent
    // batches for the same file can't interleave mid-record. A leading '\n'
    // repairs a torn tail as part of the same atomic write.
    let mut buf = Vec::new();
    if last_byte_is_not_newline(file)? {
        buf.push(b'\n');
    }
    for rec in records {
        let line = serde_json::to_string(rec)
            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
        buf.extend_from_slice(line.as_bytes());
        buf.push(b'\n');
    }
    file.write_all(&buf)?;
    car_secrets::revalidate_private_file(file)
}

/// Bind the descriptor-safe append to the canonical path before and after the
/// write. The second check converts a concurrent rename/substitution into a
/// failed append receipt while guaranteeing the replacement path was never
/// opened for writing.
fn append_jsonl_batch_to_path(
    path: &Path,
    file: &mut File,
    records: &[RunRecord],
) -> std::io::Result<()> {
    car_secrets::revalidate_private_path(path, file)?;
    append_jsonl_batch_on_descriptor(file, records)?;
    car_secrets::revalidate_private_path(path, file)
}

/// Return `true` when the opened file's last byte is not `\n` — i.e. the
/// previous append was torn. An empty file returns `false`. The caller passes
/// the already-validated read+append descriptor so no path lookup occurs
/// between inspection and repair.
fn last_byte_is_not_newline(file: &mut File) -> std::io::Result<bool> {
    let len = file.seek(SeekFrom::End(0))?;
    if len == 0 {
        return Ok(false);
    }
    file.seek(SeekFrom::End(-1))?;
    let mut buf = [0u8; 1];
    file.read_exact(&mut buf)?;
    Ok(buf[0] != b'\n')
}

#[derive(Debug)]
enum RecordScanError {
    Io(std::io::Error),
    Malformed { line: usize, detail: String },
}

#[derive(Debug)]
struct StrictRunTraceCorruptionError {
    corruption: RunTraceCorruption,
    detail: String,
}

impl std::fmt::Display for StrictRunTraceCorruptionError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "malformed run trace record at line {}: {}",
            self.corruption.line, self.detail
        )
    }
}

impl std::error::Error for StrictRunTraceCorruptionError {}

fn scan_error_to_io(error: RecordScanError) -> std::io::Error {
    match error {
        RecordScanError::Io(error) => error,
        RecordScanError::Malformed { line, detail } => std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            StrictRunTraceCorruptionError {
                corruption: RunTraceCorruption {
                    kind: RunTraceCorruptionKind::MalformedRecord,
                    line,
                },
                detail,
            },
        ),
    }
}

/// Visit every committed JSONL row. A malformed newline-terminated row is
/// durable corruption and rejects the trace. A malformed final row without a
/// newline is an uncommitted crash tail and is ignored.
fn scan_records<F>(file: &File, mut visit: F) -> Result<(), RecordScanError>
where
    F: FnMut(RunRecord),
{
    let cloned = file.try_clone().map_err(RecordScanError::Io)?;
    let mut reader = std::io::BufReader::new(cloned);
    let mut bytes = Vec::new();
    let mut line = 0usize;
    loop {
        bytes.clear();
        let read = reader
            .read_until(b'\n', &mut bytes)
            .map_err(RecordScanError::Io)?;
        if read == 0 {
            break;
        }
        line = line.saturating_add(1);
        let terminated = bytes.last() == Some(&b'\n');
        if terminated {
            bytes.pop();
            if bytes.last() == Some(&b'\r') {
                bytes.pop();
            }
        }
        if bytes.iter().all(u8::is_ascii_whitespace) {
            continue;
        }
        match serde_json::from_slice::<RunRecord>(&bytes) {
            Ok(record) => visit(record),
            Err(_) if !terminated => break,
            Err(error) => {
                return Err(RecordScanError::Malformed {
                    line,
                    detail: error.to_string(),
                })
            }
        }
    }
    Ok(())
}

fn load_records(file: &File) -> std::io::Result<Vec<RunRecord>> {
    let mut records = Vec::new();
    scan_records(file, |record| records.push(record)).map_err(scan_error_to_io)?;
    Ok(records)
}

fn load_private_records(path: &Path, file: &File) -> std::io::Result<Vec<RunRecord>> {
    let records = load_records(file)?;
    car_secrets::revalidate_private_path(path, file)?;
    Ok(records)
}

/// Stream a trace and retain only its lifecycle boundary rows. This preserves
/// the JSONL reader's torn-line tolerance without allocating every recorded
/// turn during daemon startup.
fn load_private_run_boundaries(
    path: &Path,
    file: &File,
) -> Option<(
    car_proto::RunStarted,
    Option<car_proto::RunEnded>,
    Option<car_proto::RunCancellationRequested>,
    Option<car_proto::RunCancelResponse>,
)> {
    let mut started = None;
    let mut ended = None;
    let mut requested = None;
    let mut result = None;
    scan_records(file, |record| match record {
        RunRecord::Started(row) if started.is_none() => started = Some(row),
        RunRecord::Ended(row) if ended.is_none() => ended = Some(row),
        RunRecord::CancellationRequested(row) if requested.is_none() => requested = Some(row),
        RunRecord::CancellationResult(row) if result.is_none() => result = Some(row),
        _ => {}
    })
    .ok()?;
    car_secrets::revalidate_private_path(path, file).ok()?;
    started.map(|started| (started, ended, requested, result))
}

fn reject_corrupt_summary(summary: &RunSummary) -> std::io::Result<()> {
    if let Some(corruption) = &summary.trace_corruption {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("malformed run trace record at line {}", corruption.line),
        ));
    }
    Ok(())
}

#[derive(Debug)]
struct RunSummaryRefreshError {
    source: std::io::Error,
    corruption: RunTraceCorruption,
}

impl std::fmt::Display for RunSummaryRefreshError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "malformed run trace record at line {}; summary persistence also failed: {}",
            self.corruption.line, self.source
        )
    }
}

impl std::error::Error for RunSummaryRefreshError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.source)
    }
}

fn summary_refresh_error(source: std::io::Error, corruption: RunTraceCorruption) -> std::io::Error {
    std::io::Error::new(source.kind(), RunSummaryRefreshError { source, corruption })
}

fn preserve_summary_corruption<T>(
    result: std::io::Result<T>,
    corruption: &Option<RunTraceCorruption>,
) -> std::io::Result<T> {
    match corruption {
        Some(corruption) => {
            result.map_err(|source| summary_refresh_error(source, corruption.clone()))
        }
        None => result,
    }
}

pub(crate) fn trace_corruption_from_error(error: &std::io::Error) -> Option<RunTraceCorruption> {
    let source = error.get_ref()?;
    if let Some(failure) = source.downcast_ref::<RunSummaryRefreshError>() {
        return Some(failure.corruption.clone());
    }
    source
        .downcast_ref::<StrictRunTraceCorruptionError>()
        .map(|failure| failure.corruption.clone())
}

pub(crate) fn is_trace_corruption_error(error: &std::io::Error) -> bool {
    trace_corruption_from_error(error).is_some()
        || (error.kind() == std::io::ErrorKind::InvalidData
            && error.to_string().contains("malformed run trace record"))
}

fn summary_from_records(
    started: Option<car_proto::RunStarted>,
    ended: Option<car_proto::RunEnded>,
    turn_count: usize,
    cancellation_pending: bool,
    trace_corruption: Option<RunTraceCorruption>,
) -> Option<RunSummary> {
    let started = started?;
    let (status, ended_at) = if trace_corruption.is_some() {
        (RunStatus::Incomplete, None)
    } else {
        match &ended {
            Some(e) => {
                let status = match &e.termination {
                    RunTermination::Outcome { .. } => RunStatus::Completed,
                    RunTermination::Incomplete => RunStatus::Incomplete,
                    RunTermination::Cancelled { .. } => RunStatus::Cancelled,
                };
                (status, Some(e.ended_at))
            }
            None if cancellation_pending => (RunStatus::CancellationPending, None),
            None => (RunStatus::InProgress, None),
        }
    };
    Some(RunSummary {
        run_id: started.run_id,
        agent_id: started.agent_id,
        intent: started.intent,
        started_at: started.started_at,
        ended_at,
        status,
        turn_count,
        sequence: 0,
        trace_corruption,
    })
}

/// Build a [`RunSummary`] from a run's JSONL file: `RunStarted` from the
/// first valid record, terminal status from the last, and `turn_count`
/// from the `Turn`s in between. Returns `None` when the file has no
/// `RunStarted` (it can't be keyed/summarized).
struct RunSummaryScan {
    summary: Option<RunSummary>,
    corruption: Option<RunTraceCorruption>,
}

fn summarize_file_checked(path: &Path) -> std::io::Result<RunSummaryScan> {
    let file = car_secrets::open_private_read(path)?;
    let mut started: Option<car_proto::RunStarted> = None;
    let mut ended: Option<car_proto::RunEnded> = None;
    let mut turn_count = 0usize;
    let mut cancellation_pending = false;
    let scan = scan_records(&file, |record| match record {
        RunRecord::Started(s) => started = Some(s),
        RunRecord::Ended(e) => ended = Some(e),
        RunRecord::Turn(_) => turn_count += 1,
        RunRecord::CancellationRequested(_) | RunRecord::CancellationResult(_) => {
            cancellation_pending = true
        }
    });
    let trace_corruption = match scan {
        Ok(()) => None,
        Err(RecordScanError::Malformed { line, .. }) => Some(RunTraceCorruption {
            kind: RunTraceCorruptionKind::MalformedRecord,
            line,
        }),
        Err(RecordScanError::Io(error)) => return Err(error),
    };
    preserve_summary_corruption(
        car_secrets::revalidate_private_path(path, &file),
        &trace_corruption,
    )?;
    let summary = summary_from_records(
        started,
        ended,
        turn_count,
        cancellation_pending,
        trace_corruption.clone(),
    );
    Ok(RunSummaryScan {
        summary,
        corruption: trace_corruption,
    })
}

fn summarize_file(path: &Path) -> Option<RunSummary> {
    summarize_file_checked(path).ok()?.summary
}

/// Sanitize an id for use as a portable path segment — replace path
/// separators, Windows-reserved punctuation, and control characters, then
/// strip `..` so a hostile `agent_id`/`run_id` can't escape the `runs/` tree
/// or make an otherwise valid trace unpublishable on Windows. Ids are uuids /
/// slugs in practice; this is defense in depth.
fn sanitize(id: &str) -> String {
    let cleaned: String = id
        .chars()
        .map(|c| {
            if c.is_control() || matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') {
                '_'
            } else {
                c
            }
        })
        .collect();
    let trimmed = cleaned.trim_matches(['.', ' ']);
    if trimmed.is_empty() {
        "_".to_string()
    } else {
        trimmed.to_string()
    }
}

/// Mark a directory backup-excluded so Time Machine / iCloud don't copy
/// plaintext traces off the machine (R14). The portable `.nobackup` marker is
/// fail-closed CAR-owned state at `0600`; only the supplementary macOS xattr
/// remains best-effort.
fn ensure_backup_excluded(dir: &Path) -> std::io::Result<()> {
    let marker = dir.join(".nobackup");
    match car_secrets::create_private_file(&marker) {
        Ok(mut file) => {
            file.write_all(b"car run traces - excluded from backup\n")?;
            car_secrets::revalidate_private_file(&file)?;
            car_secrets::revalidate_private_path(&marker, &file)?;
        }
        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
            let file = car_secrets::open_private_read(&marker)?;
            car_secrets::revalidate_private_path(&marker, &file)?;
        }
        Err(error) => return Err(error),
    }
    #[cfg(target_os = "macos")]
    set_macos_backup_excluded(dir);
    car_secrets::ensure_private_dir(dir)?;
    Ok(())
}

/// Set the macOS Time Machine exclusion xattr on `dir`. Uses the `xattr`
/// CLI (always present on macOS) rather than linking a native crate. Time
/// Machine treats any non-empty value on this attr as "exclude". Best-
/// effort — a missing `xattr` or a failure is ignored.
#[cfg(target_os = "macos")]
fn set_macos_backup_excluded(dir: &Path) {
    // `xattr -w` writes a string value; Time Machine only checks for the
    // attr's presence/non-emptiness, not its exact bytes.
    let _ = std::process::Command::new("xattr")
        .args(["-w", "com.apple.metadata:com_apple_backup_excludeItem", "1"])
        .arg(dir)
        .output();
}

#[cfg(test)]
mod tests {
    use super::*;
    use car_ir::{AgentOutcome, CostSummary, OutcomeMetrics, OutcomeStatus, ProposalLineageEntry};
    use car_proto::{RunEnded, RunStarted, RunTurn, VerifierVerdict};
    use serde_json::json;

    #[test]
    fn run_path_segments_replace_windows_reserved_characters() {
        assert_eq!(sanitize("name:bulldozer-agent"), "name_bulldozer-agent");
        assert_eq!(sanitize("<>:\"/\\|?*\0"), "__________");
        assert_eq!(sanitize(".. "), "_");
    }

    fn store(root: PathBuf) -> RunStore {
        RunStore::new(root, RetentionConfig::default())
    }

    fn started(run_id: &str, agent_id: &str, when: DateTime<Utc>) -> RunStarted {
        RunStarted {
            run_id: run_id.to_string(),
            client_id: Some("test-client".to_string()),
            agent_id: agent_id.to_string(),
            intent: "do the thing".to_string(),
            outcome_description: None,
            started_at: when,
        }
    }

    fn turn(index: usize, prompt: &str) -> RunRecord {
        RunRecord::Turn(RunTurn {
            index,
            proposal_id: None,
            action_id: None,
            action_status: None,
            action_duration_ms: None,
            action_completed_at: None,
            depends_on: None,
            state_dependencies: None,
            prompt: Some(prompt.to_string()),
            tool: Some("drive_cli".to_string()),
            parameters: json!({ "prompt": prompt }),
            output: Some(json!({ "exit_code": 0 })),
            cli_outcome: None,
            verifier_verdict: VerifierVerdict::NotRun,
            policy_rejected: None,
        })
    }

    fn ended(run_id: &str, agent_id: &str, status: OutcomeStatus) -> RunRecord {
        let outcome = AgentOutcome {
            status,
            summary: "done".to_string(),
            evidence: vec![],
            metrics: OutcomeMetrics::default(),
            timestamp: Utc::now(),
        };
        let termination = RunTermination::Outcome { status, outcome };
        let completion_digest = crate::session::run_completion_digest(&termination).unwrap();
        RunRecord::Ended(RunEnded {
            run_id: run_id.to_string(),
            client_id: Some("test-client".to_string()),
            agent_id: agent_id.to_string(),
            termination,
            completion_digest: Some(completion_digest),
            ended_at: Utc::now(),
        })
    }

    fn valid_pending(run_id: &str) -> PendingProposalFinalization {
        let proposal = ActionProposal {
            id: format!("proposal-{run_id}"),
            source: "run-store-test".to_string(),
            actions: Vec::new(),
            timestamp: Utc::now(),
            context: HashMap::new(),
        };
        let digest = proposal_digest(&proposal).unwrap();
        let proposal_result = ProposalResult {
            proposal_id: proposal.id.clone(),
            original_proposal_id: proposal.id.clone(),
            final_proposal: Some(proposal.clone()),
            replan_lineage: vec![ProposalLineageEntry {
                generation: 0,
                proposal_id: proposal.id.clone(),
                proposal_digest: Some(digest.clone()),
                status: ProposalLineageStatus::Accepted,
                rejection_reason: None,
            }],
            accepted_proposal_preimages: vec![car_ir::AcceptedProposalPreimage {
                generation: 0,
                proposal_digest: digest,
                proposal: proposal.clone(),
            }],
            results: Vec::new(),
            cost: CostSummary::default(),
        };
        let result_value = serde_json::to_value(&proposal_result).unwrap();
        let canonical = car_inference::catalog_identity::canonical_json(&result_value).unwrap();
        PendingProposalFinalization {
            run_id: run_id.to_string(),
            client_id: "test-client".to_string(),
            requested_policy_session_id: None,
            policy_session_id: None,
            original_proposal_id: proposal.id.clone(),
            final_proposal_id: proposal.id.clone(),
            original_submission: json!({
                "id": proposal.id.clone(),
                "source": "run-store-test",
                "actions": []
            }),
            original_proposal: proposal.clone(),
            final_proposal: proposal.clone(),
            accepted_proposal_preimages: vec![AcceptedProposalPreimage {
                generation: 0,
                proposal,
            }],
            proposal_result,
            result_digest: format!("{:x}", Sha256::digest(canonical.as_bytes())),
        }
    }

    fn refresh_pending_result_digest(pending: &mut PendingProposalFinalization) {
        let value = serde_json::to_value(&pending.proposal_result).unwrap();
        let canonical = car_inference::catalog_identity::canonical_json(&value).unwrap();
        pending.result_digest = format!("{:x}", Sha256::digest(canonical.as_bytes()));
    }

    fn marker_for_pending(pending: &PendingProposalFinalization) -> ProposalExecutionMarker {
        ProposalExecutionMarker {
            run_id: pending.run_id.clone(),
            client_id: pending.client_id.clone(),
            requested_policy_session_id: pending.requested_policy_session_id.clone(),
            policy_session_id: pending.policy_session_id.clone(),
            original_proposal_id: pending.original_proposal_id.clone(),
            original_submission: pending.original_submission.clone(),
            original_proposal: serde_json::to_value(&pending.original_proposal).unwrap(),
            proposal_digest: proposal_digest(&pending.original_proposal).unwrap(),
        }
    }

    fn rebind_pending_original(pending: &mut PendingProposalFinalization) {
        pending.original_submission["source"] = json!("pending-self-claim");
        pending.original_proposal.source = "pending-self-claim".to_string();
        pending.final_proposal = pending.original_proposal.clone();
        pending.accepted_proposal_preimages[0].proposal = pending.original_proposal.clone();
        pending.proposal_result.final_proposal = Some(pending.original_proposal.clone());
        pending.proposal_result.replan_lineage[0].proposal_digest =
            Some(proposal_digest(&pending.original_proposal).unwrap());
        refresh_pending_result_digest(pending);
    }

    fn write_pending_provenance(store: &RunStore, pending: &PendingProposalFinalization) {
        store
            .write_started(&started(&pending.run_id, "agent-a", Utc::now()))
            .unwrap();
        store
            .write_execution_marker(&marker_for_pending(pending))
            .unwrap();
    }

    fn write_completed_receipt_fixture(
        store: &RunStore,
        pending: PendingProposalFinalization,
        exact_bytes: Option<usize>,
        invalid_tail: bool,
    ) -> CompletedProposalResponse {
        let receipt = CompletedProposalResponse {
            finalization: pending,
        };
        receipt.validate().unwrap();
        let pending = &receipt.finalization;
        let run_root = store.completed_response_run_root(&pending.run_id);
        store.ensure_private_dir(&run_root).unwrap();
        let path = store
            .completed_response_path(
                &pending.run_id,
                &pending.client_id,
                pending.requested_policy_session_id.as_deref(),
                &pending.original_submission,
            )
            .unwrap();
        let mut bytes = serde_json::to_vec(&receipt).unwrap();
        if let Some(exact_bytes) = exact_bytes {
            assert!(bytes.len() <= exact_bytes);
            bytes.resize(exact_bytes, b' ');
        }
        if invalid_tail {
            bytes.push(b'!');
        }
        let mut file = store.create_private_file(&path).unwrap();
        file.write_all(&bytes).unwrap();
        file.sync_all().unwrap();
        receipt
    }

    #[test]
    fn first_use_agent_receipt_parent_sync_failure_is_not_acknowledged_and_retry_is_exact() {
        let tmp = tempfile::TempDir::new().unwrap();
        let failures = car_secrets::PrivatePathDurabilityFailureInjector::default();
        let store =
            store(tmp.path().join("runs")).with_private_path_failure_injector(failures.clone());
        store.prepare_storage().unwrap();
        failures.fail_next(car_secrets::PrivatePathDurabilityFailurePoint::ParentDirectorySync);
        let boundary = started("private-first-use", "new-agent", Utc::now());

        let error = store.write_started(&boundary).unwrap_err();
        assert!(error
            .to_string()
            .contains("injected private-path parent directory sync failure"));
        assert!(
            store.get_run_trace(&boundary.run_id).is_none(),
            "an unacknowledged agent-directory entry must not contain a run boundary"
        );

        store.write_started(&boundary).unwrap();
        let trace = store.get_run_trace(&boundary.run_id).unwrap();
        assert_eq!(
            trace
                .iter()
                .filter(|row| matches!(row, RunRecord::Started(_)))
                .count(),
            1,
            "retry must persist exactly one RunStarted boundary"
        );
    }

    #[test]
    fn proposal_sidecar_parent_sync_failures_are_not_acknowledged_and_retry_exactly() {
        let tmp = tempfile::TempDir::new().unwrap();
        let failures = car_secrets::PrivatePathDurabilityFailureInjector::default();
        let store =
            store(tmp.path().join("runs")).with_private_path_failure_injector(failures.clone());
        let pending = valid_pending("private-sidecar-first-use");
        store
            .write_started(&started(&pending.run_id, "agent-a", Utc::now()))
            .unwrap();
        let marker = marker_for_pending(&pending);

        failures.fail_next(car_secrets::PrivatePathDurabilityFailurePoint::ParentDirectorySync);
        assert!(store.write_execution_marker(&marker).is_err());
        assert_eq!(store.execution_marker(&pending.run_id).unwrap(), None);
        store.write_execution_marker(&marker).unwrap();
        assert_eq!(
            store.execution_marker(&pending.run_id).unwrap(),
            Some(marker)
        );

        failures.fail_next(car_secrets::PrivatePathDurabilityFailurePoint::ParentDirectorySync);
        assert!(store.write_pending_proposal(&pending).is_err());
        assert_eq!(store.pending_proposal(&pending.run_id).unwrap(), None);
        store.write_pending_proposal(&pending).unwrap();
        assert_eq!(
            store.pending_proposal(&pending.run_id).unwrap(),
            Some(pending)
        );
    }

    /// A completed run is readable from a brand-new store instance — the
    /// "simulated daemon restart" (new store, empty memory): the trace
    /// must come back from disk (R4).
    #[test]
    fn completed_run_readable_after_restart() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s1 = store(root.clone());
        s1.write_started(&started("run-1", "agent-a", Utc::now()))
            .unwrap();
        s1.append_turns("agent-a", "run-1", &[turn(0, "first")])
            .unwrap();
        s1.append_records(
            "agent-a",
            "run-1",
            &[ended("run-1", "agent-a", OutcomeStatus::Success)],
        )
        .unwrap();

        // Brand-new store over the same root = simulated restart with empty memory.
        let s2 = store(root);
        let trace = s2
            .get_run_trace("run-1")
            .expect("trace readable after restart");
        assert!(matches!(trace.first(), Some(RunRecord::Started(_))));
        assert!(matches!(trace.last(), Some(RunRecord::Ended(_))));
        let turns = trace
            .iter()
            .filter(|r| matches!(r, RunRecord::Turn(_)))
            .count();
        assert_eq!(turns, 1);
    }

    /// Each run persists to its own `(agent_id, run_id)` file — no
    /// cross-contamination between runs or agents (R1).
    #[test]
    fn runs_isolated_per_agent_and_run() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = store(tmp.path().join("runs"));
        s.write_started(&started("run-1", "agent-a", Utc::now()))
            .unwrap();
        s.append_turns("agent-a", "run-1", &[turn(0, "a-first")])
            .unwrap();
        s.write_started(&started("run-2", "agent-a", Utc::now()))
            .unwrap();
        s.append_turns("agent-a", "run-2", &[turn(0, "a-second")])
            .unwrap();
        s.write_started(&started("run-3", "agent-b", Utc::now()))
            .unwrap();
        s.append_turns("agent-b", "run-3", &[turn(0, "b-first")])
            .unwrap();

        // Distinct files; each holds only its own turn.
        let t1 = s.get_run_trace("run-1").unwrap();
        let t2 = s.get_run_trace("run-2").unwrap();
        let t3 = s.get_run_trace("run-3").unwrap();
        assert_eq!(turn_prompt(&t1), "a-first");
        assert_eq!(turn_prompt(&t2), "a-second");
        assert_eq!(turn_prompt(&t3), "b-first");
        // run_id -> agent_id resolution works for replay authz.
        assert_eq!(s.agent_for_run("run-1").as_deref(), Some("agent-a"));
        assert_eq!(s.agent_for_run("run-3").as_deref(), Some("agent-b"));
        // agent-a lists 2 runs, agent-b lists 1.
        assert_eq!(s.list_runs("agent-a").len(), 2);
        assert_eq!(s.list_runs("agent-b").len(), 1);
    }

    #[test]
    fn summary_index_pages_in_stable_newest_first_order() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = store(tmp.path().join("runs"));
        let now = Utc::now();
        s.write_started(&started(
            "run-old",
            "agent-page",
            now - chrono::Duration::seconds(2),
        ))
        .unwrap();
        s.append_turns("agent-page", "run-old", &[turn(0, "old")])
            .unwrap();
        s.write_started(&started("run-new", "agent-page", now))
            .unwrap();
        s.append_turns(
            "agent-page",
            "run-new",
            &[turn(0, "new-0"), turn(1, "new-1")],
        )
        .unwrap();

        let (first, next) = s.list_runs_page("agent-page", 0, 1).unwrap();
        assert_eq!(first.len(), 1);
        assert_eq!(first[0].run_id, "run-new");
        assert_eq!(first[0].turn_count, 2);
        let next = next.expect("older run remains");

        // A new run arriving at the head must not shift an offset cursor and
        // cause the previous first row to be returned twice.
        s.write_started(&started(
            "run-newest",
            "agent-page",
            now + chrono::Duration::seconds(1),
        ))
        .unwrap();

        let (second, next) = s.list_runs_page("agent-page", next, 1).unwrap();
        assert_eq!(second.len(), 1);
        assert_eq!(second[0].run_id, "run-old");
        assert_eq!(second[0].turn_count, 1);
        assert_eq!(next, None);

        let (past_end, next) = s.list_runs_page("agent-page", 1, 1).unwrap();
        assert!(past_end.is_empty());
        assert_eq!(next, None);
    }

    #[test]
    fn newline_terminated_malformed_record_quarantines_completed_trace() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s = store(root.clone());
        s.write_started(&started("corrupt", "agent-a", Utc::now()))
            .unwrap();
        s.append_turns("agent-a", "corrupt", &[turn(0, "before")])
            .unwrap();

        let path = root.join("agent-a").join("corrupt.jsonl");
        let mut file = car_secrets::open_private_append(&path).unwrap();
        file.write_all(b"{malformed-middle}\n").unwrap();
        file.flush().unwrap();
        file.sync_all().unwrap();
        drop(file);

        let RunRecord::Ended(terminal) = ended("corrupt", "agent-a", OutcomeStatus::Success) else {
            unreachable!()
        };
        let error = s
            .write_ended(&terminal)
            .expect_err("a durable malformed row must prevent completion");
        assert!(error.to_string().contains("line 3"), "{error}");

        let (summaries, _) = s.list_runs_page("agent-a", 0, 1).unwrap();
        assert_eq!(summaries[0].status, RunStatus::Incomplete);
        assert_eq!(
            serde_json::to_value(&summaries[0]).unwrap()["trace_corruption"],
            json!({"kind":"malformed_record","line":3})
        );
        assert!(s
            .get_run_turn_page_for("agent-a", "corrupt", 0, 10)
            .unwrap_err()
            .to_string()
            .contains("line 3"));
    }

    fn turn_prompt(trace: &[RunRecord]) -> String {
        trace
            .iter()
            .find_map(|r| match r {
                RunRecord::Turn(t) => t.prompt.clone(),
                _ => None,
            })
            .unwrap_or_default()
    }

    /// Files are `0600` and dirs are `0700` (R14 — assert the modes).
    #[cfg(unix)]
    #[test]
    fn perms_are_0600_files_0700_dirs() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s = store(root.clone());
        s.write_started(&started("run-1", "agent-a", Utc::now()))
            .unwrap();

        let file = root.join("agent-a").join("run-1.jsonl");
        let fmode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
        assert_eq!(fmode, 0o600, "run file must be 0600, got {:o}", fmode);

        let root_mode = std::fs::metadata(&root).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            root_mode, 0o700,
            "runs/ dir must be 0700, got {:o}",
            root_mode
        );
        let agent_mode = std::fs::metadata(root.join("agent-a"))
            .unwrap()
            .permissions()
            .mode()
            & 0o777;
        assert_eq!(
            agent_mode, 0o700,
            "agent dir must be 0700, got {:o}",
            agent_mode
        );

        // The backup-exclusion marker is present.
        let marker = root.join(".nobackup");
        assert!(marker.exists(), ".nobackup marker written");
        let marker_mode = std::fs::metadata(marker).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            marker_mode, 0o600,
            ".nobackup marker must be 0600, got {:o}",
            marker_mode
        );
    }

    #[cfg(unix)]
    #[test]
    fn replay_hardens_owned_legacy_tree_without_changing_content() {
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let agent = root.join("agent-a");
        std::fs::create_dir_all(&agent).unwrap();
        let path = agent.join("run-1.jsonl");
        let line =
            serde_json::to_string(&RunRecord::Started(started("run-1", "agent-a", Utc::now())))
                .unwrap();
        let original = format!("{line}\n");
        std::fs::write(&path, original.as_bytes()).unwrap();
        std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::set_permissions(&agent, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();

        let trace = store(root.clone())
            .get_run_trace_for("agent-a", "run-1")
            .expect("legacy run remains replayable");
        assert_eq!(trace.len(), 1);
        assert_eq!(std::fs::read_to_string(&path).unwrap(), original);
        assert_eq!(
            std::fs::metadata(root).unwrap().permissions().mode() & 0o777,
            0o700
        );
        assert_eq!(
            std::fs::metadata(agent).unwrap().permissions().mode() & 0o777,
            0o700
        );
        assert_eq!(
            std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
            0o600
        );
    }

    #[cfg(unix)]
    #[test]
    fn run_file_symlinks_and_hardlinks_are_rejected_without_touching_victim() {
        use std::os::unix::fs::symlink;

        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let agent = root.join("agent-a");
        std::fs::create_dir_all(&agent).unwrap();
        let victim = tmp.path().join("victim.jsonl");
        std::fs::write(&victim, b"victim\n").unwrap();

        let symlink_path = agent.join("symlink.jsonl");
        symlink(&victim, &symlink_path).unwrap();
        let s = store(root.clone());
        assert!(s.get_run_trace_for("agent-a", "symlink").is_none());
        assert!(s
            .append_records(
                "agent-a",
                "symlink",
                &[RunRecord::Started(started(
                    "symlink",
                    "agent-a",
                    Utc::now()
                ))],
            )
            .is_err());
        assert_eq!(std::fs::read(&victim).unwrap(), b"victim\n");

        std::fs::remove_file(&symlink_path).unwrap();
        let hardlink_path = agent.join("hardlink.jsonl");
        std::fs::hard_link(&victim, &hardlink_path).unwrap();
        assert!(s.get_run_trace_for("agent-a", "hardlink").is_none());
        assert!(s
            .append_records(
                "agent-a",
                "hardlink",
                &[RunRecord::Started(started(
                    "hardlink",
                    "agent-a",
                    Utc::now()
                ))],
            )
            .is_err());
        assert_eq!(std::fs::read(&victim).unwrap(), b"victim\n");
    }

    #[cfg(unix)]
    #[test]
    fn symlink_agent_directory_and_special_run_file_are_rejected() {
        use std::os::unix::fs::symlink;
        use std::os::unix::net::UnixListener;

        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        std::fs::create_dir(&root).unwrap();
        let victim_dir = tmp.path().join("victim-agent");
        std::fs::create_dir(&victim_dir).unwrap();
        symlink(&victim_dir, root.join("agent-link")).unwrap();

        let s = store(root.clone());
        assert!(s.list_runs("agent-link").is_empty());
        assert!(s
            .append_records(
                "agent-link",
                "run-1",
                &[RunRecord::Started(started(
                    "run-1",
                    "agent-link",
                    Utc::now()
                ))],
            )
            .is_err());
        assert!(std::fs::read_dir(&victim_dir).unwrap().next().is_none());

        let agent = root.join("agent-a");
        std::fs::create_dir(&agent).unwrap();
        let socket_path = agent.join("socket.jsonl");
        let _listener = UnixListener::bind(&socket_path).unwrap();
        assert!(s.get_run_trace_for("agent-a", "socket").is_none());
        assert!(s
            .append_records(
                "agent-a",
                "socket",
                &[RunRecord::Started(started("socket", "agent-a", Utc::now()))],
            )
            .is_err());
    }

    #[cfg(unix)]
    #[test]
    fn append_uses_the_validated_descriptor_after_path_substitution() {
        use std::os::unix::fs::symlink;

        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("run.jsonl");
        std::fs::write(&path, b"torn").unwrap();
        let mut file = car_secrets::open_private_append(&path).unwrap();
        let victim = tmp.path().join("victim");
        std::fs::write(&victim, b"victim\n").unwrap();

        std::fs::remove_file(&path).unwrap();
        symlink(&victim, &path).unwrap();
        assert!(append_jsonl_batch_to_path(&path, &mut file, &[turn(0, "safe")]).is_err());

        assert_eq!(std::fs::read(&victim).unwrap(), b"victim\n");
    }

    #[cfg(unix)]
    #[test]
    fn replay_rejects_path_substitution_after_open() {
        use std::os::unix::fs::symlink;

        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("run.jsonl");
        let line =
            serde_json::to_string(&RunRecord::Started(started("run-1", "agent-a", Utc::now())))
                .unwrap();
        std::fs::write(&path, format!("{line}\n")).unwrap();
        let file = car_secrets::open_private_read(&path).unwrap();
        let victim = tmp.path().join("victim");
        std::fs::write(&victim, b"victim\n").unwrap();

        std::fs::rename(&path, tmp.path().join("moved.jsonl")).unwrap();
        symlink(&victim, &path).unwrap();

        assert!(load_private_records(&path, &file).is_err());
        assert_eq!(std::fs::read(&victim).unwrap(), b"victim\n");
    }

    /// A run with no `RunEnded` reads `InProgress`; once the disconnect
    /// path writes the `Incomplete` terminal it reads `Incomplete` — never
    /// silently `Completed`. This is the R5 distinguishability the
    /// dashboard renders.
    #[test]
    fn orphan_run_status_distinguishes_inprogress_from_incomplete() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = store(tmp.path().join("runs"));
        // Stale start time (no harness writing — an orphan).
        let stale = Utc::now() - chrono::Duration::hours(6);
        s.write_started(&started("run-1", "agent-a", stale))
            .unwrap();
        s.append_turns("agent-a", "run-1", &[turn(0, "first")])
            .unwrap();

        // Still open: no terminal record yet.
        let open = &s.list_runs("agent-a")[0];
        assert_eq!(open.status, RunStatus::InProgress);

        // Disconnect path writes the Incomplete terminal.
        let incomplete = RunRecord::Ended(RunEnded {
            run_id: "run-1".to_string(),
            client_id: Some("test-client".to_string()),
            agent_id: "agent-a".to_string(),
            termination: RunTermination::Incomplete,
            completion_digest: Some("test-digest".to_string()),
            ended_at: Utc::now(),
        });
        s.append_records("agent-a", "run-1", &[incomplete]).unwrap();
        let closed = &s.list_runs("agent-a")[0];
        assert_eq!(closed.status, RunStatus::Incomplete);
    }

    /// Retention evicts beyond the per-agent cap, never an in-progress
    /// run (R6).
    #[test]
    fn gc_evicts_beyond_per_agent_cap_but_never_in_progress() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s = RunStore::new(
            root,
            RetentionConfig {
                max_per_agent: 3,
                max_age_days: 30,
            },
        );
        // 5 completed runs with increasing start times.
        let base = Utc::now() - chrono::Duration::days(1);
        for i in 0..5 {
            let id = format!("c{i}");
            let when = base + chrono::Duration::minutes(i);
            s.write_started(&started(&id, "agent-a", when)).unwrap();
            s.append_records(
                "agent-a",
                &id,
                &[ended(&id, "agent-a", OutcomeStatus::Success)],
            )
            .unwrap();
        }
        // 1 in-progress run (no terminal) — must survive GC.
        s.write_started(&started("live", "agent-a", Utc::now()))
            .unwrap();

        let removed = s.gc();
        // Keep 3 most-recent completed; evict the 2 oldest completed. The
        // in-progress run is never counted/evicted.
        assert_eq!(removed, 2, "should evict the 2 oldest completed runs");
        let remaining = s.list_runs("agent-a");
        // 3 kept completed + the live one = 4.
        assert_eq!(remaining.len(), 4);
        assert!(
            remaining.iter().any(|r| r.run_id == "live"),
            "in-progress run must never be evicted"
        );
        // The two oldest (c0, c1) are gone.
        assert!(!remaining.iter().any(|r| r.run_id == "c0"));
        assert!(!remaining.iter().any(|r| r.run_id == "c1"));
    }

    /// Retention evicts completed runs older than the age cap (R6).
    #[test]
    fn gc_evicts_runs_older_than_age_cap() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = RunStore::new(
            tmp.path().join("runs"),
            RetentionConfig {
                max_per_agent: 50,
                max_age_days: 30,
            },
        );
        // One old completed run — started AND ended 40 days ago (its
        // terminal time is what the age cap measures, FIX 2) — and one
        // fresh run.
        let old = Utc::now() - chrono::Duration::days(40);
        s.write_started(&started("old", "agent-a", old)).unwrap();
        s.append_records(
            "agent-a",
            "old",
            &[ended_at("old", "agent-a", OutcomeStatus::Success, old)],
        )
        .unwrap();
        s.write_started(&started("fresh", "agent-a", Utc::now()))
            .unwrap();
        s.append_records(
            "agent-a",
            "fresh",
            &[ended("fresh", "agent-a", OutcomeStatus::Success)],
        )
        .unwrap();

        let removed = s.gc();
        assert_eq!(removed, 1, "the 40-day-old run should be evicted");
        let remaining = s.list_runs("agent-a");
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].run_id, "fresh");
    }

    /// An old run that is still in progress is NOT evicted by the age cap
    /// (R6 — never evict an open run, even a stale one).
    #[test]
    fn gc_never_evicts_stale_in_progress_run() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = RunStore::new(
            tmp.path().join("runs"),
            RetentionConfig {
                max_per_agent: 1,
                max_age_days: 1,
            },
        );
        let old = Utc::now() - chrono::Duration::days(40);
        // Old + in-progress (no terminal).
        s.write_started(&started("stale-live", "agent-a", old))
            .unwrap();
        let removed = s.gc();
        assert_eq!(removed, 0);
        assert!(s
            .list_runs("agent-a")
            .iter()
            .any(|r| r.run_id == "stale-live"));
    }

    /// A corrupt/partial trailing JSONL line loads the prior valid
    /// records rather than failing the whole run (error path).
    #[test]
    fn corrupt_trailing_line_loads_prior_records() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s = store(root.clone());
        s.write_started(&started("run-1", "agent-a", Utc::now()))
            .unwrap();
        s.append_turns("agent-a", "run-1", &[turn(0, "first"), turn(1, "second")])
            .unwrap();

        // Append a partial/garbage line directly (simulating a crash
        // mid-append).
        let path = root.join("agent-a").join("run-1.jsonl");
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap();
        f.write_all(b"{\"record\":\"turn\",\"index\":2,\"prom")
            .unwrap();

        let trace = s.get_run_trace("run-1").expect("trace still loads");
        // RunStarted + 2 valid turns; the garbage trailing line is dropped.
        let turns = trace
            .iter()
            .filter(|r| matches!(r, RunRecord::Turn(_)))
            .count();
        assert_eq!(turns, 2, "prior valid turns load; corrupt line skipped");
        assert!(matches!(trace.first(), Some(RunRecord::Started(_))));
    }

    /// `list_runs` for an agent with no runs returns empty (empty-state).
    #[test]
    fn list_runs_empty_for_unknown_agent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = store(tmp.path().join("runs"));
        assert!(s.list_runs("nobody").is_empty());
        assert!(s.get_run_trace("nope").is_none());
        assert!(s.agent_for_run("nope").is_none());
    }

    /// `from_journal_dir` roots the store at `<car_dir>/runs` as a sibling
    /// of the journal dir.
    #[test]
    fn from_journal_dir_roots_at_car_runs() {
        let s = RunStore::from_journal_dir(Path::new("/home/u/.car/journals"));
        assert_eq!(s.root(), Path::new("/home/u/.car/runs"));
    }

    /// Retention config loads `[runs]` overrides from config.toml; missing
    /// keys keep the restrictive default.
    #[test]
    fn retention_config_reads_overrides() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("config.toml"),
            "[runs]\nmax_per_agent = 10\n",
        )
        .unwrap();
        let cfg = RetentionConfig::from_car_dir(tmp.path());
        assert_eq!(cfg.max_per_agent, 10);
        // Missing key keeps the default.
        assert_eq!(cfg.max_age_days, DEFAULT_MAX_AGE_DAYS);
    }

    /// A missing/malformed config.toml falls back to the restrictive
    /// default — never refuses.
    #[test]
    fn retention_config_defaults_on_missing_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        let cfg = RetentionConfig::from_car_dir(tmp.path());
        assert_eq!(cfg.max_per_agent, DEFAULT_MAX_RUNS_PER_AGENT);
        assert_eq!(cfg.max_age_days, DEFAULT_MAX_AGE_DAYS);
    }

    /// Append the terminal `RunEnded` with an explicit `ended_at` (the
    /// disconnect/complete path uses `Utc::now()`, but GC ages by terminal
    /// time, so tests need to control it).
    fn ended_at(
        run_id: &str,
        agent_id: &str,
        status: OutcomeStatus,
        when: DateTime<Utc>,
    ) -> RunRecord {
        let outcome = AgentOutcome {
            status,
            summary: "done".to_string(),
            evidence: vec![],
            metrics: OutcomeMetrics::default(),
            timestamp: when,
        };
        RunRecord::Ended(RunEnded {
            run_id: run_id.to_string(),
            client_id: Some("test-client".to_string()),
            agent_id: agent_id.to_string(),
            termination: RunTermination::Outcome { status, outcome },
            completion_digest: Some("test-digest".to_string()),
            ended_at: when,
        })
    }

    /// FIX 2: a run that STARTED >max_age_days ago but COMPLETED recently is
    /// a fresh result and must NOT be evicted by the age cap. GC must age by
    /// the terminal time, not the start time.
    #[test]
    fn gc_age_cap_uses_terminal_time_not_start() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = RunStore::new(
            tmp.path().join("runs"),
            RetentionConfig {
                max_per_agent: 50,
                max_age_days: 30,
            },
        );
        // Long-running run: started 40 days ago, completed 1 day ago.
        let started_40d = Utc::now() - chrono::Duration::days(40);
        let ended_1d = Utc::now() - chrono::Duration::days(1);
        s.write_started(&started("long", "agent-a", started_40d))
            .unwrap();
        s.append_records(
            "agent-a",
            "long",
            &[ended_at(
                "long",
                "agent-a",
                OutcomeStatus::Success,
                ended_1d,
            )],
        )
        .unwrap();

        let removed = s.gc();
        assert_eq!(
            removed, 0,
            "a run completed 1 day ago must survive the 30-day age cap, \
             even if it started 40 days ago"
        );
        let remaining = s.list_runs("agent-a");
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].run_id, "long");
    }

    /// FIX 4: a crash-orphaned run (RunStarted + Turn, no RunEnded) on disk
    /// reads `InProgress`. A fresh store's `adopt_orphans()` at boot — when
    /// the in-memory map is empty — appends an `Incomplete` terminal so the
    /// run becomes terminal (and thus age-GC-eligible), no longer leaking.
    #[test]
    fn adopt_orphans_marks_crashed_inprogress_runs_incomplete() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        // Prior process wrote a start + a turn, then crashed (no terminal).
        let s1 = store(root.clone());
        s1.write_started(&started("orphan", "agent-a", Utc::now()))
            .unwrap();
        s1.append_turns("agent-a", "orphan", &[turn(0, "first")])
            .unwrap();
        assert_eq!(
            s1.list_runs("agent-a")[0].status,
            RunStatus::InProgress,
            "precondition: orphan reads InProgress before adoption"
        );

        // Fresh store = new process boot, empty in-memory map.
        let s2 = store(root);
        let adopted = s2.adopt_orphans();
        assert_eq!(adopted, 1, "the crash orphan should be adopted");

        let after = &s2.list_runs("agent-a")[0];
        assert_eq!(
            after.status,
            RunStatus::Incomplete,
            "adopted orphan now reads Incomplete (terminal)"
        );
        assert!(after.ended_at.is_some(), "terminal record has an ended_at");

        // Idempotent: a second boot finds no orphans (already terminal).
        assert_eq!(s2.adopt_orphans(), 0);
    }

    fn write_truncated_private_file(path: &Path) {
        let parent = path.parent().unwrap();
        car_secrets::ensure_private_dir(parent).unwrap();
        let mut file = car_secrets::create_private_file(path).unwrap();
        file.write_all(b"{").unwrap();
        file.sync_all().unwrap();
    }

    #[test]
    fn corrupt_execution_marker_quarantines_orphan_adoption() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s = store(root);
        s.write_started(&started("marker-corrupt", "agent-a", Utc::now()))
            .unwrap();
        write_truncated_private_file(&s.proposal_execution_path("marker-corrupt"));

        assert!(s.execution_marker("absent-marker").unwrap().is_none());
        assert!(s.execution_marker("marker-corrupt").is_err());

        assert_eq!(
            s.adopt_orphans(),
            0,
            "present-but-invalid marker is outcome-unknown, never an adoptable absence"
        );
        assert_eq!(s.list_runs("agent-a")[0].status, RunStatus::InProgress);
    }

    #[test]
    fn corrupt_finalization_outbox_quarantines_orphan_adoption() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s = store(root);
        s.write_started(&started("outbox-corrupt", "agent-a", Utc::now()))
            .unwrap();
        write_truncated_private_file(&s.proposal_outbox_path("outbox-corrupt"));

        assert!(s.pending_proposal("absent-outbox").unwrap().is_none());
        assert!(s.pending_proposal("outbox-corrupt").is_err());

        assert_eq!(
            s.adopt_orphans(),
            0,
            "present-but-invalid outbox is outcome-unknown, never an adoptable absence"
        );
        assert_eq!(s.list_runs("agent-a")[0].status, RunStatus::InProgress);
    }

    #[test]
    fn proposal_sidecars_reject_wrong_run_identity() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = store(tmp.path().join("runs"));
        let marker = ProposalExecutionMarker {
            run_id: "other-run".to_string(),
            client_id: "client".to_string(),
            requested_policy_session_id: None,
            policy_session_id: None,
            original_proposal_id: "proposal".to_string(),
            original_submission: json!({"id":"proposal","source":"test","actions":[]}),
            original_proposal: json!({"id":"proposal","source":"test","actions":[]}),
            proposal_digest: "a".repeat(64),
        };
        let path = s.proposal_execution_path("requested-run");
        car_secrets::ensure_private_dir(path.parent().unwrap()).unwrap();
        let mut file = car_secrets::create_private_file(&path).unwrap();
        serde_json::to_writer(&mut file, &marker).unwrap();
        file.sync_all().unwrap();

        let error = s.execution_marker("requested-run").unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("does not match requested run"));

        let mut pending = valid_pending("other-outbox-run");
        pending.client_id = "other-client".to_string();
        let path = s.proposal_outbox_path("requested-outbox-run");
        car_secrets::ensure_private_dir(path.parent().unwrap()).unwrap();
        let mut file = car_secrets::create_private_file(&path).unwrap();
        serde_json::to_writer(&mut file, &pending).unwrap();
        file.sync_all().unwrap();
        let error = s.pending_proposal("requested-outbox-run").unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("does not match requested run"));
    }

    #[test]
    fn execution_marker_reader_rejects_semantically_invalid_preimage() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = store(tmp.path().join("runs"));
        let pending = valid_pending("invalid-marker");
        let marker = ProposalExecutionMarker {
            run_id: pending.run_id.clone(),
            client_id: pending.client_id.clone(),
            requested_policy_session_id: None,
            policy_session_id: None,
            original_proposal_id: pending.original_proposal_id.clone(),
            original_submission: pending.original_submission.clone(),
            original_proposal: serde_json::to_value(&pending.original_proposal).unwrap(),
            proposal_digest: "A".repeat(64),
        };
        let path = s.proposal_execution_path(&pending.run_id);
        car_secrets::ensure_private_dir(path.parent().unwrap()).unwrap();
        let mut file = car_secrets::create_private_file(&path).unwrap();
        serde_json::to_writer(&mut file, &marker).unwrap();
        file.sync_all().unwrap();

        let error = s.execution_marker(&pending.run_id).unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("does not bind"));
    }

    #[test]
    fn execution_marker_cleanup_requires_the_full_identity_tuple() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let pending = valid_pending("marker-cleanup-tuple");
        let marker = marker_for_pending(&pending);
        store.write_execution_marker(&marker).unwrap();

        let mut mismatched = marker.clone();
        mismatched.requested_policy_session_id = Some("self-claimed-policy".to_string());
        assert!(store.clear_execution_marker(&mismatched).is_err());
        assert_eq!(
            store.execution_marker(&marker.run_id).unwrap(),
            Some(marker.clone()),
            "tuple mismatch must preserve the exact durable marker"
        );

        store.clear_execution_marker(&marker).unwrap();
        assert!(store.execution_marker(&marker.run_id).unwrap().is_none());
    }

    #[test]
    fn typed_finalization_rejects_invalid_result_and_lineage() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = store(tmp.path().join("runs"));
        let valid = valid_pending("typed-valid");
        valid.validate().unwrap();
        write_pending_provenance(&s, &valid);
        s.write_pending_proposal(&valid).unwrap();
        assert_eq!(s.pending_proposal("typed-valid").unwrap(), Some(valid));

        let mut missing_final = valid_pending("typed-missing-final");
        missing_final.proposal_result.final_proposal = None;
        assert!(missing_final.validate().is_err());

        let mut wrong_digest = valid_pending("typed-wrong-digest");
        wrong_digest.proposal_result.replan_lineage[0].proposal_digest = Some("A".repeat(64));
        assert!(wrong_digest.validate().is_err());

        let mut wrong_final = valid_pending("typed-wrong-final");
        wrong_final.final_proposal_id = "another-final".to_string();
        assert!(wrong_final.validate().is_err());

        let mut rejected_tail = valid_pending("typed-rejected-tail");
        rejected_tail
            .proposal_result
            .replan_lineage
            .push(ProposalLineageEntry {
                generation: 1,
                proposal_id: "rejected-candidate".to_string(),
                proposal_digest: Some("d".repeat(64)),
                status: ProposalLineageStatus::Rejected,
                rejection_reason: Some("candidate failed quality gate".to_string()),
            });
        let value = serde_json::to_value(&rejected_tail.proposal_result).unwrap();
        let canonical = car_inference::catalog_identity::canonical_json(&value).unwrap();
        rejected_tail.result_digest = format!("{:x}", Sha256::digest(canonical.as_bytes()));
        rejected_tail.validate().unwrap();

        let mut rejected_without_reason = valid_pending("typed-rejected-no-reason");
        rejected_without_reason
            .proposal_result
            .replan_lineage
            .push(ProposalLineageEntry {
                generation: 1,
                proposal_id: "rejected-candidate".to_string(),
                proposal_digest: None,
                status: ProposalLineageStatus::Rejected,
                rejection_reason: None,
            });
        assert!(rejected_without_reason.validate().is_err());

        let mut rejected_zero_then_accepted = valid_pending("typed-rejected-zero");
        rejected_zero_then_accepted.proposal_result.replan_lineage[0].status =
            ProposalLineageStatus::Rejected;
        rejected_zero_then_accepted.proposal_result.replan_lineage[0].rejection_reason =
            Some("original rejected".to_string());
        rejected_zero_then_accepted
            .proposal_result
            .replan_lineage
            .push(ProposalLineageEntry {
                generation: 1,
                proposal_id: rejected_zero_then_accepted.final_proposal_id.clone(),
                proposal_digest: Some(
                    proposal_digest(&rejected_zero_then_accepted.final_proposal).unwrap(),
                ),
                status: ProposalLineageStatus::Accepted,
                rejection_reason: None,
            });
        rejected_zero_then_accepted
            .accepted_proposal_preimages
            .push(AcceptedProposalPreimage {
                generation: 1,
                proposal: rejected_zero_then_accepted.final_proposal.clone(),
            });
        refresh_pending_result_digest(&mut rejected_zero_then_accepted);
        assert!(rejected_zero_then_accepted.validate().is_err());
    }

    #[test]
    fn active_pending_requires_exact_raw_submission_shape() {
        let valid = valid_pending("raw-valid");
        valid.validate().unwrap();

        for raw in [
            Value::Null,
            json!([]),
            json!({"id": valid.original_proposal_id, "source": "run-store-test"}),
            json!({
                "id": valid.original_proposal_id,
                "source": "run-store-test",
                "actions": [{"id":"not-the-typed-action","type":"state_read"}]
            }),
        ] {
            let mut invalid = valid.clone();
            invalid.original_submission = raw;
            assert!(
                invalid.validate().is_err(),
                "active pending accepted invalid raw submission: {}",
                invalid.original_submission
            );
        }

        let mut with_extra = valid;
        with_extra.original_submission["caller_extension"] = json!({"kept": true});
        with_extra.validate().unwrap();
        assert_eq!(
            with_extra.event_data()["original_submission"]["caller_extension"],
            json!({"kept": true})
        );
    }

    #[test]
    fn fresh_pending_write_requires_exact_run_and_marker_provenance() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let pending = valid_pending("fresh-provenance");

        assert!(
            store.write_pending_proposal(&pending).is_err(),
            "pending without durable RunStarted and execution marker must be rejected"
        );
        write_pending_provenance(&store, &pending);
        store.write_pending_proposal(&pending).unwrap();
        assert_eq!(
            store.pending_proposal(&pending.run_id).unwrap(),
            Some(pending.clone())
        );

        store.clear_pending_proposal(&pending).unwrap();
        let mut client_mismatch = pending.clone();
        client_mismatch.client_id = "self-claimed-client".to_string();
        let mut requested_policy_mismatch = pending.clone();
        requested_policy_mismatch.requested_policy_session_id =
            Some("self-claimed-policy".to_string());
        let mut run_mismatch = pending.clone();
        run_mismatch.run_id = "self-claimed-run".to_string();
        let mut original_mismatch = pending;
        rebind_pending_original(&mut original_mismatch);
        for (name, mismatched) in [
            ("client", client_mismatch),
            ("requested policy", requested_policy_mismatch),
            ("run", run_mismatch),
            ("original proposal", original_mismatch),
        ] {
            assert!(
                store.write_pending_proposal(&mismatched).is_err(),
                "pending {name} self-claim must not override durable run/marker provenance"
            );
        }

        let mut authenticated = valid_pending("fresh-auth-provenance");
        authenticated.requested_policy_session_id = Some("live-policy".to_string());
        authenticated.policy_session_id = Some("live-policy".to_string());
        write_pending_provenance(&store, &authenticated);
        authenticated.policy_session_id = None;
        assert!(
            store.write_pending_proposal(&authenticated).is_err(),
            "pending authenticated policy self-claim must match the durable marker"
        );
    }

    #[test]
    fn outbox_reader_requires_active_v3_typed_result_fields() {
        let tmp = tempfile::TempDir::new().unwrap();
        let s = store(tmp.path().join("runs"));
        let pending = valid_pending("strict-result");
        let mut value = serde_json::to_value(&pending).unwrap();
        value["proposal_result"]
            .as_object_mut()
            .unwrap()
            .remove("cost");
        let path = s.proposal_outbox_path("strict-result");
        car_secrets::ensure_private_dir(path.parent().unwrap()).unwrap();
        let mut file = car_secrets::create_private_file(&path).unwrap();
        serde_json::to_writer(&mut file, &value).unwrap();
        file.sync_all().unwrap();

        let error = s.pending_proposal("strict-result").unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("missing `cost`"));
    }

    /// FIX 4 (corollary): a completed run is NOT adopted (it already has a
    /// terminal record).
    #[test]
    fn adopt_orphans_leaves_completed_runs_alone() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s = store(root);
        s.write_started(&started("done", "agent-a", Utc::now()))
            .unwrap();
        s.append_records(
            "agent-a",
            "done",
            &[ended("done", "agent-a", OutcomeStatus::Success)],
        )
        .unwrap();
        assert_eq!(s.adopt_orphans(), 0);
        assert_eq!(s.list_runs("agent-a")[0].status, RunStatus::Completed);
    }

    /// A torn final tail is tolerated only until another committed record
    /// follows it. The separator makes the prior fragment a durable malformed
    /// middle row, so the trace must then be quarantined rather than filtered.
    #[test]
    fn appending_after_torn_tail_quarantines_trace() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let s = store(root.clone());
        s.write_started(&started("run-1", "agent-a", Utc::now()))
            .unwrap();
        s.append_turns("agent-a", "run-1", &[turn(0, "first")])
            .unwrap();

        // Simulate a torn append: a partial line with NO trailing newline.
        let path = root.join("agent-a").join("run-1.jsonl");
        {
            let mut f = std::fs::OpenOptions::new()
                .append(true)
                .open(&path)
                .unwrap();
            // No writeln! — deliberately leaves the file's last byte != '\n'.
            f.write_all(b"{\"record\":\"turn\",\"index\":1,\"prom")
                .unwrap();
        }
        let mut opened = car_secrets::open_private_append(&path).unwrap();
        assert!(
            last_byte_is_not_newline(&mut opened).unwrap(),
            "precondition: tail is torn (no trailing newline)"
        );
        drop(opened);

        // A following durable record turns the torn fragment into a committed
        // middle row. The append itself is durable but the trace is no longer
        // eligible for trusted replay/completion.
        let append_error = s
            .append_turns("agent-a", "run-1", &[turn(2, "third")])
            .expect_err("committed middle corruption must fail the append receipt");
        assert!(
            append_error.to_string().contains("line 3"),
            "{append_error}"
        );

        let error = s.get_run_trace_checked("run-1").unwrap_err();
        assert!(error.to_string().contains("line 3"), "{error}");
        let summary = &s.list_runs("agent-a")[0];
        assert_eq!(summary.status, RunStatus::Incomplete);
        assert_eq!(summary.trace_corruption.as_ref().unwrap().line, 3);
    }

    #[test]
    fn durable_boundaries_fail_closed_and_retry_without_duplicate_rows() {
        for point in [
            RunStoreFailurePoint::Write,
            RunStoreFailurePoint::Flush,
            RunStoreFailurePoint::Fsync,
        ] {
            let tmp = tempfile::TempDir::new().unwrap();
            let root = tmp.path().join("runs");
            let failures = RunStoreFailureInjector::default();
            let store = RunStore::new(root.clone(), RetentionConfig::default())
                .with_failure_injector(failures.clone());
            let started = started("durable", "agent-a", Utc::now());

            failures.fail_next(point);
            assert!(
                store.write_started(&started).is_err(),
                "{point:?} start must not acknowledge"
            );
            store
                .write_started(&started)
                .expect("exact start retry reaches durability");

            let ended = match ended("durable", "agent-a", OutcomeStatus::Success) {
                RunRecord::Ended(ended) => ended,
                _ => unreachable!(),
            };
            failures.fail_next(point);
            assert!(
                store.write_ended(&ended).is_err(),
                "{point:?} terminal must not acknowledge"
            );
            store
                .write_ended(&ended)
                .expect("exact terminal retry reaches durability");

            let restarted = RunStore::new(root, RetentionConfig::default());
            let trace = restarted.get_run_trace("durable").unwrap();
            assert_eq!(
                trace
                    .iter()
                    .filter(|row| matches!(row, RunRecord::Started(_)))
                    .count(),
                1,
                "{point:?} retry duplicated RunStarted"
            );
            assert_eq!(
                trace
                    .iter()
                    .filter(|row| matches!(row, RunRecord::Ended(_)))
                    .count(),
                1,
                "{point:?} retry duplicated RunEnded"
            );
        }
    }

    #[test]
    fn retained_completed_proposal_survives_run_gc_and_restart() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let retention = RetentionConfig {
            max_per_agent: 0,
            max_age_days: DEFAULT_MAX_AGE_DAYS,
        };
        let store = RunStore::new(root.clone(), retention);
        let pending = valid_pending("completed-after-gc");
        write_pending_provenance(&store, &pending);
        store.write_pending_proposal(&pending).unwrap();
        let receipt = store.write_completed_proposal(&pending).unwrap();
        store.cleanup_completed_proposal_guards(&receipt).unwrap();
        let ended = match ended(&pending.run_id, "agent-a", OutcomeStatus::Success) {
            RunRecord::Ended(ended) => ended,
            _ => unreachable!(),
        };
        store.write_ended(&ended).unwrap();

        assert_eq!(store.gc(), 1, "the completed run trace must be evicted");
        assert!(store.get_run_trace(&pending.run_id).is_none());
        assert_eq!(
            store
                .completed_proposal(
                    &pending.run_id,
                    &pending.client_id,
                    pending.requested_policy_session_id.as_deref(),
                    &pending.original_submission,
                )
                .unwrap(),
            Some(receipt.clone()),
            "receipt validity must not depend on a GC-eligible RunStarted"
        );

        let restarted = RunStore::new(root, retention);
        assert_eq!(
            restarted
                .completed_proposal_retry_owner(
                    pending.requested_policy_session_id.as_deref(),
                    &pending.original_submission,
                )
                .unwrap(),
            Some((pending.run_id.clone(), pending.client_id.clone())),
            "the retry tuple owner must remain recoverable after restart"
        );
        assert_eq!(restarted.all_completed_proposals().unwrap(), vec![receipt]);
    }

    #[test]
    fn resumed_completed_proposal_lookup_requires_one_exact_receipt() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let mut first = valid_pending("resumed-policy-rotation");
        first.requested_policy_session_id = Some("original-policy-one".to_string());
        first.policy_session_id = first.requested_policy_session_id.clone();
        write_pending_provenance(&store, &first);
        store.write_pending_proposal(&first).unwrap();
        let first_receipt = store.write_completed_proposal(&first).unwrap();
        store
            .cleanup_completed_proposal_guards(&first_receipt)
            .unwrap();

        assert_eq!(
            store
                .completed_proposal_for_resumed_owner(
                    &first.run_id,
                    &first.client_id,
                    &first.original_submission,
                )
                .unwrap(),
            Some(first_receipt),
            "a single exact receipt is recoverable without the closed policy-session id"
        );
        assert!(
            store
                .completed_proposal_for_resumed_owner(
                    &first.run_id,
                    &first.client_id,
                    &json!({"id":"different"}),
                )
                .unwrap()
                .is_none(),
            "a different proposal must not match"
        );

        let mut second = first.clone();
        second.requested_policy_session_id = Some("original-policy-two".to_string());
        second.policy_session_id = second.requested_policy_session_id.clone();
        store
            .write_execution_marker(&marker_for_pending(&second))
            .unwrap();
        store.write_pending_proposal(&second).unwrap();
        let second_receipt = store.write_completed_proposal(&second).unwrap();
        store
            .cleanup_completed_proposal_guards(&second_receipt)
            .unwrap();

        let error = store
            .completed_proposal_for_resumed_owner(
                &first.run_id,
                &first.client_id,
                &first.original_submission,
            )
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("ambiguous"));
    }

    #[test]
    fn resumed_completed_proposal_lookup_enforces_receipt_count_before_deserialization() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let target = valid_pending("resumed-receipt-count-limit");
        let target_receipt = write_completed_receipt_fixture(&store, target.clone(), None, false);
        for index in 1..MAX_RESUMED_PROPOSAL_RECEIPTS_PER_RUN {
            let mut unrelated = target.clone();
            unrelated.client_id = format!("unrelated-client-{index}");
            write_completed_receipt_fixture(&store, unrelated, None, false);
        }

        assert_eq!(
            store
                .completed_proposal_for_resumed_owner(
                    &target.run_id,
                    &target.client_id,
                    &target.original_submission,
                )
                .unwrap(),
            Some(target_receipt),
            "the exact receipt-count limit remains recoverable"
        );

        let corrupt_path = store
            .completed_response_run_root(&target.run_id)
            .join("count-plus-one-is-never-deserialized.json");
        let mut corrupt = store.create_private_file(&corrupt_path).unwrap();
        corrupt.write_all(b"not-json").unwrap();
        corrupt.sync_all().unwrap();
        let error = store
            .completed_proposal_for_resumed_owner(
                &target.run_id,
                &target.client_id,
                &target.original_submission,
            )
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("receipt count limit"));
    }

    #[test]
    fn resumed_completed_proposal_lookup_enforces_byte_limit_before_deserialization() {
        let at_limit = tempfile::TempDir::new().unwrap();
        let at_limit_store = store(at_limit.path().join("runs"));
        let target = valid_pending("resumed-receipt-byte-limit");
        let first_receipt_bytes = MAX_RESUMED_PROPOSAL_RECEIPT_BYTES_PER_RUN as usize / 2;
        let target_receipt = write_completed_receipt_fixture(
            &at_limit_store,
            target.clone(),
            Some(first_receipt_bytes),
            false,
        );
        let mut unrelated = target.clone();
        unrelated.client_id = "unrelated-byte-limit-client".to_string();
        write_completed_receipt_fixture(
            &at_limit_store,
            unrelated,
            Some(MAX_RESUMED_PROPOSAL_RECEIPT_BYTES_PER_RUN as usize - first_receipt_bytes),
            false,
        );
        assert_eq!(
            at_limit_store
                .completed_proposal_for_resumed_owner(
                    &target.run_id,
                    &target.client_id,
                    &target.original_submission,
                )
                .unwrap(),
            Some(target_receipt),
            "the exact cumulative-byte limit remains recoverable"
        );

        let cumulative_over_limit = tempfile::TempDir::new().unwrap();
        let cumulative_over_limit_store = store(cumulative_over_limit.path().join("runs"));
        write_completed_receipt_fixture(
            &cumulative_over_limit_store,
            target.clone(),
            Some(first_receipt_bytes),
            false,
        );
        let mut unrelated = target.clone();
        unrelated.client_id = "unrelated-byte-over-limit-client".to_string();
        write_completed_receipt_fixture(
            &cumulative_over_limit_store,
            unrelated,
            Some(MAX_RESUMED_PROPOSAL_RECEIPT_BYTES_PER_RUN as usize - first_receipt_bytes + 1),
            false,
        );
        let error = cumulative_over_limit_store
            .completed_proposal_for_resumed_owner(
                &target.run_id,
                &target.client_id,
                &target.original_submission,
            )
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("receipt byte limit"));

        let invalid_over_limit = tempfile::TempDir::new().unwrap();
        let invalid_over_limit_store = store(invalid_over_limit.path().join("runs"));
        write_completed_receipt_fixture(
            &invalid_over_limit_store,
            target.clone(),
            Some(MAX_RESUMED_PROPOSAL_RECEIPT_BYTES_PER_RUN as usize),
            true,
        );
        let error = invalid_over_limit_store
            .completed_proposal_for_resumed_owner(
                &target.run_id,
                &target.client_id,
                &target.original_submission,
            )
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(
            error.to_string().contains("receipt byte limit"),
            "the byte ceiling must reject an oversized corrupt receipt before deserialization"
        );
    }

    #[test]
    fn resumed_completed_proposal_lookup_rejects_corrupt_receipt_under_limits() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let target = valid_pending("resumed-corrupt-receipt");
        let run_root = store.completed_response_run_root(&target.run_id);
        store.ensure_private_dir(&run_root).unwrap();
        let path = store
            .completed_response_path(
                &target.run_id,
                &target.client_id,
                target.requested_policy_session_id.as_deref(),
                &target.original_submission,
            )
            .unwrap();
        let mut corrupt = store.create_private_file(&path).unwrap();
        corrupt.write_all(b"not-json").unwrap();
        corrupt.sync_all().unwrap();

        let error = store
            .completed_proposal_for_resumed_owner(
                &target.run_id,
                &target.client_id,
                &target.original_submission,
            )
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert!(!error.to_string().contains("receipt count limit"));
        assert!(!error.to_string().contains("receipt byte limit"));
    }

    #[test]
    fn completed_proposal_owner_lookup_does_not_scan_unrelated_receipts() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let unrelated_dir = store.completed_response_root().join("unrelated-run");
        car_secrets::ensure_private_dir(&unrelated_dir).unwrap();
        let path = unrelated_dir.join("corrupt.json");
        let mut file = car_secrets::create_private_file(&path).unwrap();
        file.write_all(b"not-json").unwrap();
        file.sync_all().unwrap();

        assert_eq!(
            store
                .completed_proposal_retry_owner(None, &json!({"id": "absent"}))
                .unwrap(),
            None,
            "a bounded content-addressed miss must not enumerate unrelated receipts"
        );
    }

    #[test]
    fn proposal_retry_reservation_is_first_writer_wins_and_exact_owner_idempotent() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let submission = json!({"id":"reserved","source":"test","actions":[]});
        assert_eq!(
            store
                .reserve_proposal_retry_owner("first-run", "first-client", None, &submission)
                .unwrap(),
            ProposalRetryReservation::Acquired
        );
        for (run_id, client_id) in [
            ("first-run", "first-client"),
            ("second-run", "second-client"),
        ] {
            assert_eq!(
                store
                    .reserve_proposal_retry_owner(run_id, client_id, None, &submission)
                    .unwrap(),
                ProposalRetryReservation::Existing {
                    run_id: "first-run".to_string(),
                    client_id: "first-client".to_string(),
                }
            );
        }
        assert_eq!(
            store
                .completed_proposal_retry_owner(None, &submission)
                .unwrap(),
            Some(("first-run".to_string(), "first-client".to_string()))
        );
    }

    #[test]
    fn partial_proposal_retry_reservation_fails_closed_without_replacement() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let submission = json!({"id":"partial","source":"test","actions":[]});
        let root = store.completed_response_index_root();
        car_secrets::ensure_private_dir(&root).unwrap();
        let path = store
            .completed_response_owner_path(None, &submission)
            .unwrap();
        let mut file = car_secrets::create_private_file(&path).unwrap();
        file.write_all(b"{").unwrap();
        file.sync_all().unwrap();

        let error = store
            .reserve_proposal_retry_owner("partial-run", "partial-client", None, &submission)
            .unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
        assert_eq!(std::fs::read(&path).unwrap(), b"{");
    }

    #[test]
    fn completed_proposal_owner_claim_rejects_a_different_run_for_the_same_retry_tuple() {
        let tmp = tempfile::TempDir::new().unwrap();
        let store = store(tmp.path().join("runs"));
        let first = valid_pending("owner-first-run");
        write_pending_provenance(&store, &first);
        store.write_pending_proposal(&first).unwrap();
        store.write_completed_proposal(&first).unwrap();

        let mut conflicting = first.clone();
        conflicting.run_id = "owner-conflicting-run".to_string();
        write_pending_provenance(&store, &conflicting);
        store.write_pending_proposal(&conflicting).unwrap();
        let error = store.write_completed_proposal(&conflicting).unwrap_err();
        assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
        assert!(error.to_string().contains("different completed response"));
        assert_eq!(
            store
                .completed_proposal_retry_owner(
                    first.requested_policy_session_id.as_deref(),
                    &first.original_submission,
                )
                .unwrap(),
            Some((first.run_id.clone(), first.client_id.clone())),
            "a conflicting writer must not replace the first durable owner"
        );
        assert!(
            store
                .completed_proposal(
                    &conflicting.run_id,
                    &conflicting.client_id,
                    conflicting.requested_policy_session_id.as_deref(),
                    &conflicting.original_submission,
                )
                .unwrap()
                .is_none(),
            "the rejected owner must not publish a receipt"
        );
    }

    #[test]
    fn startup_enumeration_backfills_a_legacy_completed_proposal_owner() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path().join("runs");
        let initial = store(root.clone());
        let pending = valid_pending("legacy-owner-backfill");
        write_pending_provenance(&initial, &pending);
        initial.write_pending_proposal(&pending).unwrap();
        let receipt = initial.write_completed_proposal(&pending).unwrap();
        let owner_path = initial
            .completed_response_owner_path(
                pending.requested_policy_session_id.as_deref(),
                &pending.original_submission,
            )
            .unwrap();
        std::fs::remove_file(&owner_path).unwrap();
        sync_directory(owner_path.parent().unwrap()).unwrap();

        let restarted = store(root);
        assert!(
            restarted
                .completed_proposal_retry_owner(
                    pending.requested_policy_session_id.as_deref(),
                    &pending.original_submission,
                )
                .unwrap()
                .is_none(),
            "pre-index receipts begin without an ownership claim"
        );
        assert_eq!(restarted.all_completed_proposals().unwrap(), vec![receipt]);
        assert_eq!(
            restarted
                .completed_proposal_retry_owner(
                    pending.requested_policy_session_id.as_deref(),
                    &pending.original_submission,
                )
                .unwrap(),
            Some((pending.run_id, pending.client_id)),
            "startup receipt enumeration must durably backfill the owner claim"
        );
    }
}