khive-runtime 0.10.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
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
//! Events-daemon split (ADR-170): the audit lane leaves the domain store.
//!
//! The ADR-133 idempotent audit batch is the measured bulk of event write
//! volume, and in a single-store deployment its rows queue on the same SQLite
//! writer lane as domain mutations. This module moves that lane into a
//! dedicated events daemon that owns the events database, reachable over a
//! Unix socket with the same length-prefixed framing and peer-uid admission the
//! main daemon socket uses. Plain event appends stay on the domain store —
//! the legacy `events` table has raw-SQL consumers (schedule provenance, kg
//! projection guards, graph-query substrate unions) whose correctness
//! depends on finding those rows there.
//!
//! Cooperating pieces:
//!
//! - [`run_events_daemon`] — the server loop the `events-daemon` subcommand
//!   runs: binds the events socket, owns the only resident writer of the
//!   events database, and serves append/read requests through the ordinary
//!   `SqlEventStore`.
//! - [`EventsSplitClient`] — one per domain process. Plain appends ride a
//!   bounded in-memory queue drained by a background forwarder
//!   (fire-and-forget; overflow or a dead daemon drops the batch, counts it,
//!   and logs — the loss-tolerant durability class made concrete; unused by
//!   the default routing until telemetry producers opt in). Idempotent
//!   audit-batch appends and reads are synchronous framed round-trips with
//!   bounded timeouts, because their callers are background flushers or query
//!   paths, never the dispatch hot path.
//! - [`ForwardingEventStore`] — the lane-side [`EventStore`] over the socket.
//!   Preflight validation delegates to an in-memory `SqlEventStore`, so the
//!   ADR-133 audit-batch seam keeps its pre-enqueue shape check without any
//!   I/O on the dispatch path.
//! - [`SplitEventStore`] — the per-namespace handle
//!   [`crate::runtime::KhiveRuntime::events`] returns when the split is
//!   configured: routes the idempotent lane to the events store, plain
//!   appends to the legacy store, and merges reads across both.
//!
//! Domain availability never depends on events-daemon liveness: every failure
//! path here degrades (drop + count + log, or a typed storage error for the
//! synchronous lanes) instead of blocking the caller.

use std::path::{Path, PathBuf};
#[cfg(unix)]
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
#[cfg(unix)]
use std::time::Duration;

use async_trait::async_trait;
use khive_db::{StorageBackend, WalCeilingPolicy};
use khive_storage::event::{EventPageQuery, EventPageWindow, IdempotentEventBatchResult};
use khive_storage::{
    BatchWriteSummary, Event, EventFilter, EventStore, Page, PageRequest, StorageError,
    StorageResult,
};
use serde::{Deserialize, Serialize};

#[cfg(unix)]
use tokio::net::{UnixListener, UnixStream};
use uuid::Uuid;

#[cfg(unix)]
use crate::daemon::{read_frame, write_frame};

/// Bump whenever the request or response frame shape changes incompatibly.
/// The server rejects frames whose version it does not speak, so a skewed
/// client gets a typed refusal instead of a deserialization panic.
///
/// Version 2 was the first version any release shipped: version 1 carried a
/// `side_effects_unknown` error field that was replaced by the
/// `writer_task_state` carrier before this module reached any released ref,
/// so v1 speakers existed only on unreleased development heads. The bump
/// exists so that even such a process gets the version refusal above rather
/// than having its retryable writer states silently mapped to terminal
/// `InvalidInput`. Version 3 replaces that state-only carrier with a failure
/// disposition so a proven rollback can cross the socket without falsely
/// claiming the remote writer task terminated. Version 4 adds exact event-target
/// filtering and the refusal kind. Older readers would ignore the new filter
/// field, silently broadening a query, so both peers must speak version 4.
pub const EVENTS_PROTOCOL_VERSION: u32 = 4;

/// Default bound on the fire-and-forget append queue, in batches. The byte
/// bound below also applies, so a large batch cannot multiply this depth
/// into unbounded retained event memory.
#[cfg(unix)]
pub const DEFAULT_APPEND_QUEUE_BATCHES: usize = 4096;

/// Maximum serialized append-request bytes retained by the fire-and-forget
/// queue and its one in-flight delivery. A single request must also fit the
/// daemon's per-frame cap; the queue budget covers several such requests.
#[cfg(unix)]
pub const DEFAULT_APPEND_QUEUE_BYTES: usize = 32 * 1024 * 1024;

/// Timeout for one synchronous round-trip (idempotent appends, reads).
/// Covers the WHOLE attempt — connect, peer verification, write, read —
/// because each round-trip owns its connection (no shared lock to wait on
/// outside the clock).
#[cfg(unix)]
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

/// Reconnect backoff for the background forwarder after a failed connect.
#[cfg(unix)]
const FORWARDER_BACKOFF: Duration = Duration::from_secs(2);

/// Cap on concurrently served daemon connections. Admission control, not a
/// correctness bound: every permitted-uid process on the machine shares the
/// daemon, and without a cap each accepted connection holds a task and a file
/// descriptor for as long as the peer keeps the socket open — a stalled or
/// hostile same-uid peer could exhaust both. Excess connects are dropped
/// (peer sees EOF) and retried by the clients' own reconnect paths.
#[cfg(unix)]
const MAX_EVENTS_CONNECTIONS: usize = 128;

/// Per-frame I/O deadline on a served connection: the longest the daemon
/// waits for one request frame to finish arriving, or one response frame to
/// finish sending. A peer that sends a partial frame and stalls is closed
/// instead of holding its task and descriptor forever. Idle well-behaved
/// clients are closed too — that is fine by construction: round-trips open a
/// fresh connection per call, and the forwarder's delivery path retries once
/// on a stale connection.
#[cfg(unix)]
const CONN_IO_TIMEOUT: Duration = Duration::from_secs(60);

/// Aggregate cap on request-frame bytes buffered across all served
/// connections at once. The per-frame cap bounds one buffer and the
/// connection cap bounds the task count, but their product is the real
/// allocation exposure (128 connections × 8 MiB declared frames ≈ 1 GiB).
/// Body buffers are admitted against this shared byte budget before they are
/// allocated; a connection whose frame cannot be admitted waits inside its
/// own I/O deadline, so exhaustion degrades into per-connection timeouts,
/// never into daemon memory growth. Must be at least `MAX_FRAME_BYTES`, or a
/// maximum-size frame could never be admitted.
#[cfg(unix)]
const MAX_INFLIGHT_REQUEST_BYTES: usize = 64 * 1024 * 1024;

/// Cap on the per-namespace store cache. Stores are cheap pool handles, but
/// the namespace string is client-supplied, so an unbounded map is
/// attacker-controlled memory growth. Beyond the cap, stores are built
/// per-request instead of cached — slower, never wrong.
#[cfg(unix)]
const MAX_CACHED_NAMESPACE_STORES: usize = 1024;

/// Symlink-chain hop ceiling for events-path resolution. Matches the bound
/// the daemon's socket-path traversal guard enforces, which is itself the
/// kernel's total-links ceiling on Linux (40): both resolvers must agree,
/// or a chain one accepts derives a different identity than the other.
const EVENTS_SYMLINK_HOP_BOUND: u32 = 40;

/// Cap on `QueryEvents` page size, in rows. The wire `PageRequest.limit` is
/// client-supplied `u32`, and the daemon materializes the full page as a
/// `Vec<Event>` and serializes it into one response frame — so an unbounded
/// limit is attacker-controlled memory and serialization work in a process
/// that lives for months. Over-cap requests get a typed refusal naming the
/// cap, never a silently clamped page: a caller that asked for more rows
/// than it got would otherwise read the short page as the end of the data.
/// The split client's merged read requests a prefix of `offset + limit`
/// rows, so this cap also bounds the deep-offset window a socket client can
/// demand in one request.
///
/// Public (and defined on every platform) because in-tree consumers that
/// read events through a possibly-split store must size their page requests
/// under it — a deep read is a `before`-cursor walk at `offset: 0` in pages
/// of at most this many rows, never one wide page. Even a page under this row
/// cap can exceed the IPC frame cap; the daemon then returns a non-retryable
/// `response_frame_size_limit` refusal so the caller can narrow the page.
pub const MAX_QUERY_EVENTS_PAGE_ROWS: u32 = 4096;

/// Default events database file, beside the main database file.
///
/// The name is derived from the main database's full file name (`khive.db` →
/// `khive.db.events.db`), never from its stem and never a fixed name in the
/// parent directory: two independent databases that happen to share a
/// directory (`a.db`, `b.db`) — or a stem (`a.db`, `a.sqlite`) — must each
/// get their own event plane, not silently share one. The whole path is
/// canonicalized when the database file exists — final-component symlink
/// aliases of one database must derive the same sidecar and socket as the
/// target spelling, because backend identity already treats those aliases as
/// one database. When the file does not exist yet, the parent directory alone
/// is canonicalized when it resolves, so path aliases of a fresh database
/// (relative spellings, symlinked directories) still map to one sidecar
/// instead of minting a distinct events database per spelling.
pub fn events_db_path_beside(main_db: &Path) -> PathBuf {
    // When the database file does not exist yet, the path can still be a
    // symlink — a dangling alias whose target the first open will create.
    // `canonicalize` refuses dangling links, so resolve final-component
    // links by hand on that arm: alias-first and target-first cold starts
    // must derive the same sidecar, or the first process to open each
    // spelling writes audit records the other never reads.
    let resolved = std::fs::canonicalize(main_db)
        .unwrap_or_else(|_| resolve_dangling_final_component(main_db));
    let mut name = resolved
        .file_name()
        .map(std::ffi::OsStr::to_os_string)
        .unwrap_or_else(|| std::ffi::OsString::from("khive.db"));
    name.push(".events.db");
    let path = match resolved.parent().filter(|dir| !dir.as_os_str().is_empty()) {
        Some(dir) => std::fs::canonicalize(dir)
            .unwrap_or_else(|_| dir.to_path_buf())
            .join(&name),
        None => PathBuf::from(name),
    };
    absolutize(&path)
}

/// Follow final-component symlinks whose eventual target need not exist.
/// The identity being recovered is the target's NAME — the file the first
/// open through the alias will actually create — so a chain of links is
/// walked (relative targets anchored at each link's parent) up to the same
/// bound kernels use; a cycle or over-long chain stops at the last spelling,
/// which `open()` will refuse anyway.
fn resolve_dangling_final_component(path: &Path) -> PathBuf {
    let mut current = path.to_path_buf();
    // Same hop bound as the daemon's socket-path traversal guard (and the
    // kernel's own total-links ceiling on Linux, 40): a chain the kernel
    // would resolve must derive the target's sidecar, or a 33-hop alias
    // opens fine yet splits its audit records from the target spelling.
    for _ in 0..EVENTS_SYMLINK_HOP_BOUND {
        match std::fs::read_link(&current) {
            Ok(target) => {
                current = if target.is_absolute() {
                    target
                } else {
                    match current.parent().filter(|dir| !dir.as_os_str().is_empty()) {
                        Some(dir) => dir.join(target),
                        None => target,
                    }
                };
            }
            Err(_) => break,
        }
    }
    current
}

/// Anchor a relative path to the current working directory. A bare relative
/// spelling (`khive.db`) yields `Some("")` from `Path::parent`, and every
/// consumer downstream — lock-file parenting, socket-directory trust
/// validation, the daemon spawn contract — needs a real directory to stat,
/// not an empty string. Absolute paths pass through untouched.
fn absolutize(path: &Path) -> PathBuf {
    if path.is_absolute() {
        return path.to_path_buf();
    }
    std::env::current_dir()
        .map(|cwd| cwd.join(path))
        .unwrap_or_else(|_| path.to_path_buf())
}

/// Events daemon socket path, beside the events database it serves.
///
/// Derived from the events db path (not a process-global location, not a
/// fixed name in the parent directory) so every events database gets its own
/// daemon and socket: a shared socket would route events from any second
/// database (another seat, a test tempdir) to whichever daemon happens to
/// own it, persisting them beside the wrong main store. `khive.db.events.db`
/// yields `khive.db.events.sock`; the daemon's advisory lock is the same
/// path with a `.lock` extension.
pub fn events_socket_path_beside(events_db: &Path) -> PathBuf {
    events_db.with_extension("sock")
}

#[cfg(unix)]
#[path = "events_split_socket_path.rs"]
pub(crate) mod socket_path;
#[cfg(unix)]
pub use socket_path::validate_events_socket_path;

/// How a runtime reaches event storage when the split is configured.
#[derive(Debug, Clone)]
pub struct EventsSplitConfig {
    /// The events database file. The events daemon is its only writer in
    /// daemon deployments; embedded mode writes it directly.
    pub db_path: PathBuf,
    /// `Some(socket)` = forward appends to the events daemon at this socket
    /// (daemon deployments). `None` = embedded mode: open `db_path` directly
    /// in-process (one-shot CLI, tests).
    pub socket_path: Option<PathBuf>,
}

// ---------------------------------------------------------------------------
// Process-global handles
// ---------------------------------------------------------------------------
//
// One events-split client (or one direct backend) per process, whatever the
// number of runtimes and clones — the same shape as the daemon module's other
// process-global state. Keyed by path so tests exercising two distinct paths
// in one process stay isolated.

#[cfg(unix)]
type ClientMap = std::collections::HashMap<PathBuf, Arc<EventsSplitClient>>;
/// One admission per canonical path. The access mode belongs to the entry,
/// so another mode cannot run raw-file preflight over a live SQLite pool.
/// Strong entries retain the existing process lifetime, including derived stores.
type BackendMap = std::collections::HashMap<PathBuf, (bool, Arc<StorageBackend>)>;

#[cfg(unix)]
fn client_registry() -> &'static std::sync::Mutex<ClientMap> {
    static REGISTRY: std::sync::OnceLock<std::sync::Mutex<ClientMap>> = std::sync::OnceLock::new();
    REGISTRY.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
}

fn direct_backend_registry() -> &'static std::sync::Mutex<BackendMap> {
    static REGISTRY: std::sync::OnceLock<std::sync::Mutex<BackendMap>> = std::sync::OnceLock::new();
    REGISTRY.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
}

/// Release only one test fixture's process-registry entries when its scope ends.
///
/// Borrow a unique temporary directory immediately after creating it, before
/// declaring its backend/store/client handles. Those handles then drop before
/// this guard, and the borrowed directory outlives registry cleanup. Production
/// callers retain the normal process-lifetime registry ownership.
#[cfg(any(test, feature = "test-internals"))]
#[doc(hidden)]
pub struct TestRegistryGuard<'a> {
    root: &'a Path,
    canonical_root: PathBuf,
}

#[cfg(any(test, feature = "test-internals"))]
impl<'a> TestRegistryGuard<'a> {
    /// Keep `root` alive until this fixture's registry references are released.
    pub fn new(root: &'a Path) -> Self {
        Self {
            root,
            canonical_root: std::fs::canonicalize(root).expect("existing unique fixture root"),
        }
    }

    fn remove_entries<T>(
        &self,
        registry: &std::sync::Mutex<std::collections::HashMap<PathBuf, T>>,
    ) -> Vec<T> {
        let mut entries = registry
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let keys: Vec<_> = entries
            .keys()
            .filter(|path| path.starts_with(self.root) || path.starts_with(&self.canonical_root))
            .cloned()
            .collect();
        keys.into_iter()
            .filter_map(|key| entries.remove(&key))
            .collect()
    }
}

#[cfg(any(test, feature = "test-internals"))]
impl Drop for TestRegistryGuard<'_> {
    fn drop(&mut self) {
        // Destructors may close SQLite connections or senders. Run them only
        // after releasing each registry lock; unrelated fixtures keep serving.
        let backends = self.remove_entries(direct_backend_registry());
        #[cfg(unix)]
        let clients = self.remove_entries(client_registry());
        drop(backends);
        #[cfg(unix)]
        drop(clients);
    }
}

/// The process-wide client for `socket_path`, created (and its forwarder
/// spawned) on first use. Requires a tokio runtime context on first call.
#[cfg(unix)]
pub fn client_for(socket_path: &Path) -> crate::error::RuntimeResult<Arc<EventsSplitClient>> {
    let mut registry = client_registry()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if let Some(existing) = registry.get(socket_path) {
        return Ok(Arc::clone(existing));
    }
    let client = EventsSplitClient::new(socket_path.to_path_buf())?;
    registry.insert(socket_path.to_path_buf(), Arc::clone(&client));
    Ok(client)
}

/// The process-wide direct (embedded-mode) backend for `db_path`, opened
/// read-write on first use.
pub fn direct_backend_for(db_path: &Path) -> crate::error::RuntimeResult<Arc<StorageBackend>> {
    direct_backend_with_max_readers(db_path, false, None)
}

/// The process-wide direct backend for `db_path`, opened READ-ONLY on first
/// use. The file must already exist — this constructor never creates or
/// schema-initializes an events database, which is what a read-only runtime's
/// no-DB-creation contract requires of its event lane.
pub fn direct_backend_read_only_for(
    db_path: &Path,
) -> crate::error::RuntimeResult<Arc<StorageBackend>> {
    direct_backend_with_max_readers(db_path, true, None)
}

/// Standalone opener: resolve its environment once before opening the event lane.
pub(crate) fn direct_backend_with_max_readers(
    db_path: &Path,
    read_only: bool,
    max_readers: Option<usize>,
) -> crate::error::RuntimeResult<Arc<StorageBackend>> {
    let mut config = crate::RuntimeConfig {
        db_path: Some(db_path.to_path_buf()),
        ..crate::RuntimeConfig::no_embeddings()
    };
    let wal_ceiling = config.resolve_wal_ceiling_policy(read_only)?;
    let disk_guard = config.resolve_disk_guard_policy(read_only)?;
    direct_backend_with_policies(
        db_path,
        read_only,
        max_readers,
        wal_ceiling,
        disk_guard,
        config.volume_lock_dir,
    )
}

/// Open the direct event lane with the policies already resolved for its main
/// backend. A writable open also needs the disk policy and the volume lock
/// directory; a read-only open uses neither.
pub(crate) fn direct_backend_with_policies(
    db_path: &Path,
    read_only: bool,
    max_readers: Option<usize>,
    wal_ceiling: WalCeilingPolicy,
    disk_guard: Option<khive_db::EffectiveDiskGuardConfig>,
    volume_lock_dir: Option<PathBuf>,
) -> crate::error::RuntimeResult<Arc<StorageBackend>> {
    wal_ceiling.validate_static(true, true, read_only)?;
    if !read_only {
        disk_guard
            .ok_or_else(|| {
                crate::error::RuntimeError::Internal("missing events disk policy".into())
            })?
            .validate()?;
        khive_db::require_volume_lock_dir(volume_lock_dir.clone())?;
    }
    let mut registry = direct_backend_registry()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let absolute_path = absolutize(db_path);
    let db_path = absolute_path.as_path();
    refuse_events_db_symlinks(db_path)
        .map_err(|e| crate::error::RuntimeError::Internal(e.to_string()))?;
    #[cfg(unix)]
    if !read_only {
        if let Some(parent) = db_path.parent().filter(|p| !p.as_os_str().is_empty()) {
            let _ = std::fs::create_dir_all(parent);
        }
    }
    // Directory trust comes after creation (a fresh parent in a trusted
    // ancestor must be statable) and before any open: SQLite's open is
    // path-based, so the only defense against a component swapped between
    // validation and open is that no untrusted local user can write the
    // directories the path traverses.
    #[cfg(unix)]
    ensure_events_db_parent_trusted(db_path)
        .map_err(|e| crate::error::RuntimeError::Internal(e.to_string()))?;
    let key = std::fs::canonicalize(db_path)
        .or_else(|error| {
            if error.kind() != std::io::ErrorKind::NotFound {
                return Err(error);
            }
            let parent = db_path.parent().ok_or(error)?;
            let name = db_path.file_name().ok_or_else(|| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidInput,
                    "events path has no file name",
                )
            })?;
            std::fs::canonicalize(parent).map(|parent| parent.join(name))
        })
        .map_err(|e| crate::error::RuntimeError::Internal(e.to_string()))?;
    if let Some((existing_read_only, existing)) = registry.get(&key) {
        if *existing_read_only != read_only {
            let existing_mode = if *existing_read_only {
                "read-only"
            } else {
                "writable"
            };
            let requested_mode = if read_only { "read-only" } else { "writable" };
            return Err(crate::error::RuntimeError::InvalidInput(format!(
                "events database {} is already open {existing_mode} in this process; cannot \
                 open it {requested_mode}; read-only events access requires a separate frozen snapshot",
                key.display()
            )));
        }
        let numbers = |p: Option<khive_db::EffectiveDiskGuardConfig>| {
            p.map(|p| (p.reserve_bytes, p.guard_deadline_ms))
        };
        if numbers(existing.pool().effective_disk_guard_config()) != numbers(disk_guard) {
            return Err(crate::error::RuntimeError::Internal(
                "events database is already open with a different disk reserve/deadline policy"
                    .into(),
            ));
        }
        if !read_only && existing.pool().config().volume_lock_dir != volume_lock_dir {
            return Err(crate::error::RuntimeError::Internal(
                "events database is already open with a different volume-lock directory".into(),
            ));
        }
        let existing_bytes = existing.pool().config().wal_ceiling.bytes;
        if existing_bytes != wal_ceiling.bytes {
            return Err(khive_db::SqliteError::InvalidConfig(format!(
                "events database {} is already open with wal_ceiling_bytes={existing_bytes}; \
                 requested {}; drain and restart before changing the WAL ceiling",
                key.display(),
                wal_ceiling.bytes
            ))
            .into());
        }
        return Ok(Arc::clone(existing));
    }
    let db_path = key.as_path();
    // Embedded writable mode holds the events database to the daemon's own
    // contract: owner-only from the first byte, never at the process umask,
    // and — because event rows carry the same audit payloads either way — a
    // pre-existing database or -wal/-shm sidecar is tightened to 0600 too,
    // fail-closed. A create race just means SQLite finds the file present.
    #[cfg(unix)]
    if !read_only {
        use std::os::unix::fs::OpenOptionsExt;
        let _ = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(db_path);
        // Before the open, and only before it: see the precondition on
        // `harden_events_db_sidecars`.
        let _before_open = harden_events_db_sidecars(db_path)
            .map_err(|e| crate::error::RuntimeError::Internal(e.to_string()))?;
    }
    let backend = Arc::new(if read_only {
        StorageBackend::sqlite_read_only_with_max_readers_and_wal_ceiling(
            db_path,
            max_readers,
            wal_ceiling,
        )?
    } else {
        StorageBackend::sqlite_with_max_readers_and_policies(
            db_path,
            max_readers,
            wal_ceiling,
            disk_guard.ok_or_else(|| {
                crate::error::RuntimeError::Internal("missing events disk policy".into())
            })?,
            khive_db::require_volume_lock_dir(volume_lock_dir)?,
        )?
    });
    registry.insert(key, (read_only, Arc::clone(&backend)));
    Ok(backend)
}

/// Forwarding metrics for the process-wide client at `socket_path`, if one
/// exists. `None` means the split never initialized in this process.
#[cfg(unix)]
pub fn forwarding_metrics(socket_path: &Path) -> Option<EventsForwardingMetrics> {
    let registry = client_registry()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    registry.get(socket_path).map(|client| client.metrics())
}

// ---------------------------------------------------------------------------
// Wire protocol
// ---------------------------------------------------------------------------

/// Request frame sent from a domain process to the events daemon.
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum EventsRequest {
    /// Fire-and-forget append lane. The daemon replies with a summary, but the
    /// forwarder treats a failed reply as a counted drop, never an error to
    /// the original caller.
    AppendEvents {
        protocol_version: u32,
        namespace: String,
        events: Vec<Event>,
    },
    /// ADR-133 audit-batch lane: real dispositions come back.
    AppendEventsIdempotent {
        protocol_version: u32,
        namespace: String,
        events: Vec<Event>,
    },
    GetEvent {
        protocol_version: u32,
        namespace: String,
        id: Uuid,
    },
    QueryEvents {
        protocol_version: u32,
        namespace: String,
        filter: EventFilter,
        page: PageRequest,
    },
    QueryEventPage {
        protocol_version: u32,
        namespace: String,
        query: EventPageQuery,
    },
    CountEvents {
        protocol_version: u32,
        namespace: String,
        filter: EventFilter,
    },
}

impl EventsRequest {
    fn protocol_version(&self) -> u32 {
        match self {
            Self::AppendEvents {
                protocol_version, ..
            }
            | Self::AppendEventsIdempotent {
                protocol_version, ..
            }
            | Self::GetEvent {
                protocol_version, ..
            }
            | Self::QueryEvents {
                protocol_version, ..
            }
            | Self::QueryEventPage {
                protocol_version, ..
            }
            | Self::CountEvents {
                protocol_version, ..
            } => *protocol_version,
        }
    }

    fn namespace(&self) -> &str {
        match self {
            Self::AppendEvents { namespace, .. }
            | Self::AppendEventsIdempotent { namespace, .. }
            | Self::GetEvent { namespace, .. }
            | Self::QueryEvents { namespace, .. }
            | Self::QueryEventPage { namespace, .. }
            | Self::CountEvents { namespace, .. } => namespace,
        }
    }
}

/// Response frame from the events daemon.
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum EventsResponse {
    Appended {
        summary: BatchWriteSummary,
    },
    Idempotent {
        result: IdempotentEventBatchResult,
    },
    Event {
        event: Option<Event>,
    },
    Pageful {
        page: Page<Event>,
    },
    EventPageWindow {
        window: EventPageWindow,
    },
    Count {
        count: u64,
    },
    /// Typed refusal. `retryable` distinguishes transient daemon-side
    /// conditions from contract errors (bad frame, version skew).
    /// `writer_task_failure` carries both request finality and whether the
    /// remote writer seam terminated. The retryable bit cannot express that
    /// distinction: an ordinary operation or COMMIT error may be transient or
    /// permanent while its transaction is independently proven rolled back.
    /// `None` means the error is not from a writer request. Cross-version
    /// frames never reach this mapping because `dispatch_events_request`
    /// refuses a mismatched version before any write executes.
    Error {
        message: String,
        retryable: bool,
        #[serde(default)]
        writer_task_failure: Option<WireWriterTaskFailure>,
    },
}

/// Whether a writer-state error belongs to one failed request on a still-live
/// seam or to a permanently retired writer task.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum WireWriterTaskFailure {
    RequestFailed { request_state: WireWriterTaskState },
    TaskTerminated { request_state: WireWriterTaskState },
}

/// Wire mirror of [`khive_storage::WriterTaskRequestState`]. A separate type
/// because the storage enum is not serializable and the wire shape must stay
/// under this module's protocol-version control, not the storage crate's.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WireWriterTaskState {
    NotStarted,
    TransactionRolledBack,
    SideEffectsUnknown,
}

impl From<khive_storage::WriterTaskRequestState> for WireWriterTaskState {
    fn from(state: khive_storage::WriterTaskRequestState) -> Self {
        use khive_storage::WriterTaskRequestState as S;
        match state {
            S::NotStarted => Self::NotStarted,
            S::TransactionRolledBack => Self::TransactionRolledBack,
            S::SideEffectsUnknown => Self::SideEffectsUnknown,
        }
    }
}

impl From<WireWriterTaskState> for khive_storage::WriterTaskRequestState {
    fn from(state: WireWriterTaskState) -> Self {
        use khive_storage::WriterTaskRequestState as S;
        match state {
            WireWriterTaskState::NotStarted => S::NotStarted,
            WireWriterTaskState::TransactionRolledBack => S::TransactionRolledBack,
            WireWriterTaskState::SideEffectsUnknown => S::SideEffectsUnknown,
        }
    }
}

// ---------------------------------------------------------------------------
// Server side
// ---------------------------------------------------------------------------

/// Advisory lock guaranteeing at most one events daemon per socket path.
/// Held for the daemon's lifetime; a second daemon exits instead of stealing
/// the socket path from the live one.
#[cfg(unix)]
pub struct EventsDaemonGuard {
    _file: std::fs::File,
}

/// Try to become the events daemon for `socket_path`, returning `None` for
/// contention or any refusal. Callers must validate the parent with
/// `ensure_socket_dir_is_trusted` before lock-path operations in that directory.
#[cfg(unix)]
pub fn try_acquire_events_daemon_guard(socket_path: &Path) -> Option<EventsDaemonGuard> {
    match acquire_events_daemon_guard_outcome(socket_path) {
        EventsDaemonGuardAcquisition::Held(guard) => Some(guard),
        _ => None,
    }
}

/// Why a non-blocking daemon-lock acquisition did or did not succeed.
/// Refusals retain the I/O error instead of treating every failure as contention.
#[cfg(unix)]
enum EventsDaemonGuardAcquisition {
    Held(EventsDaemonGuard),
    Contended,
    OpenFailed(std::io::Error),
    HardeningRefused(std::io::Error),
}

#[cfg(unix)]
impl std::fmt::Debug for EventsDaemonGuardAcquisition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Held(_) => f.write_str("Held"),
            Self::Contended => f.write_str("Contended"),
            Self::OpenFailed(error) => f.debug_tuple("OpenFailed").field(error).finish(),
            Self::HardeningRefused(error) => {
                f.debug_tuple("HardeningRefused").field(error).finish()
            }
        }
    }
}

/// Try to become the events daemon for `socket_path`. Every refusal means
/// the caller must not serve; only `Contended` identifies a held lock.
/// Callers that need the socket directory validated must run
/// `ensure_socket_dir_is_trusted` on the parent BEFORE calling this, so no
/// lock-path operation happens in an untrusted directory.
#[cfg(unix)]
fn acquire_events_daemon_guard_outcome(socket_path: &Path) -> EventsDaemonGuardAcquisition {
    use EventsDaemonGuardAcquisition::{Contended, HardeningRefused, Held, OpenFailed};

    let lock_path = socket_path.with_extension("lock");
    if let Some(parent) = lock_path.parent() {
        if let Err(error) = std::fs::create_dir_all(parent) {
            return OpenFailed(error);
        }
    }
    use std::os::unix::fs::OpenOptionsExt;
    // `O_NOFOLLOW` pins the open to the final component: a symlink planted
    // at the lock name is refused instead of redirecting the open (and the
    // chmod below) to an attacker-selected target.
    let file = match std::fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .write(true)
        .mode(0o600)
        .custom_flags(libc::O_NOFOLLOW)
        .open(&lock_path)
    {
        Ok(file) => file,
        Err(error) if error.raw_os_error() == Some(libc::ELOOP) => {
            return HardeningRefused(error);
        }
        Err(error) => return OpenFailed(error),
    };
    // `mode` applies only at creation; tighten a pre-existing lock file too.
    // Descriptor-based (`fchmod` on the handle just opened), never a second
    // path lookup — and fail closed: with the inode pinned, a failed chmod
    // is abnormal, and serving behind a lock file another user can open is
    // exactly what the hardening exists to refuse.
    if let Err(error) = file.set_permissions(
        <std::fs::Permissions as std::os::unix::fs::PermissionsExt>::from_mode(0o600),
    ) {
        return HardeningRefused(error);
    }
    use std::os::fd::AsRawFd;
    // SAFETY: `fd` is a live descriptor owned by `file` for the duration of
    // the call; `flock` reads nothing else.
    let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
    if rc == 0 {
        Held(EventsDaemonGuard { _file: file })
    } else {
        let error = std::io::Error::last_os_error();
        if error.raw_os_error() == Some(libc::EWOULDBLOCK)
            || error.raw_os_error() == Some(libc::EAGAIN)
        {
            Contended
        } else {
            HardeningRefused(error)
        }
    }
}

fn events_db_targets(db_path: &Path) -> [PathBuf; 3] {
    ["", "-wal", "-shm"].map(|suffix| {
        let mut name = db_path.as_os_str().to_os_string();
        name.push(suffix);
        PathBuf::from(name)
    })
}

/// Refuse to serve an events database whose path — or whose `-wal`/`-shm`
/// sidecar path — is a pre-existing symlink. These paths are derived, never
/// user-chosen (`events_db_path_beside` canonicalizes the main database
/// spelling first), so a link here is a planted redirect, not an alias:
/// permission hardening and SQLite would otherwise follow it and tighten or
/// write event rows through to whatever file the link's author chose
/// (CWE-59). Runs before any open on both the embedded and daemon arms; a
/// link planted after admission is bounded by the daemon's trusted-directory
/// contract on the socket parent.
fn refuse_events_db_symlinks(db_path: &Path) -> anyhow::Result<()> {
    for path in events_db_targets(db_path) {
        match std::fs::symlink_metadata(&path) {
            Ok(meta) if meta.file_type().is_symlink() => anyhow::bail!(
                "refusing to serve events: {} is a symlink; the events database and its \
                 sidecars must be regular files",
                path.display()
            ),
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => anyhow::bail!(
                "refusing to serve events: cannot inspect {}: {e}",
                path.display()
            ),
        }
    }
    Ok(())
}

#[cfg(unix)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct EventsFileIdentity {
    device: u64,
    inode: u64,
}

#[cfg(unix)]
impl EventsFileIdentity {
    fn from_metadata(metadata: &std::fs::Metadata) -> Self {
        use std::os::unix::fs::MetadataExt;
        Self {
            device: metadata.dev(),
            inode: metadata.ino(),
        }
    }
}

/// Main/WAL/SHM identities, in `events_db_targets` order. None means the
/// target was absent when pre-open hardening tried to open it.
#[cfg(unix)]
type EventsDbIdentities = [Option<EventsFileIdentity>; 3];

/// Require the directory holding the events database to be trusted before
/// anything opens a path inside it. The symlink pre-checks and the fd-pinned
/// chmod close the races they can see, but SQLite's own open is path-based
/// and cannot be inode-pinned from here — so the remaining defense is the
/// same one the daemon socket uses: no untrusted local user may be able to
/// write (or swap components of) the directory the path traverses. Delegates
/// to the socket-path walk, which validates every ancestor the kernel will
/// visit, with the same ownership and sticky-bit rules.
#[cfg(unix)]
fn ensure_events_db_parent_trusted(db_path: &Path) -> anyhow::Result<()> {
    let parent = absolutize(db_path);
    let parent = parent.parent().filter(|p| !p.as_os_str().is_empty());
    match parent {
        Some(dir) => crate::daemon::ensure_socket_dir_is_trusted(dir).map_err(|e| {
            anyhow::anyhow!("refusing to serve events from an untrusted directory: {e}")
        }),
        None => Ok(()),
    }
}

/// Create the events database file owner-only if it does not exist yet.
/// The 0600 socket and peer-uid admission bound who can *talk to* the
/// daemon; they bound nothing if the database file itself is readable by
/// other local users, so the daemon creates it 0600 before SQLite ever
/// opens it (SQLite would otherwise create it at the process umask).
#[cfg(unix)]
fn ensure_events_db_owner_only(db_path: &Path) -> anyhow::Result<()> {
    use std::os::unix::fs::OpenOptionsExt;
    refuse_events_db_symlinks(db_path)?;
    if let Some(parent) = db_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    // After creation so a fresh parent can be validated; a directory this
    // process just created in a trusted ancestor passes by construction.
    ensure_events_db_parent_trusted(db_path)?;
    match std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(db_path)
    {
        // A zero-byte file is a valid empty SQLite database.
        Ok(_created) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Ok(()),
        Err(e) => Err(anyhow::anyhow!(
            "refusing to serve events: cannot create {} owner-only: {e}",
            db_path.display()
        )),
    }
}

/// Tighten the events database and its SQLite sidecars to owner-only.
/// Fail closed, same contract as the socket chmod: a daemon that cannot
/// keep its database owner-only must not serve it.
///
/// PRECONDITION: no SQLite connection to `db_path` may be open in this
/// process. This function opens and closes a descriptor on the database and
/// on each sidecar, and POSIX advisory locks are per process and per inode,
/// released by the close of ANY descriptor for the inode (fcntl(2)): called
/// on a live database it silently drops the SHARED lock SQLite keeps in WAL
/// mode and the `-shm` DMS lock, while the connection believes it still
/// holds them. Both callers run it before their open; keep it that way. The
/// post-open check that opens nothing is `verify_events_db_owner_only_unopened`.
#[cfg(unix)]
fn harden_events_db_sidecars(db_path: &Path) -> anyhow::Result<EventsDbIdentities> {
    use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
    let mut identities = [None; 3];
    for (index, path) in events_db_targets(db_path).into_iter().enumerate() {
        // Pin the inode before touching it: `O_NOFOLLOW` makes the open
        // itself refuse a symlink at the final component, and the chmod is
        // then issued on the returned handle (fchmod), so no path re-lookup
        // exists between validation and the permission change for a swapped
        // entry to exploit. A path-based lstat-then-chmod pair here would
        // re-open the exact race it is defending against.
        let file = match std::fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_NOFOLLOW)
            .open(&path)
        {
            Ok(file) => file,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
            Err(e) => {
                anyhow::bail!(
                    "refusing to serve events: cannot open {} without following symlinks: \
                     {e}. The events database and its sidecars must be regular files.",
                    path.display()
                )
            }
        };
        // The open succeeds on a directory too; fstat the handle (no path
        // re-lookup) so a directory at the path is refused, never chmod'ed.
        let metadata = file.metadata()?;
        if !metadata.file_type().is_file() {
            anyhow::bail!(
                "refusing to serve events: {} is not a regular file. The events \
                 database and its sidecars must be regular files.",
                path.display()
            );
        }
        file.set_permissions(std::fs::Permissions::from_mode(0o600))
            .map_err(|e| {
                anyhow::anyhow!(
                    "refusing to serve events: cannot chmod 0600 {}: {e}. The events \
                     database and its sidecars must be owner-only.",
                    path.display()
                )
            })?;
        // The same descriptor supplied validation and fchmod; record its
        // identity before closing it, never by re-looking up the path.
        identities[index] = Some(EventsFileIdentity::from_metadata(&metadata));
    }
    Ok(identities)
}

/// Check, after SQLite has opened the database, that it and its sidecars are
/// owner-only regular files WITHOUT opening any of them: `lstat` takes no
/// descriptor, so it cannot release the advisory locks the open connections
/// hold (see the precondition on `harden_events_db_sidecars`). Sidecars
/// SQLite creates inherit the database file's mode, so a failure here means
/// something else changed the file set; refuse to serve rather than tighten
/// through a path-based chmod and its lookup race. Present paths must retain
/// their pre-open device/inode when one was observed. A missing main database
/// is refused: serving an unlinked database would detach writes from its path.
/// Sidecars may legitimately be absent or newly created by SQLite, so an absent
/// pre- or post-observation does not assert identity continuity for that sidecar.
///
/// This is a two-observation check, not a pin of SQLite's own descriptors. It
/// cannot detect swaps restored between observations, inode reuse, or changes
/// after the final lstat. Even a legitimate sidecar delete/recreate is refused
/// if both observations see different identities; a later startup can retry
/// with a fresh snapshot. Trusted parent directories remain required. Unix only.
#[cfg(unix)]
fn verify_events_db_owner_only_unopened(
    db_path: &Path,
    before: &EventsDbIdentities,
) -> anyhow::Result<()> {
    use std::os::unix::fs::PermissionsExt;
    for (index, path) in events_db_targets(db_path).into_iter().enumerate() {
        let metadata = match std::fs::symlink_metadata(&path) {
            Ok(metadata) => metadata,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound && index != 0 => continue,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => anyhow::bail!(
                "refusing to serve events: main database {} disappeared after SQLite open; \
                 refusing to serve an unlinked database",
                path.display()
            ),
            Err(e) => {
                anyhow::bail!(
                    "refusing to serve events: cannot stat {}: {e}",
                    path.display()
                )
            }
        };
        if !metadata.file_type().is_file() {
            anyhow::bail!(
                "refusing to serve events: {} is not a regular file. The events database \
                 and its sidecars must be regular files.",
                path.display()
            );
        }
        let mode = metadata.permissions().mode() & 0o777;
        if mode & 0o077 != 0 {
            anyhow::bail!(
                "refusing to serve events: {} is mode {mode:03o}, not owner-only. The events \
                 database and its sidecars must be owner-only.",
                path.display()
            );
        }
        if before[index]
            .is_some_and(|identity| identity != EventsFileIdentity::from_metadata(&metadata))
        {
            anyhow::bail!(
                "refusing to serve events: {} changed identity between pre-open hardening \
                 and post-open verification",
                path.display()
            );
        }
    }
    Ok(())
}

/// Supervise the events daemon from the main daemon process: probe the
/// socket periodically and (re)spawn the daemon subcommand when unreachable.
///
/// The spawned command contract is fixed here once: the current executable
/// re-invoked as `events-daemon --db <db> --socket <socket>` with the resolved
/// WAL ceiling bytes and source — the subcommand the kernel binary registers
/// for [`run_events_daemon`]. The child holds the per-socket advisory lock,
/// so a probe/spawn race resolves to one survivor.
///
/// Lifecycle: the loop observes the process-wide daemon shutdown token, so
/// `drain()` never waits on it forever, and it retains the handle of the
/// child it spawned — reaping it with `try_wait` on every probe (no zombie
/// accumulation during a persistent startup failure) and never stacking a
/// second spawn on a still-live child. On shutdown, a child this supervisor
/// spawned is killed and reaped; a pre-existing events daemon it never
/// spawned is left alone.
///
/// The reachability probe uses the peer-verified connect: a socket answered
/// by a foreign-uid process is treated as UNREACHABLE (and logged loudly),
/// so a pre-bound spoof socket triggers a real-daemon spawn instead of being
/// reported healthy.
///
/// This standalone entry resolves its environment once before supervision.
/// Hosts with an opened main backend pass its resolved policies through
/// [`supervise_events_daemon_with_policies`].
#[cfg(unix)]
pub async fn supervise_events_daemon(db_path: PathBuf, socket_path: PathBuf) {
    match standalone_daemon_policies(&db_path) {
        Ok((wal_ceiling, disk_guard, volume_lock_dir)) => {
            supervise_events_daemon_with_policies(
                db_path,
                socket_path,
                wal_ceiling,
                disk_guard,
                volume_lock_dir,
            )
            .await;
        }
        Err(error) => {
            tracing::warn!(%error, "invalid events daemon policy; events supervisor not started");
        }
    }
}

/// Supervise using the main pool's captured writer policies and lock directory.
#[cfg(unix)]
pub async fn supervise_events_daemon_with_policies(
    db_path: PathBuf,
    socket_path: PathBuf,
    wal_ceiling: WalCeilingPolicy,
    disk_guard: khive_db::EffectiveDiskGuardConfig,
    volume_lock_dir: PathBuf,
) {
    if let Err(error) = disk_guard.validate() {
        tracing::warn!(%error, "invalid disk policy; events supervisor not started");
        return;
    }
    if let Err(error) = wal_ceiling.validate_static(true, true, false) {
        tracing::warn!(error = %error, "invalid WAL ceiling; events supervisor not started");
        return;
    }
    const PROBE_INTERVAL: Duration = Duration::from_secs(15);
    let shutdown = crate::daemon::daemon_shutdown_token();
    let mut child: Option<std::process::Child> = None;
    let mut respawns: u64 = 0;
    loop {
        // Reap first: a child that exited (crashed, lost the advisory lock
        // race, refused an untrusted directory) must not linger as a zombie,
        // and clearing the slot is what re-arms the spawn below.
        if let Some(c) = child.as_mut() {
            match c.try_wait() {
                Ok(Some(status)) => {
                    tracing::info!(%status, "events daemon child exited");
                    child = None;
                }
                Ok(None) => {}
                Err(error) => {
                    tracing::warn!(error = %error, "cannot poll events daemon child; dropping handle");
                    child = None;
                }
            }
        }

        let reachable = match connect_verified(&socket_path).await {
            Ok(_stream) => true,
            Err(error) if error.kind() == std::io::ErrorKind::PermissionDenied => {
                tracing::warn!(
                    socket = %socket_path.display(),
                    error = %error,
                    "events socket answered by a foreign uid; treating as unreachable"
                );
                false
            }
            Err(_) => false,
        };
        if !reachable && child.is_none() {
            match std::env::current_exe() {
                Ok(exe) => {
                    let spawned = events_daemon_command(
                        &exe,
                        &db_path,
                        &socket_path,
                        wal_ceiling,
                        disk_guard,
                        &volume_lock_dir,
                    )
                    .spawn();
                    match spawned {
                        Ok(spawned_child) => {
                            respawns += 1;
                            tracing::info!(
                                pid = spawned_child.id(),
                                respawns,
                                socket = %socket_path.display(),
                                "spawned events daemon"
                            );
                            child = Some(spawned_child);
                        }
                        Err(error) => {
                            tracing::warn!(error = %error, "failed to spawn events daemon");
                        }
                    }
                }
                Err(error) => {
                    tracing::warn!(error = %error, "cannot resolve current executable for events daemon spawn");
                }
            }
        }
        tokio::select! {
            _ = shutdown.cancelled() => break,
            _ = tokio::time::sleep(PROBE_INTERVAL) => {}
        }
    }
    if let Some(mut c) = child.take() {
        // Our child, our cleanup: the events daemon holds no volatile queue
        // state (SQLite is the durability), and the next daemon host's
        // supervisor respawns it.
        let _ = c.kill();
        let _ = c.wait();
        tracing::info!("events daemon child stopped with supervisor shutdown");
    }
}

#[cfg(unix)]
fn events_daemon_command(
    executable: &Path,
    db_path: &Path,
    socket_path: &Path,
    wal_ceiling: WalCeilingPolicy,
    disk_guard: khive_db::EffectiveDiskGuardConfig,
    volume_lock_dir: &Path,
) -> std::process::Command {
    let source = match wal_ceiling.source {
        khive_db::WalCeilingSource::BackendField => "backend_field",
        khive_db::WalCeilingSource::Environment => "environment",
        khive_db::WalCeilingSource::Default => "default",
    };
    let mut command = std::process::Command::new(executable);
    command
        .arg("events-daemon")
        .arg("--db")
        .arg(db_path)
        .arg("--socket")
        .arg(socket_path)
        .arg("--wal-ceiling-bytes")
        .arg(wal_ceiling.bytes.to_string())
        .arg("--wal-ceiling-source")
        .arg(source)
        .arg("--disk-reserve-bytes")
        .arg(disk_guard.reserve_bytes.to_string())
        .arg("--disk-guard-deadline-ms")
        .arg(disk_guard.guard_deadline_ms.to_string())
        .arg("--disk-reserve-source")
        .arg(disk_guard.reserve_source.as_str())
        .arg("--disk-deadline-source")
        .arg(disk_guard.deadline_source.as_str())
        .arg("--disk-legacy-environment-present")
        .arg(disk_guard.legacy_environment_present.to_string())
        .arg("--volume-lock-dir")
        .arg(volume_lock_dir)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    command
}

/// Serve the events daemon loop on `socket_path`, owning `db_path`.
///
/// Binds the socket (removing a stale path first), then accepts connections
/// for the process lifetime. Each connection is served sequentially:
/// same-uid admission, then a read-frame → dispatch → write-frame loop until
/// the peer disconnects. All storage goes through `SqlEventStore` on a
/// backend opened read-write against `db_path`; the events schema is ensured
/// once at boot.
///
/// Bind-path trust mirrors the main daemon socket: the socket directory must
/// pass the same ownership/mode/swap-resistance validation, and the bound
/// socket entry is chmod'd 0600 fail-closed. Pathname reachability is not
/// identity — clients additionally verify the peer uid on every connect —
/// but a hardened bind path is what keeps the *bind* itself out of another
/// user's hands.
///
/// This standalone entry resolves its environment once before opening the
/// daemon. Hosts with resolved policies use [`run_events_daemon_with_policies`].
#[cfg(unix)]
pub async fn run_events_daemon(db_path: &Path, socket_path: &Path) -> anyhow::Result<()> {
    let (wal_ceiling, disk_guard, volume_lock_dir) = standalone_daemon_policies(db_path)?;
    run_events_daemon_with_policies(
        db_path,
        socket_path,
        wal_ceiling,
        disk_guard,
        volume_lock_dir,
    )
    .await
}

/// Serve using the exact policies inherited from the opened main backend.
#[cfg(unix)]
pub async fn run_events_daemon_with_policies(
    db_path: &Path,
    socket_path: &Path,
    wal_ceiling: WalCeilingPolicy,
    disk_guard: khive_db::EffectiveDiskGuardConfig,
    volume_lock_dir: PathBuf,
) -> anyhow::Result<()> {
    disk_guard.validate()?;
    wal_ceiling
        .validate_static(true, true, false)
        .map_err(crate::error::RuntimeError::from)?;
    // The subcommand's `--db`/`--socket` arrive from argv and may be
    // relative; anchor them before anything derives a parent from them.
    let db_path = &absolutize(db_path);
    let socket_path = &absolutize(socket_path);
    validate_events_socket_path(socket_path)?;
    // Directory trust comes FIRST: the lock guard below opens and chmods a
    // path in this directory, and validating only before the later bind
    // would let those operations run in a directory another user controls.
    if let Some(parent) = socket_path.parent() {
        std::fs::create_dir_all(parent)?;
        crate::daemon::ensure_socket_dir_is_trusted(parent)?;
    }
    let _guard = match acquire_events_daemon_guard_outcome(socket_path) {
        EventsDaemonGuardAcquisition::Held(guard) => guard,
        refusal => {
            tracing::info!(
                socket = %socket_path.display(),
                reason = ?refusal,
                "events daemon lock unavailable; exiting"
            );
            return Ok(());
        }
    };
    ensure_events_db_owner_only(db_path)?;
    // Tighten a pre-existing database and any `-wal`/`-shm` an earlier
    // process left behind BEFORE SQLite opens the database. The order is
    // load-bearing: hardening opens and closes its own descriptor on each of
    // these files, and POSIX advisory locks are per process and per inode,
    // released by the close of ANY descriptor for the inode (fcntl(2)). Run
    // after the open, it silently dropped the SHARED lock SQLite keeps on the
    // database in WAL mode and the shared lock on the `-shm` DMS byte, so the
    // next external connection to close (a backup tool, an inspection shell)
    // took itself for the last connection, checkpointed, and unlinked the
    // sidecars underneath this daemon, which kept writing to the unlinked
    // inodes. Sidecars SQLite creates from here on inherit the database
    // file's mode; the check after the open below opens nothing.
    let before_open = harden_events_db_sidecars(db_path)?;
    let backend = Arc::new(
        StorageBackend::sqlite_with_max_readers_and_policies(
            db_path,
            None,
            wal_ceiling,
            disk_guard,
            volume_lock_dir,
        )
        .map_err(crate::error::RuntimeError::from)?,
    );
    // Ensure the schema once, loudly, before accepting traffic.
    backend.events()?;
    verify_events_db_owner_only_unopened(db_path, &before_open)?;

    if socket_path.exists() {
        std::fs::remove_file(socket_path)?;
    }
    let listener = UnixListener::bind(socket_path)?;
    {
        use std::os::unix::fs::PermissionsExt;
        // Fail closed, same contract as the main daemon socket: if the entry
        // cannot be made owner-only, drop the listener and remove it rather
        // than serve a world-reachable socket the design never covered.
        if let Err(e) =
            std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600))
        {
            drop(listener);
            let _ = std::fs::remove_file(socket_path);
            anyhow::bail!(
                "refusing to serve events: cannot chmod 0600 {}: {e}. The events socket must \
                 be owner-only.",
                socket_path.display()
            );
        }
    }
    let daemon_euid = unsafe { libc::geteuid() };
    // Per-namespace store cache: `events_for_namespace` takes a writer-lane
    // checkout and re-runs the schema DDL on every call, so paying it once
    // per namespace instead of once per request keeps the writer lane for
    // actual writes. The namespace is client-supplied, so the cache is
    // bounded (`MAX_CACHED_NAMESPACE_STORES`) rather than trusted small.
    let stores: NamespaceStores = Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
    let connections = Arc::new(tokio::sync::Semaphore::new(MAX_EVENTS_CONNECTIONS));
    let frame_budget = Arc::new(tokio::sync::Semaphore::new(MAX_INFLIGHT_REQUEST_BYTES));
    tracing::info!(
        socket = %socket_path.display(),
        db = %db_path.display(),
        wal_ceiling_configured_bytes = wal_ceiling.bytes,
        wal_ceiling_effective_bytes = wal_ceiling.effective_bytes(backend.is_read_only()),
        wal_ceiling_source = ?wal_ceiling.source,
        "events daemon listening"
    );

    loop {
        let (stream, _addr) = match listener.accept().await {
            Ok(pair) => pair,
            Err(error) => {
                tracing::warn!(error = %error, "events daemon accept failed");
                continue;
            }
        };
        match crate::daemon::peer_uid(&stream) {
            Ok(uid) if crate::daemon::uid_is_permitted(uid, daemon_euid) => {}
            Ok(uid) => {
                tracing::warn!(peer_uid = uid, "events daemon rejected foreign-uid peer");
                continue;
            }
            Err(error) => {
                tracing::warn!(error = %error, "events daemon could not read peer credentials");
                continue;
            }
        }
        let permit = match Arc::clone(&connections).try_acquire_owned() {
            Ok(permit) => permit,
            Err(_) => {
                // At the cap: drop the stream (peer sees EOF and retries via
                // its own reconnect path) instead of queueing unbounded work.
                tracing::warn!(
                    cap = MAX_EVENTS_CONNECTIONS,
                    "events daemon at connection cap; dropping new connection"
                );
                continue;
            }
        };
        let backend = Arc::clone(&backend);
        let stores = Arc::clone(&stores);
        let frame_budget = Arc::clone(&frame_budget);
        crate::daemon::spawn_named_tracked_task("events_connection", async move {
            serve_events_conn(stream, backend, stores, frame_budget).await;
            drop(permit);
        });
    }
}

#[cfg(unix)]
#[path = "events_split_policy_entries.rs"]
mod policy_entries;
#[cfg(unix)]
use policy_entries::standalone_daemon_policies;
#[cfg(unix)]
pub use policy_entries::{
    run_events_daemon_with_wal_ceiling, supervise_events_daemon_with_wal_ceiling,
};

#[cfg(all(test, unix))]
#[path = "events_wal_policy_tests.rs"]
mod wal_policy_tests;

/// Read one length-prefixed request frame, admitting the body buffer against
/// the shared byte budget before allocating it. The returned permit holds
/// the admitted bytes for as long as the buffer may be alive — the caller
/// drops it after the response is written. The per-frame cap is checked
/// before admission, so a single frame is always satisfiable against the
/// full budget (`MAX_INFLIGHT_REQUEST_BYTES >= MAX_FRAME_BYTES`) and a
/// waiter can never deadlock on an impossible request.
#[cfg(unix)]
async fn read_frame_budgeted(
    stream: &mut UnixStream,
    budget: &Arc<tokio::sync::Semaphore>,
) -> std::io::Result<(Vec<u8>, tokio::sync::OwnedSemaphorePermit)> {
    use tokio::io::AsyncReadExt;
    let mut len_buf = [0u8; 4];
    stream.read_exact(&mut len_buf).await?;
    let len = u32::from_be_bytes(len_buf) as usize;
    if len > crate::daemon::MAX_FRAME_BYTES {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "daemon frame of {len} bytes exceeds {} cap",
                crate::daemon::MAX_FRAME_BYTES
            ),
        ));
    }
    let permit = Arc::clone(budget)
        .acquire_many_owned(len as u32)
        .await
        .map_err(|_| std::io::Error::other("frame budget closed"))?;
    let mut buf = vec![0u8; len];
    stream.read_exact(&mut buf).await?;
    Ok((buf, permit))
}

#[cfg(unix)]
type NamespaceStores =
    Arc<std::sync::Mutex<std::collections::HashMap<String, Arc<dyn EventStore>>>>;

/// The cached per-namespace store, constructing (and caching) it on first
/// use. Construction failures are not cached — the next request retries.
///
/// The cache key is the trimmed namespace, matching the backend's own
/// normalization, so spellings that resolve to one store share one handle.
/// The map is bounded: at `MAX_CACHED_NAMESPACE_STORES` entries an arbitrary
/// existing entry is evicted to admit the new namespace, so the map never
/// grows past the cap and no namespace is permanently condemned to
/// per-request store rebuilds. Keys reaching this cache have already passed
/// `Namespace` validation at dispatch (charset + length bound), so cap ×
/// bounded key is the worst-case retained memory.
#[cfg(unix)]
fn namespace_store(
    backend: &StorageBackend,
    stores: &NamespaceStores,
    namespace: &str,
) -> Result<Arc<dyn EventStore>, khive_db::SqliteError> {
    namespace_store_with_cap(backend, stores, namespace, MAX_CACHED_NAMESPACE_STORES)
}

#[cfg(unix)]
fn namespace_store_with_cap(
    backend: &StorageBackend,
    stores: &NamespaceStores,
    namespace: &str,
    cap: usize,
) -> Result<Arc<dyn EventStore>, khive_db::SqliteError> {
    let key = namespace.trim();
    if let Some(store) = stores
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(key)
    {
        return Ok(Arc::clone(store));
    }
    let store = backend.events_for_namespace(namespace)?;
    let mut map = stores
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    if map.len() >= cap && !map.contains_key(key) {
        // At the cap, evict an arbitrary entry instead of refusing
        // admission: stores are cheap pool handles, so eviction costs one
        // rebuild on the victim's next request, while refusing admission
        // would make every request beyond the cap rebuild its store and
        // rerun schema init on the SQLite writer forever. Keys are
        // validated `Namespace` values (bounded length), so the map's
        // worst-case memory is cap × small key + cap handles.
        if let Some(victim) = map.keys().next().cloned() {
            map.remove(&victim);
        }
    }
    map.insert(key.to_string(), Arc::clone(&store));
    Ok(store)
}

#[cfg(unix)]
async fn serve_events_conn(
    mut stream: UnixStream,
    backend: Arc<StorageBackend>,
    stores: NamespaceStores,
    frame_budget: Arc<tokio::sync::Semaphore>,
) {
    loop {
        // Deadline on the whole frame read — budget admission included: a
        // peer that opens a connection and stalls, or that cannot be
        // admitted because other connections hold the byte budget, is
        // closed instead of holding this task and its descriptor
        // indefinitely.
        let (payload, budget_permit) = match tokio::time::timeout(
            CONN_IO_TIMEOUT,
            read_frame_budgeted(&mut stream, &frame_budget),
        )
        .await
        {
            Ok(Ok(pair)) => pair,
            // Includes clean EOF on peer disconnect, and the expired deadline.
            Ok(Err(_)) | Err(_) => return,
        };
        let response = match serde_json::from_slice::<EventsRequest>(&payload) {
            Ok(request) => dispatch_events_request(request, &backend, &stores).await,
            Err(error) => EventsResponse::Error {
                message: format!("events daemon could not parse request frame: {error}"),
                retryable: false,
                writer_task_failure: None,
            },
        };
        let bytes = match serde_json::to_vec(&response) {
            Ok(bytes) => bytes,
            Err(error) => {
                tracing::error!(error = %error, "events daemon response serialization failed");
                return;
            }
        };
        let bytes = if bytes.len() > crate::daemon::MAX_FRAME_BYTES {
            // A page can obey the row cap yet exceed the framing cap. Reply
            // with a small, non-retryable refusal instead of closing the
            // socket and making a healthy daemon look unreachable.
            let refusal = EventsResponse::Error {
                message: format!(
                    "response_frame_size_limit: {} response bytes exceed the {}-byte events IPC frame cap; request a narrower page",
                    bytes.len(),
                    crate::daemon::MAX_FRAME_BYTES
                ),
                retryable: false,
                writer_task_failure: None,
            };
            match serde_json::to_vec(&refusal) {
                Ok(bytes) => bytes,
                Err(error) => {
                    tracing::error!(error = %error, "events daemon frame-size refusal serialization failed");
                    return;
                }
            }
        } else {
            bytes
        };
        // Same deadline on the response write: a peer that stops reading
        // would otherwise park this task in a full socket buffer.
        match tokio::time::timeout(CONN_IO_TIMEOUT, write_frame(&mut stream, &bytes)).await {
            Ok(Ok(())) => {}
            Ok(Err(_)) | Err(_) => return,
        }
        // The request buffer is long dropped; release its byte budget only
        // now, after the whole request lifecycle, so admission tracks live
        // work rather than just live buffers.
        drop(budget_permit);
    }
}

#[cfg(unix)]
async fn dispatch_events_request(
    request: EventsRequest,
    backend: &StorageBackend,
    stores: &NamespaceStores,
) -> EventsResponse {
    if request.protocol_version() != EVENTS_PROTOCOL_VERSION {
        return EventsResponse::Error {
            message: format!(
                "events protocol version mismatch: daemon speaks {}, client sent {}",
                EVENTS_PROTOCOL_VERSION,
                request.protocol_version()
            ),
            retryable: false,
            writer_task_failure: None,
        };
    }
    // The wire namespace is an unrestricted client-supplied String until this
    // point. Validate it as a real `Namespace` (charset plus the 256-byte
    // length bound) before it can become a cache key, a store, or a database
    // row — without this, near-frame-sized strings are attacker-controlled
    // retained memory in a process that lives for months.
    if let Err(error) = khive_types::Namespace::parse(request.namespace().trim()) {
        return EventsResponse::Error {
            message: format!("events request namespace rejected: {error}"),
            retryable: false,
            writer_task_failure: None,
        };
    }
    let store = match namespace_store(backend, stores, request.namespace()) {
        Ok(store) => store,
        Err(error) => {
            return EventsResponse::Error {
                message: format!("events store unavailable: {error}"),
                retryable: true,
                writer_task_failure: None,
            };
        }
    };
    match request {
        EventsRequest::AppendEvents { events, .. } => match store.append_events(events).await {
            Ok(summary) => EventsResponse::Appended { summary },
            Err(error) => storage_error_response(&error),
        },
        EventsRequest::AppendEventsIdempotent { events, .. } => {
            match store.append_events_idempotent(events).await {
                Ok(result) => EventsResponse::Idempotent { result },
                Err(error) => storage_error_response(&error),
            }
        }
        EventsRequest::GetEvent { id, .. } => match store.get_event(id).await {
            Ok(event) => EventsResponse::Event { event },
            Err(error) => storage_error_response(&error),
        },
        EventsRequest::QueryEvents { filter, page, .. } => {
            if page.limit > MAX_QUERY_EVENTS_PAGE_ROWS {
                return EventsResponse::Error {
                    message: format!(
                        "events query page limit {} exceeds the daemon cap of {} rows; \
                         request narrower pages",
                        page.limit, MAX_QUERY_EVENTS_PAGE_ROWS
                    ),
                    retryable: false,
                    writer_task_failure: None,
                };
            }
            match store.query_events(filter, page).await {
                Ok(page) => EventsResponse::Pageful { page },
                Err(error) => storage_error_response(&error),
            }
        }
        EventsRequest::QueryEventPage { query, .. } => {
            if let Err(error) = crate::event_page::validate_page_query(&query) {
                return storage_error_response(&error);
            }
            match store.query_event_page(query).await {
                Ok(window) => EventsResponse::EventPageWindow { window },
                Err(error) => storage_error_response(&error),
            }
        }
        EventsRequest::CountEvents { filter, .. } => match store.count_events(filter).await {
            Ok(count) => EventsResponse::Count { count },
            Err(error) => storage_error_response(&error),
        },
    }
}

#[cfg(unix)]
fn storage_error_response(error: &StorageError) -> EventsResponse {
    let (message, writer_task_failure) = match error {
        StorageError::WriterTaskRequestFailed {
            request_state,
            source,
        } => (
            source.to_string(),
            Some(WireWriterTaskFailure::RequestFailed {
                request_state: (*request_state).into(),
            }),
        ),
        StorageError::WriterTaskTerminated { request_state } => (
            error.to_string(),
            Some(WireWriterTaskFailure::TaskTerminated {
                request_state: (*request_state).into(),
            }),
        ),
        _ => (error.to_string(), None),
    };
    EventsResponse::Error {
        message,
        // Defer to the storage layer's own transience classifier rather than
        // re-enumerating variants here: a hand-rolled subset silently turns
        // transient writer contention (`WriterTaskBusy`, `Transaction`) into
        // a terminal error on the client side of the socket.
        retryable: error.is_retryable(),
        writer_task_failure,
    }
}

// ---------------------------------------------------------------------------
// Client side
// ---------------------------------------------------------------------------

/// Connect to the events socket and verify who answered. Pathname
/// reachability is not identity: any process that can write the directory can
/// pre-bind the path. The kernel-reported peer uid is the one identity the
/// far side cannot choose, so every client connect — round-trips, the
/// forwarder, the supervisor probe — refuses a socket answered by a foreign
/// uid before a single frame is written.
#[cfg(unix)]
async fn connect_verified(socket_path: &Path) -> std::io::Result<UnixStream> {
    let stream = UnixStream::connect(socket_path).await?;
    // SAFETY: `geteuid` is always successful and takes no arguments.
    let own_euid = unsafe { libc::geteuid() } as u32;
    let peer = crate::daemon::peer_uid(&stream)?;
    if !crate::daemon::uid_is_permitted(peer, own_euid) {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            format!(
                "events socket {} answered by uid {peer}, not this process's uid {own_euid}; \
                 refusing to exchange event frames with an unowned daemon",
                socket_path.display()
            ),
        ));
    }
    Ok(stream)
}

/// Counters describing the fire-and-forget lane's degradation. Zero drops is
/// the healthy state; any non-zero `dropped_batches` means the loss-tolerant
/// contract was exercised and says so.
#[cfg(unix)]
#[derive(Debug, Clone, Copy, Serialize)]
pub struct EventsForwardingMetrics {
    pub forwarded_batches: u64,
    pub forwarded_events: u64,
    pub dropped_batches: u64,
    pub dropped_events: u64,
    /// Serialized request bytes reserved by queued and in-flight batches.
    pub queued_bytes: usize,
}

#[cfg(unix)]
#[derive(Debug, Default)]
struct ForwardingCounters {
    forwarded_batches: AtomicU64,
    forwarded_events: AtomicU64,
    dropped_batches: AtomicU64,
    dropped_events: AtomicU64,
    queued_bytes: AtomicUsize,
}

/// A reservation lives with the batch until delivery or a counted drop.
/// Dropping a forwarder mid-delivery also returns its byte budget.
#[cfg(unix)]
#[derive(Debug)]
struct AppendByteReservation {
    counters: Arc<ForwardingCounters>,
    bytes: usize,
}

#[cfg(unix)]
impl Drop for AppendByteReservation {
    fn drop(&mut self) {
        self.counters
            .queued_bytes
            .fetch_sub(self.bytes, Ordering::AcqRel);
    }
}

#[cfg(unix)]
#[derive(Debug)]
struct QueuedAppend {
    request: EventsRequest,
    count: u64,
    _reservation: AppendByteReservation,
}

#[cfg(all(test, unix))]
impl QueuedAppend {
    fn unmetered(namespace: &str, events: Vec<Event>, counters: Arc<ForwardingCounters>) -> Self {
        let count = events.len() as u64;
        Self {
            request: EventsRequest::AppendEvents {
                protocol_version: EVENTS_PROTOCOL_VERSION,
                namespace: namespace.to_string(),
                events,
            },
            count,
            _reservation: AppendByteReservation { counters, bytes: 0 },
        }
    }
}

/// Measure the actual wire request without retaining a second, potentially
/// huge serialized copy of the caller's batch. Serde stops at the frame cap.
#[cfg(unix)]
#[derive(Default)]
struct BoundedFrameCounter {
    bytes: usize,
    exceeded: bool,
}

#[cfg(unix)]
impl std::io::Write for BoundedFrameCounter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let next = self.bytes.saturating_add(buf.len());
        if next > crate::daemon::MAX_FRAME_BYTES {
            self.exceeded = true;
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "events append request exceeds IPC frame cap",
            ));
        }
        self.bytes = next;
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[cfg(unix)]
fn reserve_append_bytes(
    counters: &Arc<ForwardingCounters>,
    bytes: usize,
    budget: usize,
) -> Option<AppendByteReservation> {
    let mut used = counters.queued_bytes.load(Ordering::Acquire);
    loop {
        let next = used.checked_add(bytes)?;
        if next > budget {
            return None;
        }
        match counters.queued_bytes.compare_exchange_weak(
            used,
            next,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(_) => {
                return Some(AppendByteReservation {
                    counters: Arc::clone(counters),
                    bytes,
                });
            }
            Err(observed) => used = observed,
        }
    }
}

/// One per domain process: the connection to the events daemon plus the
/// bounded fire-and-forget append queue.
///
/// Synchronous round-trips each own a fresh connection: there is no shared
/// request connection and no lock in front of one, so concurrent reads and
/// audit flushes never queue behind a single stalled call, and the round-trip
/// timeout bounds each caller's whole attempt.
#[cfg(unix)]
pub struct EventsSplitClient {
    socket_path: PathBuf,
    append_tx: tokio::sync::mpsc::Sender<QueuedAppend>,
    append_queue_byte_budget: usize,
    counters: Arc<ForwardingCounters>,
    /// Flipped by the forwarder while the daemon is unreachable so the drop
    /// log fires once per outage, not once per batch.
    outage_logged: Arc<AtomicBool>,
    /// In-memory validator backing `preflight_event` without I/O.
    preflight_store: Arc<dyn EventStore>,
}

#[cfg(unix)]
impl std::fmt::Debug for EventsSplitClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EventsSplitClient")
            .field("socket_path", &self.socket_path)
            .finish_non_exhaustive()
    }
}

#[cfg(unix)]
impl EventsSplitClient {
    /// Build the client and spawn its background forwarder.
    pub fn new(socket_path: PathBuf) -> crate::error::RuntimeResult<Arc<Self>> {
        Self::new_with_queue_depth(socket_path, DEFAULT_APPEND_QUEUE_BATCHES)
    }

    /// [`Self::new`] with an explicit fire-and-forget queue bound. Tests use a
    /// tiny depth to exercise the overflow drop arm deterministically.
    pub fn new_with_queue_depth(
        socket_path: PathBuf,
        queue_depth: usize,
    ) -> crate::error::RuntimeResult<Arc<Self>> {
        Self::new_with_queue_depth_and_delivery_timeout(socket_path, queue_depth, REQUEST_TIMEOUT)
    }

    /// [`Self::new_with_queue_depth`] with an explicit per-batch delivery
    /// timeout, so tests can prove the forwarder abandons a hung peer without
    /// waiting out the production clock.
    fn new_with_queue_depth_and_delivery_timeout(
        socket_path: PathBuf,
        queue_depth: usize,
        delivery_timeout: Duration,
    ) -> crate::error::RuntimeResult<Arc<Self>> {
        Self::new_with_limits_and_delivery_timeout(
            socket_path,
            queue_depth,
            DEFAULT_APPEND_QUEUE_BYTES,
            delivery_timeout,
        )
    }

    fn new_with_limits_and_delivery_timeout(
        socket_path: PathBuf,
        queue_depth: usize,
        byte_budget: usize,
        delivery_timeout: Duration,
    ) -> crate::error::RuntimeResult<Arc<Self>> {
        validate_events_socket_path(&socket_path)?;
        let preflight_backend = StorageBackend::memory()?;
        let preflight_store = preflight_backend.events()?;
        // The in-memory backend must outlive the store handle; the store holds
        // the pool Arc internally, so dropping the backend wrapper here is fine.

        let (append_tx, append_rx) = tokio::sync::mpsc::channel::<QueuedAppend>(queue_depth.max(1));
        let counters = Arc::new(ForwardingCounters::default());
        let outage_logged = Arc::new(AtomicBool::new(false));

        let client = Arc::new(Self {
            socket_path: socket_path.clone(),
            append_tx,
            append_queue_byte_budget: byte_budget,
            counters: Arc::clone(&counters),
            outage_logged: Arc::clone(&outage_logged),
            preflight_store,
        });

        crate::daemon::spawn_named_tracked_task(
            "events_forwarder",
            run_forwarder(
                socket_path,
                append_rx,
                counters,
                outage_logged,
                delivery_timeout,
                crate::daemon::daemon_shutdown_token(),
            ),
        );
        Ok(client)
    }

    /// Snapshot of the fire-and-forget lane's health.
    pub fn metrics(&self) -> EventsForwardingMetrics {
        EventsForwardingMetrics {
            forwarded_batches: self.counters.forwarded_batches.load(Ordering::Relaxed),
            forwarded_events: self.counters.forwarded_events.load(Ordering::Relaxed),
            dropped_batches: self.counters.dropped_batches.load(Ordering::Relaxed),
            dropped_events: self.counters.dropped_events.load(Ordering::Relaxed),
            queued_bytes: self.counters.queued_bytes.load(Ordering::Acquire),
        }
    }

    /// Enqueue a batch on the fire-and-forget lane. Never blocks; a full
    /// queue is a counted, logged drop.
    fn enqueue(&self, namespace: &str, events: Vec<Event>) {
        let count = events.len() as u64;
        let request = EventsRequest::AppendEvents {
            protocol_version: EVENTS_PROTOCOL_VERSION,
            namespace: namespace.to_string(),
            events,
        };
        let mut frame_size = BoundedFrameCounter::default();
        if let Err(error) = serde_json::to_writer(&mut frame_size, &request) {
            self.count_append_drop(
                count,
                if frame_size.exceeded {
                    "frame cap"
                } else {
                    "serialization"
                },
            );
            tracing::warn!(error = %error, "events append batch could not fit a wire frame");
            return;
        }
        let Some(reservation) = reserve_append_bytes(
            &self.counters,
            frame_size.bytes,
            self.append_queue_byte_budget,
        ) else {
            self.count_append_drop(count, "queue byte budget");
            return;
        };
        let batch = QueuedAppend {
            request,
            count,
            _reservation: reservation,
        };
        match self.append_tx.try_send(batch) {
            Ok(()) => {}
            Err(_) => {
                // The rejected batch drops here and releases its reservation.
                self.count_append_drop(count, "queue batch limit");
            }
        }
    }

    fn count_append_drop(&self, count: u64, reason: &'static str) {
        self.counters
            .dropped_batches
            .fetch_add(1, Ordering::Relaxed);
        self.counters
            .dropped_events
            .fetch_add(count, Ordering::Relaxed);
        if !self.outage_logged.swap(true, Ordering::Relaxed) {
            tracing::warn!(
                dropped_events = count,
                reason,
                "events append queue rejected loss-tolerant batch"
            );
        }
    }

    /// One synchronous framed round-trip with a bounded timeout, on its own
    /// fresh connection. No connection is shared between concurrent callers,
    /// so no caller ever waits on another's stall, and `REQUEST_TIMEOUT`
    /// bounds the whole attempt — connect, peer verification, write, read.
    async fn round_trip(&self, request: &EventsRequest) -> StorageResult<EventsResponse> {
        let op = "events daemon round-trip";
        let payload = serde_json::to_vec(request).map_err(|error| StorageError::Serialization {
            capability: khive_storage::StorageCapability::Events,
            message: format!("events request serialization failed: {error}"),
        })?;

        let attempt = async {
            let mut stream = connect_verified(&self.socket_path)
                .await
                .map_err(|error| ("connect", error))?;
            write_frame(&mut stream, &payload)
                .await
                .map_err(|error| ("write", error))?;
            read_frame(&mut stream)
                .await
                .map_err(|error| ("read", error))
        };
        let bytes = match tokio::time::timeout(REQUEST_TIMEOUT, attempt).await {
            Ok(Ok(bytes)) => bytes,
            Ok(Err(("read", error))) => {
                return Err(StorageError::Serialization {
                    capability: khive_storage::StorageCapability::Events,
                    message: format!(
                        "events daemon closed or broke the response after connection at {}: {error}",
                        self.socket_path.display()
                    ),
                });
            }
            Ok(Err((stage, error))) => {
                return Err(StorageError::Pool {
                    operation: op.into(),
                    message: format!(
                        "events daemon {stage} failed at {}: {error}",
                        self.socket_path.display()
                    ),
                });
            }
            Err(_elapsed) => {
                return Err(StorageError::Timeout {
                    operation: op.into(),
                });
            }
        };

        serde_json::from_slice::<EventsResponse>(&bytes).map_err(|error| {
            StorageError::Serialization {
                capability: khive_storage::StorageCapability::Events,
                message: format!("events response deserialization failed: {error}"),
            }
        })
    }
}

/// Drain every batch currently sitting in the fire-and-forget queue,
/// counting each as a dropped batch/events and logging one summary line
/// (never one line per batch — a full queue at shutdown is exactly the
/// bursty case a per-batch log would flood). Non-blocking: `try_recv` only
/// consumes what is already queued, so it terminates as soon as the queue
/// (temporarily) empties even though the sender half is still live.
#[cfg(unix)]
fn drain_dropped_queue(
    rx: &mut tokio::sync::mpsc::Receiver<QueuedAppend>,
    counters: &ForwardingCounters,
) {
    let mut dropped_batches = 0u64;
    let mut dropped_events = 0u64;
    while let Ok(batch) = rx.try_recv() {
        dropped_batches += 1;
        dropped_events += batch.count;
        // `batch` drops its byte reservation at the end of this iteration.
    }
    if dropped_batches > 0 {
        counters
            .dropped_batches
            .fetch_add(dropped_batches, Ordering::Relaxed);
        counters
            .dropped_events
            .fetch_add(dropped_events, Ordering::Relaxed);
        tracing::warn!(
            dropped_batches,
            dropped_events,
            "events forwarder shutting down; dropping queued loss-tolerant batches"
        );
    }
}

/// The background fire-and-forget forwarder: drains the bounded queue into
/// framed appends on its own connection, reconnecting with backoff. A batch
/// that cannot be delivered is dropped and counted — never retried, never
/// blocking the queue behind it.
#[cfg(unix)]
async fn run_forwarder(
    socket_path: PathBuf,
    mut rx: tokio::sync::mpsc::Receiver<QueuedAppend>,
    counters: Arc<ForwardingCounters>,
    outage_logged: Arc<AtomicBool>,
    delivery_timeout: Duration,
    shutdown: tokio_util::sync::CancellationToken,
) {
    // The client lives in a process-global registry, so its sender is never
    // dropped and `rx.recv()` alone would keep this tracked task alive
    // through daemon shutdown, forcing `drain()` to its full timeout.
    // Observe the shutdown token directly: queued batches at shutdown are a
    // counted drop, exactly the lane's loss-tolerant contract — enforced by
    // draining and counting `rx` below on every shutdown exit, not just
    // implied by the comment.
    let mut conn: Option<UnixStream> = None;
    loop {
        let batch = tokio::select! {
            _ = shutdown.cancelled() => {
                drain_dropped_queue(&mut rx, &counters);
                break;
            },
            received = rx.recv() => match received {
                Some(batch) => batch,
                None => break,
            },
        };
        let count = batch.count;
        let payload = match serde_json::to_vec(&batch.request) {
            Ok(payload) => payload,
            Err(error) => {
                counters.dropped_batches.fetch_add(1, Ordering::Relaxed);
                counters.dropped_events.fetch_add(count, Ordering::Relaxed);
                tracing::error!(error = %error, "events forwarder serialization failed; batch dropped");
                continue;
            }
        };

        // The delivery itself must stay both cancellable and bounded: a
        // connected but non-responding daemon would otherwise park this
        // tracked task inside write_frame/read_frame, beyond the reach of the
        // recv-side shutdown select — and daemon drain would wait its full
        // timeout on it. Shutdown mid-delivery abandons the batch (the
        // lane's loss-tolerant contract); a timeout poisons the connection,
        // since the peer may answer the abandoned frame later.
        let delivered = tokio::select! {
            _ = shutdown.cancelled() => {
                counters.dropped_batches.fetch_add(1, Ordering::Relaxed);
                counters.dropped_events.fetch_add(count, Ordering::Relaxed);
                tracing::warn!(
                    dropped_events = count,
                    "events forwarder shutting down mid-delivery; in-flight batch dropped"
                );
                drain_dropped_queue(&mut rx, &counters);
                break;
            },
            outcome = tokio::time::timeout(
                delivery_timeout,
                deliver_batch(&socket_path, &mut conn, &payload),
            ) => match outcome {
                Ok(delivered) => delivered,
                Err(_elapsed) => {
                    conn = None;
                    false
                }
            },
        };
        if delivered {
            counters.forwarded_batches.fetch_add(1, Ordering::Relaxed);
            counters
                .forwarded_events
                .fetch_add(count, Ordering::Relaxed);
            if outage_logged.swap(false, Ordering::Relaxed) {
                tracing::info!("events daemon reachable again; forwarding resumed");
            }
        } else {
            counters.dropped_batches.fetch_add(1, Ordering::Relaxed);
            counters.dropped_events.fetch_add(count, Ordering::Relaxed);
            if !outage_logged.swap(true, Ordering::Relaxed) {
                tracing::warn!(
                    socket = %socket_path.display(),
                    "events daemon unreachable; dropping loss-tolerant events until it returns"
                );
            }
            tokio::select! {
                _ = shutdown.cancelled() => {
                    drain_dropped_queue(&mut rx, &counters);
                    break;
                },
                _ = tokio::time::sleep(FORWARDER_BACKOFF) => {}
            }
        }
    }
}

/// Try to deliver one framed append over the forwarder connection,
/// (re)connecting at most once. Returns whether the daemon acknowledged.
/// Connections are peer-verified: a socket answered by a foreign uid is a
/// failed connect, never a delivery target.
#[cfg(unix)]
async fn deliver_batch(socket_path: &Path, conn: &mut Option<UnixStream>, payload: &[u8]) -> bool {
    for _attempt in 0..2u8 {
        if conn.is_none() {
            match connect_verified(socket_path).await {
                Ok(stream) => *conn = Some(stream),
                Err(_) => return false,
            }
        }
        let stream = conn.as_mut().expect("connection populated above");
        let ok = async {
            write_frame(stream, payload).await?;
            let bytes = read_frame(stream).await?;
            std::io::Result::Ok(bytes)
        }
        .await;
        match ok {
            Ok(bytes) => {
                return !matches!(
                    serde_json::from_slice::<EventsResponse>(&bytes),
                    Ok(EventsResponse::Error { .. }) | Err(_)
                );
            }
            Err(_) => {
                // Stale connection (daemon restarted): drop it and retry once
                // with a fresh connect; a second failure is a real outage.
                *conn = None;
            }
        }
    }
    false
}

// ---------------------------------------------------------------------------
// The per-namespace EventStore handle
// ---------------------------------------------------------------------------

/// [`EventStore`] implementation the runtime hands out when the events split
/// runs in daemon mode. Appends are fire-and-forget through the client's
/// bounded queue; the ADR-133 idempotent lane and all reads are synchronous
/// round-trips to the events daemon.
#[cfg(unix)]
#[derive(Debug)]
pub struct ForwardingEventStore {
    namespace: String,
    client: Arc<EventsSplitClient>,
}

#[cfg(unix)]
impl ForwardingEventStore {
    pub fn new(namespace: impl Into<String>, client: Arc<EventsSplitClient>) -> Self {
        Self {
            namespace: namespace.into(),
            client,
        }
    }

    fn unexpected(&self, op: &'static str, response: EventsResponse) -> StorageError {
        match response {
            EventsResponse::Error {
                message,
                retryable,
                writer_task_failure,
            } => {
                if let Some(failure) = writer_task_failure {
                    match failure {
                        WireWriterTaskFailure::RequestFailed { request_state } => {
                            let source = if retryable {
                                StorageError::Pool {
                                    operation: op.into(),
                                    message,
                                }
                            } else {
                                StorageError::InvalidInput {
                                    capability: khive_storage::StorageCapability::Events,
                                    operation: op.into(),
                                    message,
                                }
                            };
                            StorageError::WriterTaskRequestFailed {
                                request_state: request_state.into(),
                                source: Box::new(source),
                            }
                        }
                        WireWriterTaskFailure::TaskTerminated { request_state } => {
                            StorageError::WriterTaskTerminated {
                                request_state: request_state.into(),
                            }
                        }
                    }
                } else if retryable {
                    StorageError::Pool {
                        operation: op.into(),
                        message,
                    }
                } else {
                    StorageError::InvalidInput {
                        capability: khive_storage::StorageCapability::Events,
                        operation: op.into(),
                        message,
                    }
                }
            }
            other => StorageError::Serialization {
                capability: khive_storage::StorageCapability::Events,
                message: format!("events daemon returned mismatched response for {op}: {other:?}"),
            },
        }
    }
}

#[cfg(unix)]
#[async_trait]
impl EventStore for ForwardingEventStore {
    async fn append_event(&self, event: Event) -> StorageResult<()> {
        self.client.enqueue(&self.namespace, vec![event]);
        Ok(())
    }

    async fn append_events(&self, events: Vec<Event>) -> StorageResult<BatchWriteSummary> {
        let attempted = events.len() as u64;
        self.client.enqueue(&self.namespace, events);
        // Fire-and-forget: the hand-off succeeded or was counted as a drop;
        // either way the caller's contract is "accepted for forwarding".
        Ok(BatchWriteSummary {
            attempted,
            affected: attempted,
            ..BatchWriteSummary::default()
        })
    }

    async fn get_event(&self, id: Uuid) -> StorageResult<Option<Event>> {
        let request = EventsRequest::GetEvent {
            protocol_version: EVENTS_PROTOCOL_VERSION,
            namespace: self.namespace.clone(),
            id,
        };
        match self.client.round_trip(&request).await? {
            EventsResponse::Event { event } => Ok(event),
            other => Err(self.unexpected("get_event", other)),
        }
    }

    async fn query_events(
        &self,
        filter: EventFilter,
        page: PageRequest,
    ) -> StorageResult<Page<Event>> {
        let request = EventsRequest::QueryEvents {
            protocol_version: EVENTS_PROTOCOL_VERSION,
            namespace: self.namespace.clone(),
            filter,
            page,
        };
        match self.client.round_trip(&request).await? {
            EventsResponse::Pageful { page } => Ok(page),
            other => Err(self.unexpected("query_events", other)),
        }
    }

    async fn count_events(&self, filter: EventFilter) -> StorageResult<u64> {
        let request = EventsRequest::CountEvents {
            protocol_version: EVENTS_PROTOCOL_VERSION,
            namespace: self.namespace.clone(),
            filter,
        };
        match self.client.round_trip(&request).await? {
            EventsResponse::Count { count } => Ok(count),
            other => Err(self.unexpected("count_events", other)),
        }
    }

    async fn query_event_page(&self, query: EventPageQuery) -> StorageResult<EventPageWindow> {
        crate::event_page::validate_page_query(&query)?;
        let request = EventsRequest::QueryEventPage {
            protocol_version: EVENTS_PROTOCOL_VERSION,
            namespace: self.namespace.clone(),
            query: query.clone(),
        };
        match self.client.round_trip(&request).await? {
            EventsResponse::EventPageWindow { window } => {
                crate::event_page::validate_window(&query, Some(&self.namespace), &window)?;
                Ok(window)
            }
            error @ EventsResponse::Error { .. } => Err(self.unexpected("query_event_page", error)),
            _ => Err(crate::event_page::page_error(
                "events page response kind mismatch",
            )),
        }
    }

    fn preflight_event(&self, event: &Event) -> StorageResult<()> {
        // Same validation code path as the daemon-side store, zero I/O.
        self.client.preflight_store.preflight_event(event)
    }

    async fn append_events_idempotent(
        &self,
        events: Vec<Event>,
    ) -> StorageResult<IdempotentEventBatchResult> {
        let request = EventsRequest::AppendEventsIdempotent {
            protocol_version: EVENTS_PROTOCOL_VERSION,
            namespace: self.namespace.clone(),
            events,
        };
        match self.client.round_trip(&request).await? {
            EventsResponse::Idempotent { result } => Ok(result),
            other => Err(self.unexpected("append_events_idempotent", other)),
        }
    }

    fn supports_idempotent_audit_batch(&self) -> bool {
        true
    }
}

/// The store the runtime hands out when the events split is configured:
/// routes by APPEND CLASS rather than moving the whole event plane.
///
/// - The ADR-133 idempotent audit-batch lane — the measured bulk of event
///   write volume (verb-dispatch audit plus the config-lock rows that ride
///   the same flusher) — goes to the events lane (the events database, forwarded or
///   direct).
/// - Plain appends stay on the legacy store, because the legacy `events`
///   table has raw-SQL consumers whose correctness depends on finding those
///   rows there: the schedule drain's creator-provenance fence, the kg
///   projection worker's guarded event INSERT (transactional with main-db
///   state), and GraphQuery's cross-substrate UNION. Those events are
///   low-volume domain facts; the split's contention relief does not need
///   them moved, and moving them breaks the consumers by construction.
/// - Reads merge both stores so trait-level consumers
///   (`brain.event_counts`, event getters) observe one event plane.
pub struct SplitEventStore {
    legacy: Arc<dyn EventStore>,
    lane: Arc<dyn EventStore>,
}

impl std::fmt::Debug for SplitEventStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SplitEventStore").finish_non_exhaustive()
    }
}

impl SplitEventStore {
    /// Bound on `offset + limit` for a merged `query_events` window. Offset
    /// pagination over two stores materializes the whole prefix in memory
    /// (see `query_events`), so an unbounded offset would let a single
    /// request buffer both stores wholesale. The bound comfortably admits
    /// the largest legitimate bounded window in the tree
    /// (`brain.event_counts`' 50k page); deep walks page with a `before`
    /// cursor at `offset: 0`, which never grows the materialized prefix.
    pub const MAX_MERGED_WINDOW_ROWS: u64 = 100_000;

    pub fn new(legacy: Arc<dyn EventStore>, lane: Arc<dyn EventStore>) -> Self {
        Self { legacy, lane }
    }
}

#[async_trait]
impl EventStore for SplitEventStore {
    async fn append_event(&self, event: Event) -> StorageResult<()> {
        self.legacy.append_event(event).await
    }

    async fn append_events(&self, events: Vec<Event>) -> StorageResult<BatchWriteSummary> {
        self.legacy.append_events(events).await
    }

    async fn get_event(&self, id: Uuid) -> StorageResult<Option<Event>> {
        // Domain events (legacy) are the likelier and cheaper hit; fall back
        // to the lane for audit-batch rows.
        if let Some(event) = self.legacy.get_event(id).await? {
            return Ok(Some(event));
        }
        self.lane.get_event(id).await
    }

    async fn query_events(
        &self,
        filter: EventFilter,
        page: PageRequest,
    ) -> StorageResult<Page<Event>> {
        // Offset pagination cannot be split across two stores: fetch each
        // store's prefix covering the requested window, merge in the stores'
        // shared order (created_at DESC, id DESC), then window in memory.
        // Cost is O(offset + limit) rows materialized from each store — the
        // floor for offset semantics over two sources, since the split point
        // is unknowable without both prefixes. The sort below is a single
        // merge pass in practice (std's stable sort is adaptive on the
        // concatenation of two sorted runs). That materialization is why the
        // window is bounded below: without a bound, one authenticated
        // request with a pathological offset would make both stores buffer
        // and sort every matching row. Deep walks page with a `before`
        // cursor (strict `created_at <` bound in `EventFilter`) at
        // `offset: 0`, which stays inside the bound at any depth.
        let window = page.offset.saturating_add(u64::from(page.limit));
        if window > Self::MAX_MERGED_WINDOW_ROWS {
            return Err(StorageError::InvalidInput {
                capability: khive_storage::StorageCapability::Events,
                operation: "query_events".into(),
                message: format!(
                    "offset+limit ({window}) exceeds the merged event plane's window bound \
                     of {}; page deep windows with a `before` cursor at offset 0, or narrow \
                     the filter",
                    Self::MAX_MERGED_WINDOW_ROWS
                ),
            });
        }
        let prefix = PageRequest {
            offset: 0,
            limit: window.min(u64::from(u32::MAX)) as u32,
        };
        let legacy = self
            .legacy
            .query_events(filter.clone(), prefix.clone())
            .await?;
        let lane = self.lane.query_events(filter, prefix).await?;
        let total = match (legacy.total, lane.total) {
            (Some(a), Some(b)) => Some(a + b),
            _ => None,
        };
        let mut items = legacy.items;
        items.extend(lane.items);
        items.sort_by(|a, b| {
            b.created_at
                .cmp(&a.created_at)
                .then_with(|| b.id.cmp(&a.id))
        });
        let items = items
            .into_iter()
            .skip(page.offset as usize)
            .take(page.limit as usize)
            .collect();
        Ok(Page { items, total })
    }

    async fn count_events(&self, filter: EventFilter) -> StorageResult<u64> {
        let legacy = self.legacy.count_events(filter.clone()).await?;
        let lane = self.lane.count_events(filter).await?;
        Ok(legacy + lane)
    }

    async fn query_event_page(&self, query: EventPageQuery) -> StorageResult<EventPageWindow> {
        crate::event_page::split_page(self.legacy.as_ref(), self.lane.as_ref(), query).await
    }

    fn preflight_event(&self, event: &Event) -> StorageResult<()> {
        // Validation is store-independent; the lane's implementation is the
        // local zero-I/O validator in forwarding mode.
        self.lane.preflight_event(event)
    }

    async fn append_events_idempotent(
        &self,
        events: Vec<Event>,
    ) -> StorageResult<IdempotentEventBatchResult> {
        // A retried batch may have landed — fully or partially — on the
        // legacy store before the split cutover, and merged reads stay
        // duplicate-free only while an id lives in exactly one store. Probe
        // the legacy store for the batch's ids and route resident rows back
        // through the legacy store's own idempotent machinery, which compares
        // every persisted column without re-inserting; only genuinely new
        // rows reach the lane. Without the probe, a legacy-resident id would
        // be inserted a second time into the lane and every merged query and
        // count would double-count it.
        if events.is_empty() {
            return self.lane.append_events_idempotent(events).await;
        }
        let ids: Vec<Uuid> = events.iter().map(|event| event.id).collect();
        let probe_limit = u32::try_from(ids.len()).map_err(|_| StorageError::InvalidInput {
            capability: khive_storage::StorageCapability::Events,
            operation: "append_events_idempotent".into(),
            message: format!(
                "batch of {} rows exceeds the legacy probe window",
                ids.len()
            ),
        })?;
        let existing = self
            .legacy
            .query_events(
                EventFilter {
                    ids,
                    ..EventFilter::default()
                },
                PageRequest {
                    offset: 0,
                    limit: probe_limit,
                },
            )
            .await?;
        let legacy_resident: std::collections::HashSet<Uuid> =
            existing.items.iter().map(|event| event.id).collect();
        if legacy_resident.is_empty() {
            return self.lane.append_events_idempotent(events).await;
        }
        let mut legacy_rows = Vec::new();
        let mut lane_rows = Vec::new();
        let mut routed_to_legacy = Vec::with_capacity(events.len());
        for event in events {
            if legacy_resident.contains(&event.id) {
                routed_to_legacy.push(true);
                legacy_rows.push(event);
            } else {
                routed_to_legacy.push(false);
                lane_rows.push(event);
            }
        }
        let legacy_expected = legacy_rows.len();
        let lane_expected = lane_rows.len();
        let legacy_result = self.legacy.append_events_idempotent(legacy_rows).await?;
        let lane_result = if lane_expected == 0 {
            IdempotentEventBatchResult { rows: Vec::new() }
        } else {
            self.lane.append_events_idempotent(lane_rows).await?
        };
        if legacy_result.rows.len() != legacy_expected || lane_result.rows.len() != lane_expected {
            return Err(StorageError::Driver {
                capability: khive_storage::StorageCapability::Events,
                operation: "append_events_idempotent".into(),
                source: format!(
                    "idempotent sub-batch result length mismatch: legacy {}/{}, lane {}/{}",
                    legacy_result.rows.len(),
                    legacy_expected,
                    lane_result.rows.len(),
                    lane_expected
                )
                .into(),
            });
        }
        let mut legacy_iter = legacy_result.rows.into_iter();
        let mut lane_iter = lane_result.rows.into_iter();
        let rows = routed_to_legacy
            .into_iter()
            .map(|to_legacy| {
                if to_legacy {
                    legacy_iter.next().expect("length checked above")
                } else {
                    lane_iter.next().expect("length checked above")
                }
            })
            .collect();
        Ok(IdempotentEventBatchResult { rows })
    }

    fn supports_idempotent_audit_batch(&self) -> bool {
        // The legacy-resident probe above routes retried rows through the
        // legacy store's idempotent path, so the split supports the audit
        // batch only when BOTH stores do.
        self.lane.supports_idempotent_audit_batch() && self.legacy.supports_idempotent_audit_batch()
    }
}

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

    #[test]
    fn fixture_registry_cleanup_preserves_other_roots() {
        let live_dir = tempfile::tempdir().unwrap();
        let _live_guard = TestRegistryGuard::new(live_dir.path());
        let live_path = live_dir.path().join("events.db");
        let live_backend = direct_backend_for(&live_path).unwrap();

        let finished_dir = tempfile::tempdir().unwrap();
        let finished_backend = {
            let _finished_guard = TestRegistryGuard::new(finished_dir.path());
            let backend = direct_backend_for(&finished_dir.path().join("events.db")).unwrap();
            let weak = Arc::downgrade(&backend);
            drop(backend);
            assert!(
                weak.upgrade().is_some(),
                "registry retains the live fixture"
            );
            weak
        };

        assert!(
            finished_backend.upgrade().is_none(),
            "FD_FIXTURE_REGISTRY_RELEASED"
        );
        let same_live_backend = direct_backend_for(&live_path).unwrap();
        assert!(
            Arc::ptr_eq(&live_backend, &same_live_backend),
            "FD_FIXTURE_OTHER_ROOT_RETAINED"
        );
    }

    #[cfg(unix)]
    mod target_filter_tests {
        include!("events_split_target_tests.rs");
    }

    // The full daemon/forwarding test suite for this module lands with the
    // final slice of this series; these tests cover the naming and
    // classification contracts the module itself defines.

    include!("events_sidecar_path_tests.rs");

    #[cfg(unix)]
    #[test]
    fn deep_symlink_chains_within_the_kernel_bound_derive_the_target_sidecar() {
        // Linux resolves up to 40 links per lookup; a 35-hop dangling chain
        // therefore opens fine, so it must ALSO derive the target's sidecar
        // — a resolver stopping short would split audit records between the
        // alias and target spellings of one database.
        let dir = tempfile::tempdir().unwrap();
        let real = dir.path().join("real.db");
        let mut prev = real.clone();
        for i in 0..35 {
            let link = dir.path().join(format!("hop{i}.db"));
            std::os::unix::fs::symlink(&prev, &link).unwrap();
            prev = link;
        }
        assert_eq!(
            events_db_path_beside(&prev),
            events_db_path_beside(&real),
            "a 35-hop dangling chain must derive the target's sidecar"
        );
        // Control: an unrelated dangling path still derives its own name.
        assert_ne!(
            events_db_path_beside(&dir.path().join("unrelated.db")),
            events_db_path_beside(&real)
        );
    }

    include!("events_sidecar_hardening_tests.rs");

    #[cfg(unix)]
    fn write_owner_only_test_file(path: &Path) {
        use std::os::unix::fs::PermissionsExt;
        std::fs::write(path, b"").unwrap();
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn unopened_check_refuses_same_mode_regular_file_replacement() {
        // Must fail with the old mode-only verifier: every replacement remains
        // a regular 0600 file. Creating it before rename guarantees a different
        // live inode, without relying on inode reuse after unlink or on timing.
        for target_index in 0..3 {
            let dir = tempfile::tempdir().unwrap();
            let db = dir.path().join("events.db");
            let targets = events_db_targets(&db);
            for path in &targets {
                write_owner_only_test_file(path);
            }
            let before_open = harden_events_db_sidecars(&db).unwrap();
            let replacement = dir.path().join("replacement");
            write_owner_only_test_file(&replacement);
            let replacement_id = EventsFileIdentity::from_metadata(
                &std::fs::symlink_metadata(&replacement).unwrap(),
            );
            assert_ne!(before_open[target_index], Some(replacement_id));
            // Keep a real SQLite connection open across the pathname change.
            // Do not run SQL against deliberately replaced files afterward.
            let _connection = rusqlite::Connection::open(&db).unwrap();
            verify_events_db_owner_only_unopened(&db, &before_open).unwrap();
            std::fs::rename(&replacement, &targets[target_index]).unwrap();
            let error = verify_events_db_owner_only_unopened(&db, &before_open)
                .unwrap_err()
                .to_string();
            assert!(error.contains("changed identity"), "{error}");
            assert!(
                error.contains(&targets[target_index].display().to_string()),
                "{error}"
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn unopened_check_accepts_sidecars_missing_at_check_time() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("events.db");
        let targets = events_db_targets(&db);
        for path in &targets {
            write_owner_only_test_file(path);
        }
        let before_open = harden_events_db_sidecars(&db).unwrap();
        let _connection = rusqlite::Connection::open(&db).unwrap();
        for path in targets.iter().skip(1) {
            std::fs::remove_file(path).unwrap();
            verify_events_db_owner_only_unopened(&db, &before_open)
                .expect("SQLite sidecars may disappear without losing the main database");
        }
    }

    #[cfg(unix)]
    #[test]
    fn unopened_check_refuses_main_database_removed_after_sqlite_open() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("events.db");
        ensure_events_db_owner_only(&db).unwrap();
        let before_open = harden_events_db_sidecars(&db).unwrap();
        let backend = StorageBackend::sqlite_for_test(&db).unwrap();
        backend.events().unwrap();
        verify_events_db_owner_only_unopened(&db, &before_open).unwrap();
        std::fs::remove_file(&db).unwrap();
        // Must fail with the old NotFound-for-every-target behavior. The live
        // connection can still name an unlinked inode; it must not be served.
        let error = verify_events_db_owner_only_unopened(&db, &before_open)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("main database") && error.contains("disappeared"),
            "{error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn unopened_check_accepts_fresh_sqlite_sidecars_and_unchanged_main() {
        let dir = tempfile::tempdir().unwrap();
        let db = dir.path().join("new.events.db");
        assert!(!db.exists());
        ensure_events_db_owner_only(&db).unwrap();
        let before_open = harden_events_db_sidecars(&db).unwrap();
        assert!(before_open[0].is_some());
        assert_eq!(&before_open[1..], &[None, None]);
        let backend = StorageBackend::sqlite_for_test(&db).unwrap();
        backend.events().unwrap();
        for path in events_db_targets(&db).iter().skip(1) {
            assert!(path.exists(), "SQLite creates {}", path.display());
        }
        verify_events_db_owner_only_unopened(&db, &before_open)
            .expect("new SQLite sidecars have no pre-open identity to contradict");
    }

    #[test]
    fn socket_derives_beside_the_sidecar() {
        let db = events_db_path_beside(Path::new("/data/khive.db"));
        let socket = events_socket_path_beside(&db);
        assert!(socket.ends_with("khive.db.events.sock"), "got {socket:?}");
    }

    #[test]
    fn bare_relative_main_db_yields_an_absolute_sidecar() {
        // A bare file name has `Some("")` for a parent; every downstream
        // consumer (lock parenting, socket-dir trust validation) needs a
        // real directory, so the sidecar path must come back anchored.
        let path = events_db_path_beside(Path::new("khive.db"));
        assert!(path.is_absolute(), "got relative {path:?}");
        assert!(path.ends_with("khive.db.events.db"), "got {path:?}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn over_cap_query_page_limit_is_refused_before_materialization() {
        // `PageRequest.limit` arrives client-controlled off the wire; the
        // daemon must refuse an over-cap page with a typed, actionable error
        // instead of materializing and serializing it — and must never
        // silently clamp, or the short page reads as end-of-data.
        let backend = Arc::new(StorageBackend::memory().unwrap());
        let stores: NamespaceStores =
            Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let request = |limit: u32| EventsRequest::QueryEvents {
            protocol_version: EVENTS_PROTOCOL_VERSION,
            namespace: "local".to_string(),
            filter: EventFilter::default(),
            page: PageRequest { offset: 0, limit },
        };
        let refused =
            dispatch_events_request(request(MAX_QUERY_EVENTS_PAGE_ROWS + 1), &backend, &stores)
                .await;
        match refused {
            EventsResponse::Error {
                message,
                retryable,
                writer_task_failure,
            } => {
                assert!(
                    message.contains(&MAX_QUERY_EVENTS_PAGE_ROWS.to_string()),
                    "refusal must name the cap: {message}"
                );
                assert!(!retryable, "an over-cap page is not transient");
                assert!(writer_task_failure.is_none());
            }
            other => panic!("over-cap query must be refused, got {other:?}"),
        }
        // Control: a request AT the cap passes admission and reaches the
        // store — an empty page, not a refusal.
        let at_cap =
            dispatch_events_request(request(MAX_QUERY_EVENTS_PAGE_ROWS), &backend, &stores).await;
        assert!(
            matches!(at_cap, EventsResponse::Pageful { .. }),
            "at-cap query must reach the store, got {at_cap:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn side_effects_unknown_state_crosses_the_wire_as_terminal_failure() {
        let response = storage_error_response(&StorageError::WriterTaskTerminated {
            request_state: khive_storage::WriterTaskRequestState::SideEffectsUnknown,
        });
        assert!(
            matches!(
                response,
                EventsResponse::Error {
                    writer_task_failure: Some(WireWriterTaskFailure::TaskTerminated {
                        request_state: WireWriterTaskState::SideEffectsUnknown,
                    }),
                    ..
                }
            ),
            "an unknown-commit-state termination must carry its state on the wire"
        );
        // Any other refusal must NOT carry a writer state.
        let busy = storage_error_response(&StorageError::WriterTaskBusy { timeout_ms: 5 });
        assert!(matches!(
            busy,
            EventsResponse::Error {
                writer_task_failure: None,
                ..
            }
        ));
    }

    #[cfg(unix)]
    #[test]
    fn proven_rollback_crosses_the_wire_without_claiming_task_termination() {
        let response = storage_error_response(&StorageError::WriterTaskRequestFailed {
            request_state: khive_storage::WriterTaskRequestState::TransactionRolledBack,
            source: Box::new(StorageError::Pool {
                operation: "writer_task_commit".into(),
                message: "commit refused".into(),
            }),
        });
        assert!(matches!(
            response,
            EventsResponse::Error {
                writer_task_failure: Some(WireWriterTaskFailure::RequestFailed {
                    request_state: WireWriterTaskState::TransactionRolledBack,
                }),
                ..
            }
        ));
    }

    #[test]
    fn error_frames_without_writer_failure_still_parse() {
        // `writer_task_failure` is `#[serde(default)]`: an Error frame for a
        // non-writer failure (parse error, version refusal) omits it and the
        // client must read `None`, not fail the parse.
        let bytes = br#"{"kind":"error","message":"boom","retryable":true}"#;
        let parsed: EventsResponse = serde_json::from_slice(bytes).expect("stateless frame parses");
        assert!(matches!(
            parsed,
            EventsResponse::Error {
                retryable: true,
                writer_task_failure: None,
                ..
            }
        ));
    }

    fn split_retry_event(verb: &str) -> Event {
        Event::new(
            "test",
            verb,
            khive_types::EventKind::RecallExecuted,
            khive_types::SubstrateKind::Note,
            "agent:test",
        )
    }

    fn store_pair(dir: &Path) -> (Arc<dyn EventStore>, Arc<dyn EventStore>) {
        let legacy = direct_backend_for(&dir.join("legacy.db"))
            .expect("legacy backend")
            .events_for_namespace("test")
            .expect("legacy store");
        let lane = direct_backend_for(&dir.join("lane.db"))
            .expect("lane backend")
            .events_for_namespace("test")
            .expect("lane store");
        (legacy, lane)
    }

    /// A retried audit batch whose first attempt landed on the legacy store
    /// before the cutover must be answered by the legacy store's comparison,
    /// never re-inserted into the lane — otherwise merged reads and counts
    /// double-count the id.
    #[tokio::test]
    async fn idempotent_retry_of_legacy_resident_rows_does_not_duplicate() {
        use khive_storage::event::EventAppendDisposition;

        let dir = tempfile::tempdir().unwrap();
        let _registry_guard = TestRegistryGuard::new(dir.path());
        let (legacy, lane) = store_pair(dir.path());

        let resident = split_retry_event("recall");
        legacy
            .append_events_idempotent(vec![resident.clone()])
            .await
            .expect("pre-cutover landing");

        let split = SplitEventStore::new(Arc::clone(&legacy), Arc::clone(&lane));
        let fresh = split_retry_event("search");
        let result = split
            .append_events_idempotent(vec![resident.clone(), fresh.clone()])
            .await
            .expect("mixed retry batch");
        assert_eq!(
            result.rows,
            vec![
                EventAppendDisposition::AlreadyPresentIdentical,
                EventAppendDisposition::Inserted,
            ],
            "input order must be preserved across the two sub-batches"
        );
        assert_eq!(
            lane.count_events(EventFilter::default()).await.unwrap(),
            1,
            "the legacy-resident row must not reach the lane"
        );
        assert_eq!(
            split.count_events(EventFilter::default()).await.unwrap(),
            2,
            "merged count must not double-count the retried id"
        );

        // A conflicting retry of the resident row reports the conflict from
        // the legacy comparison and inserts nowhere.
        let mut mutated = resident.clone();
        mutated.verb = "other".to_string();
        let conflict = split
            .append_events_idempotent(vec![mutated])
            .await
            .expect("conflicting retry");
        assert_eq!(
            conflict.rows,
            vec![EventAppendDisposition::IdentityConflict]
        );
        assert_eq!(split.count_events(EventFilter::default()).await.unwrap(), 2);
    }

    /// The merged plane refuses to materialize an unbounded offset prefix;
    /// the refusal names the cursor remedy, and the bound itself is usable.
    #[tokio::test]
    async fn merged_offset_window_is_bounded() {
        let dir = tempfile::tempdir().unwrap();
        let _registry_guard = TestRegistryGuard::new(dir.path());
        let (legacy, lane) = store_pair(dir.path());
        let split = SplitEventStore::new(legacy, lane);

        let err = split
            .query_events(
                EventFilter::default(),
                PageRequest {
                    offset: SplitEventStore::MAX_MERGED_WINDOW_ROWS,
                    limit: 1,
                },
            )
            .await
            .expect_err("a window past the bound must be refused");
        assert!(
            matches!(err, StorageError::InvalidInput { .. }),
            "got {err:?}"
        );
        assert!(
            err.to_string().contains("before"),
            "the refusal must name the cursor remedy: {err}"
        );

        let at_bound = split
            .query_events(
                EventFilter::default(),
                PageRequest {
                    offset: SplitEventStore::MAX_MERGED_WINDOW_ROWS - 1,
                    limit: 1,
                },
            )
            .await
            .expect("a window at the bound is admitted");
        assert!(at_bound.items.is_empty());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn stateless_non_retryable_error_maps_terminal_not_writer_terminated() {
        // The terminal arm of the client mapping, pinned deliberately: an
        // Error frame with `retryable: false` and NO `writer_task_failure` is
        // a non-writer failure (parse error, version refusal) and must map
        // to terminal `InvalidInput` — never to `WriterTaskTerminated`
        // (there is no state to reconstruct) and never to the retryable
        // `Pool` arm (retrying a version refusal cannot succeed).
        let client = EventsSplitClient::new(std::path::PathBuf::from("/tmp/never-bound.sock"))
            .expect("client builds");
        let store = ForwardingEventStore::new("test", client);
        let bytes = br#"{"kind":"error","message":"refused","retryable":false}"#;
        let parsed: EventsResponse = serde_json::from_slice(bytes).expect("frame parses");
        assert!(matches!(
            store.unexpected("append", parsed),
            StorageError::InvalidInput { .. }
        ));
        // Control: the same non-retryable frame WITH a writer state must
        // take the reconstruction arm instead — proving the terminal arm
        // above is selected by the field's absence, not by `retryable`.
        let with_state = br#"{"kind":"error","message":"died","retryable":false,"writer_task_failure":{"kind":"task_terminated","request_state":"side_effects_unknown"}}"#;
        let parsed: EventsResponse =
            serde_json::from_slice(with_state).expect("stateful frame parses");
        assert!(matches!(
            store.unexpected("append", parsed),
            StorageError::WriterTaskTerminated { .. }
        ));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn writer_task_states_cross_the_wire_verbatim() {
        // The ADR-133 retry classifier decides per-state, so every
        // WriterTaskTerminated state must survive server → wire → client
        // reconstruction exactly. Before this field existed, NotStarted and
        // TransactionRolledBack crossed as a generic non-retryable refusal
        // and came back as terminal InvalidInput — a broken retry contract.
        use khive_storage::WriterTaskRequestState as S;
        let dir = tempfile::tempdir().unwrap();
        let client =
            EventsSplitClient::new(dir.path().join("never-bound.sock")).expect("client builds");
        let store = ForwardingEventStore::new("test", client);
        for state in [
            S::NotStarted,
            S::TransactionRolledBack,
            S::SideEffectsUnknown,
        ] {
            let response = storage_error_response(&StorageError::WriterTaskTerminated {
                request_state: state,
            });
            // Round-trip through serde like the socket does.
            let bytes = serde_json::to_vec(&response).unwrap();
            let parsed: EventsResponse = serde_json::from_slice(&bytes).unwrap();
            let err = store.unexpected("append_events_idempotent", parsed);
            assert!(
                matches!(
                    err,
                    StorageError::WriterTaskTerminated { request_state } if request_state == state
                ),
                "state {state:?} did not survive the socket: got {err:?}"
            );
        }
        // Control: a non-writer-task refusal must NOT carry the field.
        let busy = storage_error_response(&StorageError::WriterTaskBusy { timeout_ms: 5 });
        assert!(matches!(
            busy,
            EventsResponse::Error {
                writer_task_failure: None,
                ..
            }
        ));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn proven_rollback_round_trips_as_non_terminal_request_failure() {
        use khive_storage::WriterTaskRequestState as S;

        let dir = tempfile::tempdir().unwrap();
        let client =
            EventsSplitClient::new(dir.path().join("never-bound.sock")).expect("client builds");
        let store = ForwardingEventStore::new("test", client);
        let response = storage_error_response(&StorageError::WriterTaskRequestFailed {
            request_state: S::TransactionRolledBack,
            source: Box::new(StorageError::Pool {
                operation: "writer_task_commit".into(),
                message: "commit refused".into(),
            }),
        });
        let bytes = serde_json::to_vec(&response).unwrap();
        let parsed: EventsResponse = serde_json::from_slice(&bytes).unwrap();
        let err = store.unexpected("append_events_idempotent", parsed);
        assert!(
            matches!(
                err,
                StorageError::WriterTaskRequestFailed {
                    request_state: S::TransactionRolledBack,
                    ..
                }
            ),
            "proven rollback must not reconstruct as a terminal writer: {err:?}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn direct_backend_hardens_preexisting_db_and_sidecars() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let _registry_guard = TestRegistryGuard::new(dir.path());
        let db = dir.path().join("pre-existing.events.db");
        let wal = dir.path().join("pre-existing.events.db-wal");
        std::fs::write(&db, b"").unwrap();
        std::fs::write(&wal, b"").unwrap();
        for path in [&db, &wal] {
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o644)).unwrap();
        }
        // Control: the loose mode is really in place before the open.
        assert_eq!(
            std::fs::metadata(&db).unwrap().permissions().mode() & 0o777,
            0o644
        );
        direct_backend_for(&db).expect("writable open succeeds");
        for path in [&db, &wal] {
            assert_eq!(
                std::fs::metadata(path).unwrap().permissions().mode() & 0o777,
                0o600,
                "pre-existing {} must be tightened to owner-only",
                path.display()
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn namespace_store_cache_is_bounded_and_trim_normalized() {
        let backend = StorageBackend::memory().unwrap();
        let stores: NamespaceStores =
            Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        // cap=1: the first namespace caches; the second evicts it and takes
        // the slot — bounded, and never condemned to per-request rebuilds.
        namespace_store_with_cap(&backend, &stores, "alpha", 1).expect("first store");
        namespace_store_with_cap(&backend, &stores, "beta", 1).expect("second store evicts");
        {
            let map = stores.lock().unwrap();
            assert_eq!(map.len(), 1, "cache must not grow past its cap");
            assert!(
                map.contains_key("beta"),
                "the newest namespace must be admitted at the cap"
            );
        }
        // Trimmed spelling of a cached namespace hits the same entry rather
        // than minting a duplicate handle (the backend trims namespaces).
        namespace_store_with_cap(&backend, &stores, "beta", 1).expect("cached beta");
        namespace_store_with_cap(&backend, &stores, "  beta  ", 1).expect("trimmed spelling");
        {
            let map = stores.lock().unwrap();
            assert_eq!(
                map.len(),
                1,
                "spellings of one namespace must share one entry"
            );
            assert!(map.contains_key("beta"), "trimmed key is the cache key");
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn frame_budget_admits_before_allocating_and_releases_after() {
        let (mut client, mut server) = UnixStream::pair().expect("socketpair");
        let budget = Arc::new(tokio::sync::Semaphore::new(1024));
        let payload = vec![7u8; 100];
        write_frame(&mut client, &payload).await.expect("write");
        let (bytes, permit) = read_frame_budgeted(&mut server, &budget)
            .await
            .expect("budgeted read");
        assert_eq!(bytes, payload);
        // The permit holds exactly the frame's bytes against the budget…
        assert_eq!(budget.available_permits(), 1024 - 100);
        // …and releases them when the request lifecycle ends.
        drop(permit);
        assert_eq!(budget.available_permits(), 1024);
        // A frame past the per-frame cap is refused before admission: the
        // budget is untouched, so an oversized declaration cannot starve it.
        let mut oversized = Vec::from(((crate::daemon::MAX_FRAME_BYTES + 1) as u32).to_be_bytes());
        oversized.extend_from_slice(&[0u8; 8]);
        use tokio::io::AsyncWriteExt;
        client.write_all(&oversized).await.expect("raw prefix");
        let err = read_frame_budgeted(&mut server, &budget)
            .await
            .expect_err("oversized declaration must refuse");
        assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
        assert_eq!(
            budget.available_permits(),
            1024,
            "refusal must not consume budget"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn dispatch_rejects_invalid_wire_namespace() {
        let backend = Arc::new(StorageBackend::memory().unwrap());
        let stores: NamespaceStores =
            Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        // An attacker-shaped namespace: far past the 256-byte Namespace
        // bound. Must be refused as a typed non-retryable error before it
        // can become a cache key or a store.
        let huge = "n".repeat(64 * 1024);
        let response = dispatch_events_request(
            EventsRequest::CountEvents {
                protocol_version: EVENTS_PROTOCOL_VERSION,
                namespace: huge,
                filter: Default::default(),
            },
            &backend,
            &stores,
        )
        .await;
        assert!(
            matches!(
                &response,
                EventsResponse::Error {
                    retryable: false,
                    writer_task_failure: None,
                    ..
                }
            ),
            "oversized namespace must be a typed refusal, got {response:?}"
        );
        assert_eq!(
            stores.lock().unwrap().len(),
            0,
            "a rejected namespace must never enter the cache"
        );
        // Control: a valid namespace on the same dispatch path succeeds.
        let ok = dispatch_events_request(
            EventsRequest::CountEvents {
                protocol_version: EVENTS_PROTOCOL_VERSION,
                namespace: "local".to_string(),
                filter: Default::default(),
            },
            &backend,
            &stores,
        )
        .await;
        assert!(
            matches!(ok, EventsResponse::Count { .. }),
            "valid namespace must dispatch, got {ok:?}"
        );
    }

    include!("events_split_shutdown_tests.rs");

    #[cfg(unix)]
    #[tokio::test]
    async fn forwarder_abandons_hung_delivery() {
        // A daemon that accepts the connection and then never responds must
        // not park the forwarder forever: the delivery deadline fires, the
        // batch is dropped and counted, and the task stays live.
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("hung.sock");
        let listener = tokio::net::UnixListener::bind(&socket).unwrap();
        // Accept and hold connections open without ever reading or replying.
        let _server = tokio::spawn(async move {
            let mut held = Vec::new();
            loop {
                if let Ok((stream, _)) = listener.accept().await {
                    held.push(stream);
                }
            }
        });
        let client = EventsSplitClient::new_with_queue_depth_and_delivery_timeout(
            socket.clone(),
            4,
            Duration::from_millis(100),
        )
        .expect("client builds");
        let event = Event::new(
            "test",
            "noop",
            khive_types::EventKind::Audit,
            khive_types::SubstrateKind::Event,
            "tester",
        );
        client.enqueue("test", vec![event]);
        let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
        loop {
            if client.metrics().dropped_batches >= 1 {
                break;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "forwarder never abandoned the hung delivery: {:?}",
                client.metrics()
            );
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
    }

    #[cfg(unix)]
    #[test]
    fn wire_retryability_follows_the_storage_classifier() {
        let busy = storage_error_response(&StorageError::WriterTaskBusy { timeout_ms: 5 });
        assert!(
            matches!(
                busy,
                EventsResponse::Error {
                    retryable: true,
                    ..
                }
            ),
            "transient writer contention must stay retryable across the socket"
        );
        // A terminated writer task is not retryable per the storage layer's
        // own classifier; the wire response must agree rather than widen it.
        let terminated = storage_error_response(&StorageError::WriterTaskTerminated {
            request_state: khive_storage::WriterTaskRequestState::SideEffectsUnknown,
        });
        assert!(
            matches!(
                terminated,
                EventsResponse::Error {
                    retryable: false,
                    ..
                }
            ),
            "a terminated writer must not be reported transient"
        );
    }

    use khive_storage::event::EventAppendDisposition;
    use khive_types::{EventKind, SubstrateKind};

    fn test_event(namespace: &str) -> Event {
        Event::new(
            namespace,
            "test.verb",
            EventKind::Audit,
            SubstrateKind::Event,
            "actor:test",
        )
    }

    /// Boot a real events daemon on temp paths, poll until its socket accepts.
    #[cfg(unix)]
    async fn boot_daemon(dir: &tempfile::TempDir) -> (PathBuf, PathBuf) {
        let db = dir.path().join("events.db");
        let socket = dir.path().join("events.sock");
        let (db_clone, socket_clone) = (db.clone(), socket.clone());
        tokio::spawn(async move {
            let _ = run_events_daemon(&db_clone, &socket_clone).await;
        });
        for _ in 0..100 {
            if UnixStream::connect(&socket).await.is_ok() {
                return (db, socket);
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
        panic!("events daemon did not come up on {}", socket.display());
    }

    /// The split store's routing contract: plain appends land ONLY in the
    /// legacy store (whose raw-SQL consumers depend on finding them there),
    /// the idempotent audit lane lands ONLY in the events lane, and reads
    /// merge both sides into one event plane.
    #[tokio::test]
    async fn split_store_routes_plain_to_legacy_idempotent_to_lane_and_merges_reads() {
        let dir = tempfile::tempdir().expect("tempdir");
        let _registry_guard = TestRegistryGuard::new(dir.path());
        let legacy_backend =
            direct_backend_for(&dir.path().join("legacy.db")).expect("legacy backend");
        let lane_backend = direct_backend_for(&dir.path().join("lane.db")).expect("lane backend");
        let legacy = legacy_backend
            .events_for_namespace("local")
            .expect("legacy store");
        let lane = lane_backend
            .events_for_namespace("local")
            .expect("lane store");
        let split = SplitEventStore::new(Arc::clone(&legacy), Arc::clone(&lane));

        let plain = test_event("local");
        let plain_id = plain.id;
        split.append_event(plain).await.expect("plain append");

        let audit = test_event("local");
        let audit_id = audit.id;
        let result = split
            .append_events_idempotent(vec![audit])
            .await
            .expect("idempotent append");
        assert_eq!(result.rows, vec![EventAppendDisposition::Inserted]);

        // Routing: each row is in exactly its own side.
        assert!(legacy
            .get_event(plain_id)
            .await
            .expect("legacy get")
            .is_some());
        assert!(lane.get_event(plain_id).await.expect("lane get").is_none());
        assert!(legacy
            .get_event(audit_id)
            .await
            .expect("legacy get")
            .is_none());
        assert!(lane.get_event(audit_id).await.expect("lane get").is_some());

        // Merged reads observe one event plane whichever side holds the row.
        assert!(split
            .get_event(plain_id)
            .await
            .expect("split get")
            .is_some());
        assert!(split
            .get_event(audit_id)
            .await
            .expect("split get")
            .is_some());
        assert_eq!(
            split
                .count_events(EventFilter::default())
                .await
                .expect("split count"),
            2
        );
        let page = split
            .query_events(
                EventFilter::default(),
                PageRequest {
                    offset: 0,
                    limit: 10,
                },
            )
            .await
            .expect("split query");
        let ids: Vec<Uuid> = page.items.iter().map(|e| e.id).collect();
        assert!(ids.contains(&plain_id) && ids.contains(&audit_id));

        // Windowing across the merge: page size 1 at offsets 0 and 1 yields
        // the two rows exactly once each.
        let mut seen = Vec::new();
        for offset in 0..2 {
            let page = split
                .query_events(EventFilter::default(), PageRequest { offset, limit: 1 })
                .await
                .expect("windowed query");
            assert_eq!(page.items.len(), 1);
            seen.push(page.items[0].id);
        }
        seen.sort();
        let mut expected = vec![plain_id, audit_id];
        expected.sort();
        assert_eq!(seen, expected);
    }

    /// Mechanized co-residency guard: the amendment's load-bearing claim is
    /// that every class a raw-SQL consumer of the legacy `events` table
    /// depends on still LANDS in that table. Two of the three enumerated
    /// consumers (kg projection guard, graph-query union) fail silently if
    /// the classification drifts, so the classification is guarded here by
    /// the consumers' own access pattern — a raw SQL read against the legacy
    /// backend — rather than by enumeration. Arm 1 reddens if plain appends
    /// (the provenance/domain class) ever stop reaching the legacy table.
    /// Arm 2 is the boundary's other face and doubles as the positive
    /// control for the instrument: the same query DOES find lane-routed rows
    /// on the lane's own backend, so an empty arm-1 result could not be a
    /// broken query.
    #[tokio::test]
    async fn raw_sql_consumers_of_the_legacy_events_table_still_see_plain_appends() {
        use khive_storage::types::{SqlStatement, SqlValue};

        let dir = tempfile::tempdir().expect("tempdir");
        let _registry_guard = TestRegistryGuard::new(dir.path());
        let legacy_backend =
            direct_backend_for(&dir.path().join("legacy-guard.db")).expect("legacy backend");
        let lane_backend =
            direct_backend_for(&dir.path().join("lane-guard.db")).expect("lane backend");
        let split = SplitEventStore::new(
            legacy_backend
                .events_for_namespace("local")
                .expect("legacy store"),
            lane_backend
                .events_for_namespace("local")
                .expect("lane store"),
        );

        // The schedule pack's creator-provenance write is a plain append; the
        // audit flusher's write is an idempotent batch. Route one of each.
        let provenance = test_event("local");
        let provenance_id = provenance.id;
        split.append_event(provenance).await.expect("plain append");
        let audit = test_event("local");
        let audit_id = audit.id;
        split
            .append_events_idempotent(vec![audit])
            .await
            .expect("idempotent append");

        let count_by_raw_sql = |backend: Arc<StorageBackend>, id: Uuid| async move {
            let mut reader = backend.sql().reader().await.expect("sql reader");
            let rows = reader
                .query_all(SqlStatement {
                    sql: "SELECT actor FROM events WHERE id = ?1".to_string(),
                    params: vec![SqlValue::Text(id.to_string())],
                    label: None,
                })
                .await
                .expect("raw events query");
            rows.len()
        };

        // Arm 1: the co-residency contract. A raw-SQL consumer of the legacy
        // table finds the plain-append row there.
        assert_eq!(
            count_by_raw_sql(Arc::clone(&legacy_backend), provenance_id).await,
            1,
            "plain appends must stay visible to raw-SQL consumers of the legacy events table"
        );
        // Arm 2a: the moved class is genuinely gone from the legacy table —
        // this is the silent-failure face of the boundary, held visible.
        assert_eq!(
            count_by_raw_sql(Arc::clone(&legacy_backend), audit_id).await,
            0,
            "audit-lane rows must not land in the legacy events table"
        );
        // Arm 2b: positive control for the instrument — the identical query
        // finds the moved row on the lane backend, so arm 2a's zero (and any
        // future arm-1 zero) is a routing fact, not a dead query.
        assert_eq!(
            count_by_raw_sql(Arc::clone(&lane_backend), audit_id).await,
            1,
            "the raw query must prove it can find rows where they actually live"
        );
    }

    /// End to end over the real socket: the idempotent lane returns true
    /// dispositions, and the row is readable back through the same store.
    #[cfg(unix)]
    #[tokio::test]
    async fn idempotent_append_round_trips_through_the_daemon() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (_db, socket) = boot_daemon(&dir).await;
        let client = EventsSplitClient::new(socket).expect("client");
        let store = ForwardingEventStore::new("local", client);

        let event = test_event("local");
        let id = event.id;
        let result = store
            .append_events_idempotent(vec![event.clone()])
            .await
            .expect("idempotent append over socket");
        assert_eq!(result.rows, vec![EventAppendDisposition::Inserted]);

        // Retry of the identical row reports AlreadyPresentIdentical — the
        // daemon ran the real idempotent path, not a blind re-insert.
        let retry = store
            .append_events_idempotent(vec![event])
            .await
            .expect("idempotent retry");
        assert_eq!(
            retry.rows,
            vec![EventAppendDisposition::AlreadyPresentIdentical]
        );

        let fetched = store.get_event(id).await.expect("get over socket");
        assert_eq!(fetched.map(|e| e.id), Some(id));
        let count = store
            .count_events(EventFilter::default())
            .await
            .expect("count over socket");
        assert_eq!(count, 1);
    }

    /// The fire-and-forget lane delivers to the daemon store: enqueue returns
    /// immediately and the row becomes visible to a subsequent count.
    #[cfg(unix)]
    #[tokio::test]
    async fn fire_and_forget_append_lands_in_the_daemon_store() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (_db, socket) = boot_daemon(&dir).await;
        let client = EventsSplitClient::new(socket).expect("client");
        let store = ForwardingEventStore::new("local", Arc::clone(&client));

        store
            .append_event(test_event("local"))
            .await
            .expect("append_event is fire-and-forget");

        // Poll for BOTH effects: the row landing daemon-side and the
        // forwarder's own counter — the row can be visible a beat before the
        // forwarder task is rescheduled to record the delivery.
        let (count, metrics) = tokio::time::timeout(Duration::from_secs(30), async {
            loop {
                let count = store
                    .count_events(EventFilter::default())
                    .await
                    .expect("count over socket");
                let metrics = client.metrics();
                if (count == 1 && metrics.forwarded_events >= 1) || metrics.dropped_events > 0 {
                    break (count, metrics);
                }
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        })
        .await
        .expect("forwarder must deliver or report a drop within 30 seconds");
        assert_eq!(
            metrics.dropped_events, 0,
            "forwarder dropped an event before it reached the daemon store"
        );
        assert_eq!(count, 1, "forwarded event must land in the daemon store");
        assert!(metrics.forwarded_events >= 1, "delivery must be counted");
    }

    /// R4 overflow arm: with the daemon dead, appends beyond the queue bound
    /// are DROPPED and counted while every append still returns Ok — the
    /// domain path proceeds. The drop counter is the loss-tolerance contract.
    #[cfg(unix)]
    #[tokio::test]
    async fn queue_overflow_drops_and_counts_but_never_errors() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dead_socket = dir.path().join("nobody-home.sock");
        let client = EventsSplitClient::new_with_queue_depth(dead_socket, 2).expect("client");
        let store = ForwardingEventStore::new("local", Arc::clone(&client));

        for _ in 0..20 {
            store
                .append_event(test_event("local"))
                .await
                .expect("append_event must not error under overflow");
        }
        let metrics = client.metrics();
        assert!(
            metrics.dropped_events > 0,
            "overflow must register in the drop counter, got {metrics:?}"
        );
    }

    /// R4 dead-socket arm: synchronous lanes fail with a typed retryable
    /// storage error (never hang, never a generic panic), and the offline
    /// preflight validator keeps working with zero I/O.
    #[cfg(unix)]
    #[tokio::test]
    async fn dead_socket_reads_fail_typed_and_preflight_stays_local() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dead_socket = dir.path().join("nobody-home.sock");
        let client = EventsSplitClient::new(dead_socket).expect("client");
        let store = ForwardingEventStore::new("local", client);

        let error = store
            .get_event(Uuid::new_v4())
            .await
            .expect_err("read against a dead socket must fail");
        assert!(
            matches!(error, StorageError::Pool { .. }),
            "expected the typed unreachable error, got {error:?}"
        );

        // The audit-batch seam contract: preflight is local and functional
        // with the daemon down.
        assert!(store.supports_idempotent_audit_batch());
        store
            .preflight_event(&test_event("local"))
            .expect("offline preflight validates a well-formed event");
    }

    /// A connected peer that consumed the request but sent no response is a
    /// broken response, not evidence that no daemon answered the socket.
    #[cfg(unix)]
    #[tokio::test]
    async fn connected_events_peer_closing_without_response_is_not_unreachable() {
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("closes-after-request.sock");
        let listener = UnixListener::bind(&socket).unwrap();
        let server = tokio::spawn(async move {
            let (mut stream, _) = listener.accept().await.unwrap();
            read_frame(&mut stream)
                .await
                .expect("complete request arrives");
            // Drop the connection without writing a response frame.
        });
        let client = EventsSplitClient::new(socket).unwrap();
        let store = ForwardingEventStore::new("local", client);
        let error = store.get_event(Uuid::new_v4()).await.unwrap_err();
        assert!(
            matches!(error, StorageError::Serialization { .. }),
            "a post-connect response failure must not be Pool/unreachable: {error:?}"
        );
        server.await.unwrap();
    }

    /// 4096 ordinary 3-KiB events obey the row limit yet exceed one IPC
    /// frame. The daemon must answer with a non-retryable size refusal so a
    /// caller can use a narrower page on the same healthy socket.
    #[cfg(unix)]
    #[tokio::test]
    async fn query_page_over_frame_cap_returns_typed_size_refusal() {
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("large-query.sock");
        let backend = Arc::new(StorageBackend::memory().unwrap());
        let event_store = backend.events_for_namespace("local").unwrap();
        let events: Vec<_> = (0..MAX_QUERY_EVENTS_PAGE_ROWS)
            .map(|_| {
                test_event("local").with_payload(serde_json::json!({"data": "x".repeat(3 * 1024)}))
            })
            .collect();
        event_store
            .append_events(events)
            .await
            .expect("seed large page");

        let listener = UnixListener::bind(&socket).unwrap();
        let stores: NamespaceStores =
            Arc::new(std::sync::Mutex::new(std::collections::HashMap::new()));
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            serve_events_conn(
                stream,
                backend,
                stores,
                Arc::new(tokio::sync::Semaphore::new(MAX_INFLIGHT_REQUEST_BYTES)),
            )
            .await;
        });
        let client = EventsSplitClient::new(socket).unwrap();
        let store = ForwardingEventStore::new("local", client);
        let error = store
            .query_events(
                EventFilter::default(),
                PageRequest {
                    offset: 0,
                    limit: MAX_QUERY_EVENTS_PAGE_ROWS,
                },
            )
            .await
            .expect_err("the full page cannot fit one frame");
        assert!(
            matches!(error, StorageError::InvalidInput { .. }),
            "expected non-retryable frame-size refusal, got {error:?}"
        );
        assert!(
            error.to_string().contains("response_frame_size_limit"),
            "{error}"
        );
        assert!(
            error.to_string().contains("request a narrower page"),
            "{error}"
        );
        server.abort();
    }

    /// The byte budget counts the in-flight batch as well as queued batches.
    /// A stalled daemon therefore cannot retain another large batch just
    /// because the mpsc channel still has spare batch slots.
    #[cfg(unix)]
    #[tokio::test]
    async fn forwarding_queue_enforces_serialized_byte_and_frame_limits_with_drop_metrics() {
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("stalled-forwarder.sock");
        let listener = UnixListener::bind(&socket).unwrap();
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let _hold_open = stream;
            std::future::pending::<()>().await;
        });
        let event = test_event("local").with_payload(serde_json::json!({"data": "x".repeat(4096)}));
        let first = vec![event.clone(), event.clone()];
        let request_bytes = serde_json::to_vec(&EventsRequest::AppendEvents {
            protocol_version: EVENTS_PROTOCOL_VERSION,
            namespace: "local".into(),
            events: first.clone(),
        })
        .unwrap()
        .len();
        let byte_budget = request_bytes + 64;
        let client = EventsSplitClient::new_with_limits_and_delivery_timeout(
            socket,
            8,
            byte_budget,
            Duration::from_secs(30),
        )
        .unwrap();
        let store = ForwardingEventStore::new("local", Arc::clone(&client));
        store.append_events(first.clone()).await.unwrap();
        assert_eq!(client.metrics().queued_bytes, request_bytes);

        store.append_events(first).await.unwrap();
        let metrics = client.metrics();
        assert_eq!(metrics.dropped_batches, 1);
        assert_eq!(metrics.dropped_events, 2);
        assert_eq!(metrics.queued_bytes, request_bytes);
        assert!(metrics.queued_bytes <= byte_budget);

        // One append request larger than the daemon frame cannot ever be
        // delivered; it must be refused before occupying a queue slot.
        let oversized = test_event("local")
            .with_payload(serde_json::json!({"data": "x".repeat(crate::daemon::MAX_FRAME_BYTES)}));
        store.append_event(oversized).await.unwrap();
        let metrics = client.metrics();
        assert_eq!(metrics.dropped_batches, 2);
        assert_eq!(metrics.dropped_events, 3);
        assert_eq!(metrics.queued_bytes, request_bytes);
        server.abort();
    }

    /// Version-skew arm: a frame carrying an unknown protocol version gets a
    /// typed non-retryable refusal, not a deserialization failure.
    #[cfg(unix)]
    #[tokio::test]
    async fn protocol_version_skew_is_a_typed_refusal() {
        let dir = tempfile::tempdir().expect("tempdir");
        let (_db, socket) = boot_daemon(&dir).await;

        let mut stream = UnixStream::connect(&socket).await.expect("connect");
        let request = EventsRequest::CountEvents {
            protocol_version: EVENTS_PROTOCOL_VERSION + 1,
            namespace: "local".into(),
            filter: EventFilter::default(),
        };
        let payload = serde_json::to_vec(&request).expect("serialize");
        write_frame(&mut stream, &payload).await.expect("write");
        let bytes = read_frame(&mut stream).await.expect("read");
        let response: EventsResponse = serde_json::from_slice(&bytes).expect("parse");
        match response {
            EventsResponse::Error {
                message, retryable, ..
            } => {
                assert!(!retryable, "version skew is not retryable");
                assert!(message.contains("protocol version"), "message: {message}");
            }
            other => panic!("expected a typed refusal, got {other:?}"),
        }
    }

    /// The per-socket daemon guard is exclusive while held and reusable after
    /// release — the mechanism that keeps a supervisor respawn race down to
    /// one surviving daemon.
    #[cfg(unix)]
    #[test]
    fn events_daemon_guard_is_exclusive_then_reusable() {
        let dir = tempfile::tempdir().expect("tempdir");
        let socket = dir.path().join("events.sock");
        let first = match acquire_events_daemon_guard_outcome(&socket) {
            EventsDaemonGuardAcquisition::Held(guard) => guard,
            other => panic!("first acquire must succeed: {other:?}"),
        };
        let second = acquire_events_daemon_guard_outcome(&socket);
        assert!(
            matches!(second, EventsDaemonGuardAcquisition::Contended),
            "second acquire must report contention while the first guard is held: {second:?}"
        );
        drop(first);
        // Another test may fork while the first description is open. A child
        // can retain that flock until exec or exit; retry only that diagnosed
        // contention, never an open/hardening error, and never without a bound.
        const MAX_ATTEMPTS: usize = 100;
        for attempt in 1..=MAX_ATTEMPTS {
            match acquire_events_daemon_guard_outcome(&socket) {
                EventsDaemonGuardAcquisition::Held(_) => return,
                EventsDaemonGuardAcquisition::Contended if attempt < MAX_ATTEMPTS => {
                    std::thread::sleep(Duration::from_millis(10));
                }
                other => panic!(
                    "acquire must succeed after release within {MAX_ATTEMPTS} attempts; \
                     attempt {attempt}: {other:?}"
                ),
            }
        }
        unreachable!("the final acquisition attempt returns or reports its refusal");
    }

    #[cfg(unix)]
    #[test]
    fn events_daemon_guard_open_failure_is_not_contention() {
        let dir = tempfile::tempdir().expect("tempdir");
        let clean = dir.path().join("clean.sock");
        assert!(matches!(
            acquire_events_daemon_guard_outcome(&clean),
            EventsDaemonGuardAcquisition::Held(_)
        ));

        assert!(
            try_acquire_events_daemon_guard(&clean).is_some(),
            "the public Option entrance must preserve a successful acquisition"
        );

        // Opening a directory for writing must fail even when no process
        // holds a daemon lock. Exercise the real open, not an injected result.
        let socket = dir.path().join("blocked.sock");
        let lock_path = socket.with_extension("lock");
        std::fs::create_dir(&lock_path).expect("create directory at lock entry");
        let outcome = acquire_events_daemon_guard_outcome(&socket);
        assert!(
            matches!(outcome, EventsDaemonGuardAcquisition::OpenFailed(_)),
            "an actual lock-file open failure must not report contention: {outcome:?}"
        );
        assert!(
            try_acquire_events_daemon_guard(&socket).is_none(),
            "the public Option entrance must refuse an actual open failure"
        );
        assert!(
            lock_path.is_dir(),
            "the refused entry must remain a directory"
        );
    }

    /// A read-only file-backed runtime with the split configured must never
    /// create or schema-initialize an events database. Missing events db →
    /// `events()` serves the legacy store alone and leaves the filesystem
    /// untouched; a pre-existing events db (minted by an earlier writable
    /// host) is opened read-only and its rows merge into reads.
    /// (unix-gated for the sidecar-freeze harness step only.)
    #[cfg(unix)]
    #[tokio::test]
    async fn read_only_runtime_never_creates_an_events_db() {
        use crate::{KhiveRuntime, Namespace, RuntimeConfig};

        let dir = tempfile::tempdir().expect("tempdir");
        let _registry_guard = TestRegistryGuard::new(dir.path());
        let main_db = dir.path().join("main.db");
        // Materialize + migrate the main database with a writable runtime.
        drop(
            KhiveRuntime::new_for_test(RuntimeConfig {
                db_path: Some(main_db.clone()),
                ..RuntimeConfig::no_embeddings()
            })
            .expect("create main db"),
        );
        let events_db = events_db_path_beside(&main_db);
        assert!(!events_db.exists(), "precondition: no events db yet");

        // Freeze the WAL sidecars the writable runtime left behind — the
        // read-only opener refuses a snapshot with a writable -shm.
        khive_storage::test_support::freeze_snapshot_sidecars(&main_db);

        let split_config = |db: PathBuf| RuntimeConfig {
            db_path: Some(main_db.clone()),
            events_split: Some(EventsSplitConfig {
                db_path: db,
                socket_path: None,
            }),
            ..RuntimeConfig::no_embeddings()
        };

        // Arm 1: read-only runtime, no events db on disk. Reads work through
        // the legacy store and nothing is minted.
        let ro = KhiveRuntime::new_readonly_for_test(split_config(events_db.clone()))
            .expect("read-only runtime");
        let token = ro.authorize(Namespace::local()).expect("token");
        let store = ro.events(&token).expect("events store");
        let count = store
            .count_events(EventFilter::default())
            .await
            .expect("count through legacy-only plane");
        assert_eq!(count, 0);
        assert!(
            !events_db.exists(),
            "a read-only runtime must not mint the events database"
        );

        // Arm 2: a writable host mints the events db and lands a lane row;
        // the read-only runtime then opens it read-only and merges the row.
        // The writer is scoped (not the process-global registry) and its WAL
        // sidecars frozen after drop — the read-only opener rightly refuses a
        // snapshot with a live writer, and that refusal is not this test's
        // subject.
        {
            let lane_backend = StorageBackend::sqlite_for_test(&events_db).expect("writable lane");
            lane_backend
                .events_for_namespace("local")
                .expect("lane store")
                .append_event(test_event("local"))
                .await
                .expect("seed lane row");
        }
        khive_storage::test_support::freeze_snapshot_sidecars(&events_db);
        let store = ro.events(&token).expect("events store with lane present");
        let count = store
            .count_events(EventFilter::default())
            .await
            .expect("merged count");
        assert_eq!(count, 1, "the pre-existing lane row must merge into reads");
    }

    /// Embedded (direct) mode: the process-global backend writes and reads
    /// `events.db` without any daemon.
    #[tokio::test]
    async fn direct_mode_appends_and_reads_without_a_daemon() {
        let dir = tempfile::tempdir().expect("tempdir");
        let _registry_guard = TestRegistryGuard::new(dir.path());
        let db = dir.path().join("events.db");
        let backend = direct_backend_for(&db).expect("direct backend");
        let store = backend.events_for_namespace("local").expect("store");
        store
            .append_event(test_event("local"))
            .await
            .expect("direct append");
        let count = store
            .count_events(EventFilter::default())
            .await
            .expect("count");
        assert_eq!(count, 1);
    }
}