bcode_daemon_lifecycle 0.0.1-alpha.0

Daemon lifecycle registry and cleanup models for bcode
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

//! Daemon lifecycle registry and cleanup models.

mod execution_lifetime;
pub use execution_lifetime::{
    ExecutionLifetime, ExecutionLifetimeStatus, ExecutionMaintenance, execution_lifetime_status,
};

use bcode_ipc::{BUILD_FINGERPRINT, CURRENT_PROTOCOL_VERSION, IpcEndpoint, daemon_namespace};
use bcode_plugin_sdk::path::display_from_current_dir;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use std::fs;
use std::io::{Read, Seek as _, Write as _};
#[cfg(unix)]
use std::os::fd::AsRawFd as _;
#[cfg(target_os = "macos")]
use std::os::unix::ffi::OsStrExt as _;
#[cfg(all(unix, test))]
use std::os::unix::fs::MetadataExt as _;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use sysinfo::{Pid, ProcessesToUpdate, System};
use thiserror::Error;

/// Environment variable carrying parent-verified executable digest evidence to a spawned daemon.
pub const BCODE_EXECUTABLE_DIGEST_ENV: &str = "BCODE_EXECUTABLE_DIGEST";

/// Current daemon registry record schema version.
///
/// Version 4 adds `state_location_id`. The field is optional so version 3 records
/// still decode; a record without it is unverifiable rather than assumed local.
/// Version 5 widens that identity to the runtime scope pair
/// `(state root, config directory)`, so a version 4 record's narrower identity no
/// longer matches a current daemon and is treated as foreign rather than local.
pub const DAEMON_RECORD_SCHEMA_VERSION: u32 = 5;

/// Errors returned by daemon lifecycle registry operations.
#[derive(Debug, Error)]
pub enum DaemonLifecycleError {
    /// Registry I/O failed.
    #[error("daemon registry I/O error at {}: {source}", path.display())]
    Io {
        /// Path associated with the failed operation.
        path: PathBuf,
        /// Original I/O error.
        source: std::io::Error,
    },
    /// Registry serialization failed.
    #[error("daemon registry serialization error: {0}")]
    Serialize(#[from] serde_json::Error),
    /// System time was before the Unix epoch.
    #[error("system clock is before Unix epoch")]
    Clock,
}

/// Serializable local IPC endpoint metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DaemonEndpointRecord {
    /// Unix domain socket endpoint.
    UnixSocket {
        /// Socket path.
        path: PathBuf,
    },
    /// Windows named pipe endpoint.
    WindowsNamedPipe {
        /// Named pipe path.
        name: String,
    },
    /// Endpoint shape not known by this build.
    Unknown {
        /// Debug representation captured for diagnostics.
        debug: String,
    },
}

impl DaemonEndpointRecord {
    /// Convert this record into an IPC endpoint when supported by the current platform.
    #[must_use]
    pub fn to_ipc_endpoint(&self) -> Option<IpcEndpoint> {
        match self {
            Self::UnixSocket { path } => {
                #[cfg(unix)]
                {
                    Some(IpcEndpoint::unix_socket(path.clone()))
                }
                #[cfg(not(unix))]
                {
                    let _ = path;
                    None
                }
            }
            Self::WindowsNamedPipe { name } => {
                #[cfg(windows)]
                {
                    Some(IpcEndpoint::windows_named_pipe(name.clone()))
                }
                #[cfg(not(windows))]
                {
                    let _ = name;
                    None
                }
            }
            Self::Unknown { .. } => None,
        }
    }
}

/// Persistent metadata for one daemon instance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaemonRecord {
    /// Record schema version.
    pub schema_version: u32,
    /// Daemon namespace.
    pub namespace: String,
    /// IPC protocol version.
    pub protocol_version: u32,
    /// Exact produced-artifact identity, when advertised by this daemon generation.
    #[serde(default)]
    pub artifact_id: Option<bcode_ipc::ArtifactId>,
    /// Build fingerprint retained as source/build diagnostic evidence.
    pub build_fingerprint: String,
    /// Durable session-storage writer epoch supported by this daemon, when known.
    #[serde(default)]
    pub storage_writer_epoch: Option<u32>,
    /// Identity of the durable state location this daemon serves.
    ///
    /// Records already live under the state location they describe, so this is
    /// corroborating evidence rather than the routing key. It lets classification
    /// surface a record copied or inherited from another location instead of
    /// silently treating it as local.
    #[serde(default)]
    pub state_location_id: Option<String>,
    /// Process identifier, when available.
    pub pid: Option<u32>,
    /// IPC endpoint for this daemon.
    pub endpoint: DaemonEndpointRecord,
    /// Daemon log path.
    pub log_path: PathBuf,
    /// Executable path used to start the daemon.
    pub executable_path: Option<PathBuf>,
    /// SHA-256 digest of the executable bytes running this daemon.
    #[serde(default)]
    pub executable_digest: Option<String>,
    /// Daemon start time in Unix milliseconds.
    pub started_at_unix_ms: u64,
    /// Last registry write/update time in Unix milliseconds.
    pub last_seen_unix_ms: u64,
    /// Random per-process identity token.
    pub instance_id: String,
}

impl DaemonRecord {
    /// Build a daemon record for the current process and build.
    ///
    /// # Errors
    ///
    /// Returns an error when the system clock is before the Unix epoch.
    pub fn current(
        endpoint: &IpcEndpoint,
        log_path: PathBuf,
        executable_path: Option<PathBuf>,
        instance_id: String,
    ) -> Result<Self, DaemonLifecycleError> {
        let executable_digest = executable_path
            .as_deref()
            .map(executable_sha256)
            .transpose()?;
        Self::current_with_digest(
            endpoint,
            log_path,
            executable_path,
            executable_digest,
            instance_id,
        )
    }

    /// Build a daemon record from already-verified executable digest evidence.
    ///
    /// # Errors
    ///
    /// Returns an error when the system clock is before the Unix epoch.
    pub fn current_with_digest(
        endpoint: &IpcEndpoint,
        log_path: PathBuf,
        executable_path: Option<PathBuf>,
        executable_digest: Option<String>,
        instance_id: String,
    ) -> Result<Self, DaemonLifecycleError> {
        let now = unix_time_millis()?;
        Ok(Self {
            schema_version: DAEMON_RECORD_SCHEMA_VERSION,
            namespace: daemon_namespace(),
            protocol_version: u32::from(CURRENT_PROTOCOL_VERSION),
            artifact_id: Some(bcode_ipc::ArtifactId::current()),
            build_fingerprint: BUILD_FINGERPRINT.to_string(),
            storage_writer_epoch: None,
            state_location_id: Some(bcode_ipc::state_location_id()),
            pid: Some(std::process::id()),
            endpoint: endpoint_record(endpoint),
            log_path,
            executable_path,
            executable_digest,
            started_at_unix_ms: now,
            last_seen_unix_ms: now,
            instance_id,
        })
    }

    /// Return true when this record describes the current daemon namespace.
    #[must_use]
    pub fn is_current_namespace(&self) -> bool {
        self.namespace == daemon_namespace()
    }
}

/// Return the daemon registry directory under a Bcode state directory.
#[must_use]
pub fn registry_dir(state_dir: &Path) -> PathBuf {
    state_dir.join("daemons")
}

/// Return the registry path for a daemon namespace.
#[must_use]
pub fn record_path(state_dir: &Path, namespace: &str) -> PathBuf {
    registry_dir(state_dir).join(format!("{namespace}.json"))
}

/// Return a registry path isolated by artifact and runtime scope.
#[must_use]
pub fn scoped_record_path(state_dir: &Path, record: &DaemonRecord) -> PathBuf {
    record.state_location_id.as_ref().map_or_else(
        || record_path(state_dir, &record.namespace),
        |scope| record_path(state_dir, &format!("{}-{scope}", record.namespace)),
    )
}

fn startup_lock_path(state_dir: &Path, namespace: &str, scope: &str) -> PathBuf {
    registry_dir(state_dir).join(format!("{namespace}-{scope}.lock"))
}

/// Write a daemon registry record atomically.
///
/// # Errors
///
/// Returns an error when creating directories, serializing, writing, or renaming fails.
pub fn write_record(
    state_dir: &Path,
    record: &DaemonRecord,
) -> Result<PathBuf, DaemonLifecycleError> {
    let dir = registry_dir(state_dir);
    fs::create_dir_all(&dir).map_err(|source| DaemonLifecycleError::Io {
        path: dir.clone(),
        source,
    })?;
    let path = scoped_record_path(state_dir, record);
    let temp_path = path.with_extension(format!("json.tmp-{}", record.instance_id));
    let contents = serde_json::to_vec_pretty(record)?;
    fs::write(&temp_path, contents).map_err(|source| DaemonLifecycleError::Io {
        path: temp_path.clone(),
        source,
    })?;
    fs::rename(&temp_path, &path).map_err(|source| DaemonLifecycleError::Io {
        path: path.clone(),
        source,
    })?;
    Ok(path)
}

/// Read daemon registry records from a state directory.
///
/// Invalid records are ignored so one bad file does not block cleanup.
#[must_use]
pub fn read_records(state_dir: &Path) -> Vec<(PathBuf, DaemonRecord)> {
    let dir = registry_dir(state_dir);
    let Ok(entries) = fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .flatten()
        .filter_map(|entry| {
            let path = entry.path();
            if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
                return None;
            }
            let contents = fs::read(&path).ok()?;
            let record = serde_json::from_slice(&contents).ok()?;
            Some((path, record))
        })
        .collect()
}

/// Read a complete bounded daemon inventory for safety-sensitive coordination.
///
/// Unlike [`read_records`], this never treats unreadable, malformed, oversized, unsupported or
/// duplicate records as absent. This is an observation, not a lock against concurrent registration;
/// callers must separately coordinate registration before relying on absence as authority.
///
/// # Errors
/// Returns a secret-safe IO error for missing/unsafe registry roots, unknown entry types, invalid
/// records, duplicate namespaces/instances, or exhausted entry/record-byte budgets.
pub fn read_records_strict(
    state_dir: &Path,
    entry_budget: usize,
) -> std::io::Result<Vec<DaemonRecord>> {
    const MAX_RECORD_BYTES: u64 = 64 * 1024;
    fn invalid() -> std::io::Error {
        std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            "daemon inventory is incomplete or unverifiable",
        )
    }
    if entry_budget == 0 || entry_budget > 4096 {
        return Err(invalid());
    }
    let root = state_dir.canonicalize()?;
    let directory = root.join("daemons");
    if !fs::symlink_metadata(&directory)?.is_dir() || !directory.canonicalize()?.starts_with(&root)
    {
        return Err(invalid());
    }
    let mut records = Vec::new();
    let mut namespaces = std::collections::BTreeSet::new();
    let mut instances = std::collections::BTreeSet::new();
    for (index, entry) in fs::read_dir(&directory)?.enumerate() {
        if index == entry_budget {
            return Err(invalid());
        }
        let entry = entry?;
        let path = entry.path();
        let metadata = fs::symlink_metadata(&path)?;
        // Launch coordination and image publication locks share this directory with records.
        // They carry no registry identity, but must still be ordinary bounded files.
        if metadata.is_file()
            && metadata.len() <= MAX_RECORD_BYTES
            && (entry.file_name() == "daemon-images.lock"
                || (path.extension().and_then(|value| value.to_str()) == Some("lock")
                    && path
                        .file_stem()
                        .and_then(|value| value.to_str())
                        .is_some_and(|name| name.starts_with("ipc-v"))))
        {
            continue;
        }
        if !metadata.is_file()
            || metadata.len() > MAX_RECORD_BYTES
            || path.extension().and_then(|value| value.to_str()) != Some("json")
        {
            return Err(invalid());
        }
        let mut bytes = Vec::new();
        fs::File::open(&path)?
            .take(MAX_RECORD_BYTES + 1)
            .read_to_end(&mut bytes)?;
        if bytes.len() as u64 > MAX_RECORD_BYTES {
            return Err(invalid());
        }
        let record: DaemonRecord = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
        if record.schema_version != DAEMON_RECORD_SCHEMA_VERSION
            || record.namespace.is_empty()
            || record.instance_id.is_empty()
            || (path != scoped_record_path(state_dir, &record)
                && path != record_path(state_dir, &record.namespace))
            || !namespaces.insert((record.namespace.clone(), record.state_location_id.clone()))
            || !instances.insert(record.instance_id.clone())
        {
            return Err(invalid());
        }
        records.push(record);
    }
    records.sort_by(|left, right| left.namespace.cmp(&right.namespace));
    Ok(records)
}

/// Remove a daemon registry record.
///
/// # Errors
///
/// Returns an error when removing the registry file fails for reasons other than not found.
pub fn remove_record_path(path: &Path) -> Result<(), DaemonLifecycleError> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(source) => Err(DaemonLifecycleError::Io {
            path: path.to_path_buf(),
            source,
        }),
    }
}

/// Remove a daemon registry record when it still belongs to the provided instance.
///
/// # Errors
///
/// Returns an error when reading or removing the registry file fails for reasons
/// other than not found.
pub fn remove_record_if_instance(
    path: &Path,
    instance_id: &str,
) -> Result<(), DaemonLifecycleError> {
    let contents = match fs::read(path) {
        Ok(contents) => contents,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(source) => {
            return Err(DaemonLifecycleError::Io {
                path: path.to_path_buf(),
                source,
            });
        }
    };
    let record = serde_json::from_slice::<DaemonRecord>(&contents)?;
    if record.instance_id == instance_id {
        remove_record_path(path)?;
    }
    Ok(())
}

async fn probe_daemon_status(endpoint: &IpcEndpoint) -> Option<bcode_ipc::DaemonStatus> {
    let mut stream = bcode_ipc::LocalIpcStream::connect(endpoint).await.ok()?;
    let envelope = bcode_ipc::request_envelope(
        1,
        &bcode_ipc::Request::Hello {
            client_name: "bcode-daemon-readiness".to_owned(),
            runtime_context: None,
            daemon_namespace: daemon_namespace(),
            artifact_id: Some(bcode_ipc::ArtifactId::current()),
            build_fingerprint: BUILD_FINGERPRINT.to_owned(),
            state_location_id: Some(bcode_ipc::state_location_id()),
        },
    )
    .ok()?;
    bcode_ipc::send_envelope(&mut stream, &envelope)
        .await
        .ok()?;
    loop {
        let envelope = bcode_ipc::recv_envelope(&mut stream).await.ok()?;
        if envelope.kind != bcode_ipc::EnvelopeKind::Response || envelope.request_id != 1 {
            continue;
        }
        return match bcode_ipc::decode_response(&envelope.payload).ok()? {
            bcode_ipc::Response::Ok(bcode_ipc::ResponsePayload::Hello { daemon, .. }) => {
                Some(daemon)
            }
            _ => None,
        };
    }
}

/// Conservative classification of one daemon registry record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DaemonRecordClassification {
    /// Current-build daemon responded with the exact persisted identity.
    CurrentHealthy,
    /// Historical daemon responded with the exact persisted identity.
    HistoricalExactResponsive,
    /// Endpoint could not be decoded with the current protocol, but independent process evidence
    /// exactly identifies the historical daemon.
    HistoricalProcessVerifiedProtocolUnsupported,
    /// An endpoint responded, but its identity does not match this record.
    ResponsiveIdentityMismatch,
    /// Endpoint is unreachable and positive process evidence proves the recorded process is gone
    /// or replaced.
    UnreachableStale,
    /// Evidence is incomplete or ambiguous; callers must preserve the record.
    Unverifiable,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProcessIdentityEvidence {
    Exact,
    MissingOrReused,
    Unverifiable,
}

fn classify_daemon_record_evidence(
    record: &DaemonRecord,
    status: Option<&bcode_ipc::DaemonStatus>,
    endpoint_reachable: bool,
    process: ProcessIdentityEvidence,
) -> DaemonRecordClassification {
    status.map_or_else(
        || {
            if endpoint_reachable && process == ProcessIdentityEvidence::Exact {
                DaemonRecordClassification::HistoricalProcessVerifiedProtocolUnsupported
            } else if !endpoint_reachable && process == ProcessIdentityEvidence::MissingOrReused {
                DaemonRecordClassification::UnreachableStale
            } else {
                DaemonRecordClassification::Unverifiable
            }
        },
        |status| {
            if daemon_status_matches_record(record, status) {
                if record.is_current_namespace() {
                    DaemonRecordClassification::CurrentHealthy
                } else {
                    DaemonRecordClassification::HistoricalExactResponsive
                }
            } else {
                DaemonRecordClassification::ResponsiveIdentityMismatch
            }
        },
    )
}

fn daemon_status_matches_record(record: &DaemonRecord, status: &bcode_ipc::DaemonStatus) -> bool {
    status.instance_id == record.instance_id
        && status.namespace == record.namespace
        && status.protocol_version == record.protocol_version
        && status.artifact_id == record.artifact_id
        && status.build_fingerprint == record.build_fingerprint
        && status.executable_digest == record.executable_digest
        && status.storage_writer_epoch == record.storage_writer_epoch
        && status.pid == record.pid
        && status.started_at_unix_ms == record.started_at_unix_ms
}

fn process_identity_evidence(record: &DaemonRecord) -> ProcessIdentityEvidence {
    let (Some(pid), Some(expected_digest)) = (record.pid, record.executable_digest.as_deref())
    else {
        return ProcessIdentityEvidence::Unverifiable;
    };
    let pid = Pid::from_u32(pid);
    let mut system = System::new();
    system.refresh_processes(ProcessesToUpdate::Some(&[pid]), true);
    let Some(process) = system.process(pid) else {
        return ProcessIdentityEvidence::MissingOrReused;
    };
    let process_started_at_seconds = process.start_time();
    if process_started_at_seconds != record.started_at_unix_ms / 1_000 {
        return ProcessIdentityEvidence::MissingOrReused;
    }
    let Some(executable) = process.exe() else {
        return ProcessIdentityEvidence::Unverifiable;
    };
    // A digest mismatch only proves PID reuse when the pathname is content-addressed, because an
    // immutable image path can never be rewritten in place. A daemon spawned from a mutable
    // pathname (such as a `cargo build` output) keeps running its original bytes even after that
    // path is rebuilt, so a mismatch there is ambiguous rather than positive reuse evidence.
    let path_is_immutable = executable_path_matches_digest(executable, expected_digest);
    match executable_sha256(executable) {
        Ok(actual_digest) if actual_digest == expected_digest => ProcessIdentityEvidence::Exact,
        Ok(_) if path_is_immutable => ProcessIdentityEvidence::MissingOrReused,
        Ok(_) | Err(_) => ProcessIdentityEvidence::Unverifiable,
    }
}

/// Resolve a registry target only when it belongs to this process's pinned identity.
///
/// # Errors
/// Rejects foreign artifacts, executable bytes, state locations, and unsupported endpoints
/// before opening any transport connection.
pub fn pinned_daemon_endpoint(record: &DaemonRecord) -> Result<IpcEndpoint, DaemonLifecycleError> {
    let digest = initialize_artifact_bootstrap()?.digest()?;
    if record.artifact_id.as_ref() != Some(&bcode_ipc::ArtifactId::current())
        || !record.is_current_namespace()
        || record.executable_digest.as_deref() != Some(digest.as_str())
        || record.state_location_id.as_deref() != Some(bcode_ipc::state_location_id().as_str())
    {
        return Err(DaemonLifecycleError::Io {
            path: PathBuf::from("<daemon-target>"),
            source: std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "daemon target differs from the process-pinned executable or state location; use a separately started matching process",
            ),
        });
    }
    record
        .endpoint
        .to_ipc_endpoint()
        .ok_or_else(|| DaemonLifecycleError::Io {
            path: PathBuf::from("<daemon-target>"),
            source: std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "unsupported daemon endpoint",
            ),
        })
}

/// Classify one daemon record without mutating registry or endpoint state.
pub async fn classify_daemon_record(record: &DaemonRecord) -> DaemonRecordClassification {
    if pinned_daemon_endpoint(record).is_err() {
        // Foreign endpoints must never be contacted, even for liveness probes.
        // Process evidence can prove death; everything else remains conservative.
        return match process_identity_evidence(record) {
            ProcessIdentityEvidence::MissingOrReused => {
                DaemonRecordClassification::UnreachableStale
            }
            ProcessIdentityEvidence::Exact | ProcessIdentityEvidence::Unverifiable => {
                DaemonRecordClassification::Unverifiable
            }
        };
    }
    let endpoint = record.endpoint.to_ipc_endpoint();
    let status = if let Some(endpoint) = endpoint.as_ref() {
        tokio::time::timeout(Duration::from_millis(500), probe_daemon_status(endpoint))
            .await
            .ok()
            .flatten()
    } else {
        None
    };
    let endpoint_reachable = if status.is_some() {
        true
    } else if let Some(endpoint) = endpoint.as_ref() {
        tokio::time::timeout(
            Duration::from_millis(250),
            bcode_ipc::LocalIpcStream::connect(endpoint),
        )
        .await
        .is_ok_and(|result| result.is_ok())
    } else {
        false
    };
    let classification = classify_daemon_record_evidence(
        record,
        status.as_ref(),
        endpoint_reachable,
        process_identity_evidence(record),
    );
    tracing::debug!(
        namespace = record.namespace,
        instance_id = record.instance_id,
        pid = record.pid,
        classification = ?classification,
        "classified daemon registry record"
    );
    classification
}

async fn live_record_matches_instance(record: &DaemonRecord) -> bool {
    matches!(
        classify_daemon_record(record).await,
        DaemonRecordClassification::CurrentHealthy
            | DaemonRecordClassification::HistoricalExactResponsive
    )
}

/// Classify every decodable daemon record without mutating registry state.
pub async fn classified_records(
    state_dir: &Path,
) -> Vec<(PathBuf, DaemonRecord, DaemonRecordClassification)> {
    let mut classified = Vec::new();
    for (path, record) in read_records(state_dir) {
        let classification = classify_daemon_record(&record).await;
        classified.push((path, record, classification));
    }
    classified
}

/// Return whether any live or ambiguous daemon evidence exists for an artifact identity.
///
/// `identity` may be a daemon namespace, build fingerprint, or exact artifact ID. Cleanup
/// callers must refuse mutation when this returns true. Malformed registry records are treated
/// as ambiguous evidence and therefore fail closed.
///
/// # Errors
///
/// Returns an error if the registry directory cannot be read.
pub async fn namespace_has_live_or_ambiguous_evidence(
    state_dir: &Path,
    identity: &str,
) -> Result<bool, DaemonLifecycleError> {
    let dir = registry_dir(state_dir);
    let entries = match fs::read_dir(&dir) {
        Ok(entries) => entries,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(false),
        Err(source) => return Err(DaemonLifecycleError::Io { path: dir, source }),
    };
    for entry in entries {
        let entry = entry.map_err(|source| DaemonLifecycleError::Io {
            path: dir.clone(),
            source,
        })?;
        let path = entry.path();
        if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
            continue;
        }
        let contents = fs::read(&path).map_err(|source| DaemonLifecycleError::Io {
            path: path.clone(),
            source,
        })?;
        let Ok(record) = serde_json::from_slice::<DaemonRecord>(&contents) else {
            return Ok(true);
        };
        let identity_matches = record.namespace == identity
            || record.build_fingerprint == identity
            || record
                .artifact_id
                .as_ref()
                .is_some_and(|artifact_id| artifact_id.as_str() == identity);
        if !identity_matches {
            continue;
        }
        if !matches!(
            classify_daemon_record(&record).await,
            DaemonRecordClassification::UnreachableStale
        ) {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Return daemon registry records whose IPC endpoints currently respond and whose server identity
/// matches the persisted instance record.
///
/// Stale, malformed, or endpoint-reused records are excluded. This function does not mutate
/// registry files.
pub async fn live_records(state_dir: &Path) -> Vec<(PathBuf, DaemonRecord)> {
    let mut live = Vec::new();
    for (path, record) in read_records(state_dir) {
        if live_record_matches_instance(&record).await {
            live.push((path, record));
        }
    }
    live
}

fn storage_writer_is_incompatible(record: &DaemonRecord, storage_writer_epoch: u32) -> bool {
    record.storage_writer_epoch != Some(storage_writer_epoch)
}

/// Return live daemons that do not advertise `storage_writer_epoch`.
///
/// Legacy records with no writer epoch are incompatible by default.
pub async fn incompatible_storage_writer_records(
    state_dir: &Path,
    storage_writer_epoch: u32,
) -> Vec<(PathBuf, DaemonRecord)> {
    classified_records(state_dir)
        .await
        .into_iter()
        .filter(|(_, record, classification)| {
            matches!(
                classification,
                DaemonRecordClassification::CurrentHealthy
                    | DaemonRecordClassification::HistoricalExactResponsive
            ) && storage_writer_is_incompatible(record, storage_writer_epoch)
        })
        .map(|(path, record, _)| (path, record))
        .collect()
}

/// Metadata published beside one immutable daemon image.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DaemonImageMetadata {
    /// Metadata schema version.
    pub schema_version: u32,
    /// Exact produced-artifact identity embedded in the image.
    pub artifact_id: bcode_ipc::ArtifactId,
    /// SHA-256 digest of the image bytes.
    pub executable_digest: String,
}

const DAEMON_IMAGE_METADATA_SCHEMA_VERSION: u32 = 1;
const DAEMON_IMAGE_METADATA_FILE: &str = "image.json";
const DAEMON_IMAGE_CLEANUP_LOCK_FILE: &str = "daemon-images.lock";

/// Return the artifact-scoped directory that stores cached daemon executables.
#[must_use]
pub fn daemon_image_dir(state_dir: &Path) -> PathBuf {
    state_dir
        .join("daemon-images")
        .join(bcode_ipc::ArtifactId::current().as_str())
}

/// Bootstrap snapshot of the exact running artifact retained independently of its pathname.
#[derive(Debug)]
pub struct ArtifactBootstrap {
    artifact_id: bcode_ipc::ArtifactId,
    source_path: PathBuf,
    source: Mutex<fs::File>,
    executable_digest: OnceLock<String>,
}

static ARTIFACT_BOOTSTRAP: OnceLock<ArtifactBootstrap> = OnceLock::new();

/// Capture and retain the running artifact before its original pathname can be replaced.
///
/// Repeated calls return the same process bootstrap. The retained file handle remains readable
/// after Unix pathname replacement and prevents later lifecycle work from reopening a different
/// file at the original path.
///
/// # Panics
///
/// Panics only if the process-global bootstrap cannot be observed immediately after this function
/// successfully initializes it.
///
/// # Errors
///
/// Returns an error when the current executable cannot be located or opened.
pub fn initialize_artifact_bootstrap() -> Result<&'static ArtifactBootstrap, DaemonLifecycleError> {
    if let Some(bootstrap) = ARTIFACT_BOOTSTRAP.get() {
        return Ok(bootstrap);
    }
    let source_path = std::env::current_exe().map_err(|source| DaemonLifecycleError::Io {
        path: PathBuf::from("<current_exe>"),
        source,
    })?;
    let artifact_id = bcode_ipc::ArtifactId::current();
    let bootstrap = ArtifactBootstrap::open_verified(source_path, artifact_id)?;
    let _ = ARTIFACT_BOOTSTRAP.set(bootstrap);
    Ok(ARTIFACT_BOOTSTRAP
        .get()
        .expect("artifact bootstrap initialized"))
}

impl ArtifactBootstrap {
    fn open_verified(
        source_path: PathBuf,
        artifact_id: bcode_ipc::ArtifactId,
    ) -> Result<Self, DaemonLifecycleError> {
        let bootstrap = Self::open(source_path, artifact_id)?;
        let mut source = bootstrap
            .source
            .lock()
            .map_err(|_| DaemonLifecycleError::Io {
                path: bootstrap.source_path.clone(),
                source: std::io::Error::other("artifact bootstrap lock poisoned"),
            })?;
        let observed = bcode_ipc::ArtifactId::for_executable(&mut *source).map_err(|source| {
            DaemonLifecycleError::Io {
                path: bootstrap.source_path.clone(),
                source,
            }
        })?;
        if observed != bootstrap.artifact_id {
            return Err(DaemonLifecycleError::Io {
                path: bootstrap.source_path.clone(),
                source: std::io::Error::other("executable changed during artifact bootstrap"),
            });
        }
        drop(source);
        Ok(bootstrap)
    }

    fn open(
        source_path: PathBuf,
        artifact_id: bcode_ipc::ArtifactId,
    ) -> Result<Self, DaemonLifecycleError> {
        let source = fs::File::open(&source_path).map_err(|source| DaemonLifecycleError::Io {
            path: source_path.clone(),
            source,
        })?;
        Ok(Self {
            artifact_id,
            source_path,
            source: Mutex::new(source),
            executable_digest: OnceLock::new(),
        })
    }

    /// Return the exact embedded artifact identity.
    #[must_use]
    pub const fn artifact_id(&self) -> &bcode_ipc::ArtifactId {
        &self.artifact_id
    }

    /// Return the pathname observed at bootstrap for diagnostics only.
    #[must_use]
    pub fn source_path(&self) -> &Path {
        &self.source_path
    }

    /// Report whether the bootstrap source path still resolves to the retained artifact bytes.
    ///
    /// Daemons are never spawned from this mutable pathname, so this is diagnostic evidence only.
    #[cfg(all(unix, test))]
    fn source_path_still_current(&self) -> bool {
        let Ok(path_metadata) = fs::metadata(&self.source_path) else {
            return false;
        };
        let Ok(source) = self.source.lock() else {
            return false;
        };
        let Ok(source_metadata) = source.metadata() else {
            return false;
        };
        drop(source);
        path_metadata.dev() == source_metadata.dev() && path_metadata.ino() == source_metadata.ino()
    }

    fn digest(&self) -> Result<String, DaemonLifecycleError> {
        if let Some(digest) = self.executable_digest.get() {
            return Ok(digest.clone());
        }
        let mut source = self.source.lock().map_err(|_| DaemonLifecycleError::Io {
            path: self.source_path.clone(),
            source: std::io::Error::other("artifact bootstrap lock poisoned"),
        })?;
        source.rewind().map_err(|error| DaemonLifecycleError::Io {
            path: self.source_path.clone(),
            source: error,
        })?;
        let digest = sha256_reader(&mut *source, &self.source_path)?;
        drop(source);
        let _ = self.executable_digest.set(digest.clone());
        Ok(digest)
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    fn clone_to(&self, target: &Path) -> Result<bool, DaemonLifecycleError> {
        let source = self.source.lock().map_err(|_| DaemonLifecycleError::Io {
            path: self.source_path.clone(),
            source: std::io::Error::other("artifact bootstrap lock poisoned"),
        })?;
        try_clone_file_from_handle(&source, target).map_err(|source| DaemonLifecycleError::Io {
            path: target.to_path_buf(),
            source,
        })
    }

    fn copy_to(&self, target: &Path) -> Result<String, DaemonLifecycleError> {
        let mut source = self.source.lock().map_err(|_| DaemonLifecycleError::Io {
            path: self.source_path.clone(),
            source: std::io::Error::other("artifact bootstrap lock poisoned"),
        })?;
        source.rewind().map_err(|error| DaemonLifecycleError::Io {
            path: self.source_path.clone(),
            source: error,
        })?;
        let mut output = fs::File::create(target).map_err(|source| DaemonLifecycleError::Io {
            path: target.to_path_buf(),
            source,
        })?;
        let mut hasher = Sha256::new();
        let mut buffer = vec![0_u8; 1024 * 1024].into_boxed_slice();
        loop {
            let read = source
                .read(&mut buffer)
                .map_err(|source| DaemonLifecycleError::Io {
                    path: self.source_path.clone(),
                    source,
                })?;
            if read == 0 {
                break;
            }
            output
                .write_all(&buffer[..read])
                .map_err(|source| DaemonLifecycleError::Io {
                    path: target.to_path_buf(),
                    source,
                })?;
            hasher.update(&buffer[..read]);
        }
        drop(source);
        output
            .sync_all()
            .map_err(|source| DaemonLifecycleError::Io {
                path: target.to_path_buf(),
                source,
            })?;
        let digest = hex::encode(hasher.finalize());
        let _ = self.executable_digest.set(digest.clone());
        Ok(digest)
    }
}

#[cfg(target_os = "macos")]
fn try_clone_file_from_handle(source: &fs::File, target: &Path) -> std::io::Result<bool> {
    let target = std::ffi::CString::new(target.as_os_str().as_bytes())
        .map_err(|_| std::io::Error::new(std::io::ErrorKind::InvalidInput, "NUL in image path"))?;
    // SAFETY: `source` remains open for the call and `target` is a valid NUL-terminated path.
    let result =
        unsafe { libc::fclonefileat(source.as_raw_fd(), libc::AT_FDCWD, target.as_ptr(), 0) };
    if result == 0 {
        return Ok(true);
    }
    let error = std::io::Error::last_os_error();
    if error
        .raw_os_error()
        .is_some_and(|code| [libc::ENOTSUP, libc::EXDEV, libc::EINVAL].contains(&code))
    {
        return Ok(false);
    }
    Err(error)
}

#[cfg(target_os = "linux")]
fn try_clone_file_from_handle(source: &fs::File, target: &Path) -> std::io::Result<bool> {
    let output = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(target)?;
    // SAFETY: both file descriptors remain valid for the duration of the ioctl call.
    let result = unsafe { libc::ioctl(output.as_raw_fd(), libc::FICLONE, source.as_raw_fd()) };
    if result == 0 {
        return Ok(true);
    }
    let error = std::io::Error::last_os_error();
    drop(output);
    let _ = fs::remove_file(target);
    if error.raw_os_error().is_some_and(|code| {
        [libc::ENOTTY, libc::EOPNOTSUPP, libc::EXDEV, libc::EINVAL].contains(&code)
    }) {
        return Ok(false);
    }
    Err(error)
}

fn sha256_reader(mut reader: impl Read, path: &Path) -> Result<String, DaemonLifecycleError> {
    let mut hasher = Sha256::new();
    let mut buffer = vec![0_u8; 1024 * 1024].into_boxed_slice();
    loop {
        let read = reader
            .read(&mut buffer)
            .map_err(|source| DaemonLifecycleError::Io {
                path: path.to_path_buf(),
                source,
            })?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(hex::encode(hasher.finalize()))
}

/// Return the immutable cached executable path for one binary digest.
#[must_use]
pub fn cached_daemon_executable_path_for_digest(
    state_dir: &Path,
    executable_digest: &str,
) -> PathBuf {
    daemon_image_dir(state_dir)
        .join(executable_digest)
        .join(if cfg!(windows) { "bcode.exe" } else { "bcode" })
}

/// Return the cached executable path for the current process image.
///
/// # Errors
///
/// Returns an error when the current executable cannot be located or read.
pub fn current_cached_daemon_executable_path(
    state_dir: &Path,
) -> Result<PathBuf, DaemonLifecycleError> {
    let bootstrap = initialize_artifact_bootstrap()?;
    let digest = bootstrap.digest()?;
    Ok(cached_daemon_executable_path_for_digest(state_dir, &digest))
}

/// Return the lowercase SHA-256 digest of a file.
///
/// # Errors
///
/// Returns an error when the file cannot be opened or read.
pub fn executable_sha256(path: &Path) -> Result<String, DaemonLifecycleError> {
    let mut file = fs::File::open(path).map_err(|source| DaemonLifecycleError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    sha256_reader(&mut file, path)
}

/// Return the current process executable and its byte digest.
///
/// # Errors
///
/// Returns an error when the executable cannot be located or read.
pub fn current_executable_identity() -> Result<(PathBuf, String), DaemonLifecycleError> {
    let bootstrap = initialize_artifact_bootstrap()?;
    Ok((bootstrap.source_path().to_path_buf(), bootstrap.digest()?))
}

fn cached_executable_digest(path: &Path) -> Option<&str> {
    path.parent()?.file_name()?.to_str()
}

/// Verify that an executable digest agrees with its content-addressed cache path.
#[must_use]
pub fn executable_path_matches_digest(path: &Path, executable_digest: &str) -> bool {
    path.parent()
        .and_then(Path::file_name)
        .and_then(|component| component.to_str())
        == Some(executable_digest)
}

fn daemon_image_metadata_path(executable: &Path) -> PathBuf {
    executable
        .parent()
        .expect("content-addressed daemon image has a parent")
        .join(DAEMON_IMAGE_METADATA_FILE)
}

fn read_daemon_image_metadata(
    executable: &Path,
) -> Result<Option<DaemonImageMetadata>, DaemonLifecycleError> {
    let metadata_path = daemon_image_metadata_path(executable);
    let contents = match fs::read(&metadata_path) {
        Ok(contents) => contents,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(source) => {
            return Err(DaemonLifecycleError::Io {
                path: metadata_path,
                source,
            });
        }
    };
    Ok(serde_json::from_slice(&contents).ok())
}

fn daemon_image_is_valid(
    executable: &Path,
    expected_digest: &str,
) -> Result<bool, DaemonLifecycleError> {
    if !executable.is_file() || executable_sha256(executable)? != expected_digest {
        return Ok(false);
    }
    let Some(metadata) = read_daemon_image_metadata(executable)? else {
        return Ok(false);
    };
    Ok(
        metadata.schema_version == DAEMON_IMAGE_METADATA_SCHEMA_VERSION
            && metadata.artifact_id == bcode_ipc::ArtifactId::current()
            && metadata.executable_digest == expected_digest,
    )
}

fn write_daemon_image_metadata(
    executable: &Path,
    digest: &str,
) -> Result<(), DaemonLifecycleError> {
    let metadata_path = daemon_image_metadata_path(executable);
    let metadata = DaemonImageMetadata {
        schema_version: DAEMON_IMAGE_METADATA_SCHEMA_VERSION,
        artifact_id: bcode_ipc::ArtifactId::current(),
        executable_digest: digest.to_owned(),
    };
    let contents = serde_json::to_vec_pretty(&metadata)?;
    fs::write(&metadata_path, contents).map_err(|source| DaemonLifecycleError::Io {
        path: metadata_path,
        source,
    })
}

fn remove_interrupted_image_publications(state_dir: &Path) -> Result<(), DaemonLifecycleError> {
    let artifact_dir = daemon_image_dir(state_dir);
    let entries = match fs::read_dir(&artifact_dir) {
        Ok(entries) => entries,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(source) => {
            return Err(DaemonLifecycleError::Io {
                path: artifact_dir,
                source,
            });
        }
    };
    for entry in entries {
        let entry = entry.map_err(|source| DaemonLifecycleError::Io {
            path: artifact_dir.clone(),
            source,
        })?;
        let path = entry.path();
        if entry
            .file_name()
            .to_string_lossy()
            .starts_with(".bcode.tmp-")
        {
            fs::remove_file(&path).map_err(|source| DaemonLifecycleError::Io { path, source })?;
            continue;
        }
        if !entry.file_type().is_ok_and(|file_type| file_type.is_dir()) {
            continue;
        }
        let child_entries = fs::read_dir(&path).map_err(|source| DaemonLifecycleError::Io {
            path: path.clone(),
            source,
        })?;
        for child in child_entries {
            let child = child.map_err(|source| DaemonLifecycleError::Io {
                path: path.clone(),
                source,
            })?;
            if child
                .file_name()
                .to_string_lossy()
                .starts_with(".bcode.tmp-")
            {
                let child_path = child.path();
                fs::remove_file(&child_path).map_err(|source| DaemonLifecycleError::Io {
                    path: child_path,
                    source,
                })?;
            }
        }
    }
    Ok(())
}

fn current_cached_daemon_image(
    state_dir: &Path,
) -> Result<Option<(PathBuf, String)>, DaemonLifecycleError> {
    let bootstrap = initialize_artifact_bootstrap()?;
    let digest = bootstrap.digest()?;
    let executable = cached_daemon_executable_path_for_digest(state_dir, &digest);
    if daemon_image_is_valid(&executable, &digest)? {
        Ok(Some((executable, digest)))
    } else {
        Ok(None)
    }
}

/// Verified immutable executable selected from the process bootstrap.
#[derive(Debug)]
pub struct PinnedBcodeExecutable {
    path: PathBuf,
    digest: String,
}

impl PinnedBcodeExecutable {
    /// Return the verified immutable launch path.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Return the startup executable's SHA-256 digest.
    #[must_use]
    pub fn digest(&self) -> &str {
        &self.digest
    }

    /// Return the embedded process artifact identity.
    #[must_use]
    pub fn artifact_id(&self) -> bcode_ipc::ArtifactId {
        bcode_ipc::ArtifactId::current()
    }
}

static PINNED_EXECUTABLE: OnceLock<PinnedBcodeExecutable> = OnceLock::new();

/// Access the process-pinned Bcode executable, never a PATH-resolved replacement.
///
/// # Panics
/// Panics only if the process-global pin disappears after initialization.
///
/// # Errors
/// Returns an error if materialization or verification fails. A missing or modified
/// published image fails closed; this accessor never selects another executable.
pub fn pinned_bcode_executable() -> Result<&'static PinnedBcodeExecutable, DaemonLifecycleError> {
    if PINNED_EXECUTABLE.get().is_none() {
        let path = ensure_current_executable_cached_in_state(&bcode_config::default_state_dir())?;
        let digest = initialize_artifact_bootstrap()?.digest()?;
        let _ = PINNED_EXECUTABLE.set(PinnedBcodeExecutable { path, digest });
    }
    let executable = PINNED_EXECUTABLE
        .get()
        .expect("pinned executable initialized");
    verify_pinned_bcode_executable(executable)?;
    Ok(executable)
}

fn verify_pinned_bcode_executable(
    executable: &PinnedBcodeExecutable,
) -> Result<(), DaemonLifecycleError> {
    if !daemon_image_is_valid(executable.path(), executable.digest())? {
        return Err(DaemonLifecycleError::Io {
            path: executable.path.clone(),
            source: std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "pinned Bcode executable is missing or modified",
            ),
        });
    }
    Ok(())
}

/// Return the immutable process-pinned executable path.
///
/// # Errors
/// Returns an error if the pinned executable cannot be materialized or verified.
pub fn ensure_current_executable_cached() -> Result<PathBuf, DaemonLifecycleError> {
    Ok(pinned_bcode_executable()?.path().to_path_buf())
}

fn materialize_verified_daemon_image(
    bootstrap: &ArtifactBootstrap,
    source: &Path,
    temp: &Path,
) -> Result<(String, bool), DaemonLifecycleError> {
    #[cfg(not(unix))]
    let _ = source;
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    let cloned = bootstrap.clone_to(temp)?;
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    let cloned = false;
    tracing::debug!(
        target: "bcode_daemon_lifecycle::startup",
        cloned,
        "daemon image clone attempted"
    );
    let verify_started_at = std::time::Instant::now();
    let digest = if cloned {
        let digest = executable_sha256(temp)?;
        fs::OpenOptions::new()
            .read(true)
            .open(temp)
            .and_then(|file| file.sync_all())
            .map_err(|source| DaemonLifecycleError::Io {
                path: temp.to_path_buf(),
                source,
            })?;
        let _ = bootstrap.executable_digest.set(digest.clone());
        digest
    } else {
        bootstrap.copy_to(temp)?
    };
    tracing::debug!(
        target: "bcode_daemon_lifecycle::startup",
        elapsed_ms = verify_started_at.elapsed().as_millis(),
        cloned,
        "daemon image bytes verified and synchronized"
    );
    #[cfg(unix)]
    preserve_executable_permissions(source, temp)?;
    Ok((digest, cloned))
}

fn ensure_current_executable_cached_in_state(
    state_dir: &Path,
) -> Result<PathBuf, DaemonLifecycleError> {
    let bootstrap = initialize_artifact_bootstrap()?;
    let source = bootstrap.source_path().to_path_buf();
    remove_interrupted_image_publications(state_dir)?;
    if let Some((target, _digest)) = current_cached_daemon_image(state_dir)?
        && target != source
    {
        return Ok(target);
    }
    let temp_parent = daemon_image_dir(state_dir);
    fs::create_dir_all(&temp_parent).map_err(|source| DaemonLifecycleError::Io {
        path: temp_parent.clone(),
        source,
    })?;
    let temp = temp_parent.join(format!(".bcode.tmp-{}", std::process::id()));
    let materialize_started_at = std::time::Instant::now();
    let (digest, cloned) = materialize_verified_daemon_image(bootstrap, &source, &temp)?;
    let target = cached_daemon_executable_path_for_digest(state_dir, &digest);
    if target == source {
        let _ = fs::remove_file(&temp);
        return Ok(target);
    }
    let parent = target
        .parent()
        .expect("content-addressed daemon image has a parent");
    fs::create_dir_all(parent).map_err(|source| DaemonLifecycleError::Io {
        path: parent.to_path_buf(),
        source,
    })?;
    if target.exists() {
        if daemon_image_is_valid(&target, &digest)? {
            let _ = fs::remove_file(&temp);
            return Ok(target);
        }
        fs::remove_file(&target).map_err(|source| DaemonLifecycleError::Io {
            path: target.clone(),
            source,
        })?;
        let metadata = daemon_image_metadata_path(&target);
        if let Err(source) = fs::remove_file(&metadata)
            && source.kind() != std::io::ErrorKind::NotFound
        {
            return Err(DaemonLifecycleError::Io {
                path: metadata,
                source,
            });
        }
    }
    match fs::rename(&temp, &target) {
        Ok(()) => {
            write_daemon_image_metadata(&target, &digest)?;
            tracing::debug!(
                target: "bcode_daemon_lifecycle::startup",
                elapsed_ms = materialize_started_at.elapsed().as_millis(),
                cloned,
                "daemon image published"
            );
            Ok(target)
        }
        Err(_source_error) if daemon_image_is_valid(&target, &digest)? => {
            let _ = fs::remove_file(&temp);
            Ok(target)
        }
        Err(source_error) => {
            let _ = fs::remove_file(&temp);
            Err(DaemonLifecycleError::Io {
                path: target,
                source: source_error,
            })
        }
    }
}

#[cfg(unix)]
fn preserve_executable_permissions(
    source: &Path,
    target: &Path,
) -> Result<(), DaemonLifecycleError> {
    let mode = fs::metadata(source)
        .map_err(|source_error| DaemonLifecycleError::Io {
            path: source.to_path_buf(),
            source: source_error,
        })?
        .permissions()
        .mode();
    let mut permissions = fs::metadata(target)
        .map_err(|source_error| DaemonLifecycleError::Io {
            path: target.to_path_buf(),
            source: source_error,
        })?
        .permissions();
    permissions.set_mode(mode | 0o700);
    fs::set_permissions(target, permissions).map_err(|source_error| DaemonLifecycleError::Io {
        path: target.to_path_buf(),
        source: source_error,
    })
}

fn daemon_image_cleanup_lock_path(state_dir: &Path) -> PathBuf {
    state_dir
        .join("daemons")
        .join(DAEMON_IMAGE_CLEANUP_LOCK_FILE)
}

fn open_daemon_image_cleanup_lock(state_dir: &Path) -> Result<fs::File, DaemonLifecycleError> {
    let path = daemon_image_cleanup_lock_path(state_dir);
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|source| DaemonLifecycleError::Io {
            path: parent.to_path_buf(),
            source,
        })?;
    }
    fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&path)
        .map_err(|source| DaemonLifecycleError::Io { path, source })
}

struct DaemonImageUseGuard {
    file: fs::File,
}

impl DaemonImageUseGuard {
    fn acquire(state_dir: &Path) -> Result<Self, DaemonLifecycleError> {
        let file = open_daemon_image_cleanup_lock(state_dir)?;
        file.lock_shared()
            .map_err(|source| DaemonLifecycleError::Io {
                path: daemon_image_cleanup_lock_path(state_dir),
                source,
            })?;
        Ok(Self { file })
    }
}

impl Drop for DaemonImageUseGuard {
    fn drop(&mut self) {
        let _ = self.file.unlock();
    }
}

struct DaemonImageCleanupGuard {
    file: fs::File,
}

impl Drop for DaemonImageCleanupGuard {
    fn drop(&mut self) {
        // Closing alone can leave the lock held by a duplicated/inherited handle.
        let _ = self.file.unlock();
    }
}

fn try_acquire_daemon_image_cleanup_lock(
    state_dir: &Path,
) -> Result<Option<DaemonImageCleanupGuard>, DaemonLifecycleError> {
    let file = open_daemon_image_cleanup_lock(state_dir)?;
    match file.try_lock() {
        Ok(()) => Ok(Some(DaemonImageCleanupGuard { file })),
        Err(std::fs::TryLockError::WouldBlock) => Ok(None),
        Err(std::fs::TryLockError::Error(source)) => Err(DaemonLifecycleError::Io {
            path: daemon_image_cleanup_lock_path(state_dir),
            source,
        }),
    }
}

fn retained_daemon_image_paths(
    state_dir: &Path,
) -> Result<(std::collections::BTreeSet<PathBuf>, bool), DaemonLifecycleError> {
    let registry = registry_dir(state_dir);
    let entries = match fs::read_dir(&registry) {
        Ok(entries) => entries,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
            return Ok((std::collections::BTreeSet::new(), false));
        }
        Err(source) => {
            return Err(DaemonLifecycleError::Io {
                path: registry,
                source,
            });
        }
    };
    let mut retained = std::collections::BTreeSet::new();
    let mut ambiguous_record_evidence = false;
    for entry in entries {
        let entry = entry.map_err(|source| DaemonLifecycleError::Io {
            path: registry.clone(),
            source,
        })?;
        let path = entry.path();
        if path.extension().and_then(|extension| extension.to_str()) != Some("json") {
            continue;
        }
        let contents = fs::read(&path).map_err(|source| DaemonLifecycleError::Io {
            path: path.clone(),
            source,
        })?;
        let Ok(record) = serde_json::from_slice::<DaemonRecord>(&contents) else {
            ambiguous_record_evidence = true;
            continue;
        };
        if !(1..=DAEMON_RECORD_SCHEMA_VERSION).contains(&record.schema_version) {
            ambiguous_record_evidence = true;
            continue;
        }
        if let Some(executable_path) = record.executable_path {
            retained.insert(executable_path);
        }
    }
    Ok((retained, ambiguous_record_evidence))
}

/// Remove cached daemon images that are not referenced by daemon records or the current build.
///
/// Cleanup fails closed when any registry record is malformed or has an unknown schema because
/// that record may contain image-retention evidence this build cannot safely interpret.
///
/// # Errors
///
/// Returns an error when reading registry evidence or removing image directories fails.
pub fn cleanup_stale_daemon_images(state_dir: &Path) -> Result<usize, DaemonLifecycleError> {
    cleanup_stale_daemon_images_retaining_artifacts(state_dir, &std::collections::BTreeSet::new())
}

/// Remove cached daemon images, preserving images for artifacts callers still require.
///
/// `retained_artifact_ids` names artifact identities that must keep their cached images even
/// without a live daemon record. Execution authority for durable work is fenced to an exact
/// artifact identity, so deleting that artifact's image would permanently strand the work: no
/// other artifact may legitimately claim ownership, and the owning artifact can no longer be
/// launched. Retaining the image keeps a matching daemon startable so recovery stays possible.
///
/// Cleanup fails closed when any registry record is malformed or has an unknown schema because
/// that record may contain image-retention evidence this build cannot safely interpret.
///
/// # Errors
///
/// Returns an error when reading registry evidence or removing image directories fails.
pub fn cleanup_stale_daemon_images_retaining_artifacts(
    state_dir: &Path,
    retained_artifact_ids: &std::collections::BTreeSet<String>,
) -> Result<usize, DaemonLifecycleError> {
    let Some(_cleanup_lock) = try_acquire_daemon_image_cleanup_lock(state_dir)? else {
        return Ok(0);
    };
    let root = state_dir.join("daemon-images");
    let namespace_entries = match fs::read_dir(&root) {
        Ok(entries) => entries,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(0),
        Err(source) => return Err(DaemonLifecycleError::Io { path: root, source }),
    };
    let (mut retained, ambiguous_record_evidence) = retained_daemon_image_paths(state_dir)?;
    if ambiguous_record_evidence {
        return Ok(0);
    }
    retained.insert(current_cached_daemon_executable_path(state_dir)?);
    let mut removed = 0;
    for namespace_entry in namespace_entries.flatten() {
        if !namespace_entry
            .file_type()
            .is_ok_and(|file_type| file_type.is_dir())
        {
            continue;
        }
        // The namespace directory name is the artifact identity that owns these images. Durable
        // work fenced to this artifact keeps every image under it, because recovery requires
        // launching a daemon of exactly this identity.
        if namespace_entry
            .file_name()
            .to_str()
            .is_some_and(|artifact_id| retained_artifact_ids.contains(artifact_id))
        {
            continue;
        }
        let Ok(image_entries) = fs::read_dir(namespace_entry.path()) else {
            continue;
        };
        for image_entry in image_entries.flatten() {
            let path = image_entry.path();
            let candidate = if image_entry
                .file_type()
                .is_ok_and(|file_type| file_type.is_dir())
            {
                path.join(if cfg!(windows) { "bcode.exe" } else { "bcode" })
            } else {
                path.clone()
            };
            if retained.contains(&candidate) {
                continue;
            }
            if image_entry
                .file_type()
                .is_ok_and(|file_type| file_type.is_dir())
            {
                fs::remove_dir_all(&path)
            } else {
                fs::remove_file(&path)
            }
            .map_err(|source| DaemonLifecycleError::Io {
                path: path.clone(),
                source,
            })?;
            removed += 1;
        }
        if fs::read_dir(namespace_entry.path()).is_ok_and(|mut entries| entries.next().is_none()) {
            let _ = fs::remove_dir(namespace_entry.path());
        }
    }
    Ok(removed)
}

/// Return Unix time in milliseconds.
///
/// # Errors
///
/// Returns an error when the system clock is before the Unix epoch.
pub fn unix_time_millis() -> Result<u64, DaemonLifecycleError> {
    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_err(|_| DaemonLifecycleError::Clock)?;
    Ok(duration.as_millis().try_into().unwrap_or(u64::MAX))
}

fn endpoint_record(endpoint: &IpcEndpoint) -> DaemonEndpointRecord {
    if let Some(path) = endpoint.as_unix_socket() {
        return DaemonEndpointRecord::UnixSocket {
            path: path.to_path_buf(),
        };
    }
    if let Some(name) = endpoint.as_windows_named_pipe() {
        return DaemonEndpointRecord::WindowsNamedPipe {
            name: name.to_owned(),
        };
    }
    DaemonEndpointRecord::Unknown {
        debug: format!("{endpoint:?}"),
    }
}

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

    #[test]
    fn strict_inventory_accepts_coordination_locks_but_rejects_unknown_files() {
        let root = tempfile::tempdir().unwrap();
        let directory = registry_dir(root.path());
        fs::create_dir(&directory).unwrap();
        let record = record_with_writer_epoch(Some(10));
        fs::write(
            directory.join("test.json"),
            serde_json::to_vec(&record).unwrap(),
        )
        .unwrap();
        fs::write(directory.join("daemon-images.lock"), b"").unwrap();
        fs::write(directory.join("ipc-v49-fixture.lock"), b"1234").unwrap();
        assert_eq!(read_records_strict(root.path(), 16).unwrap(), vec![record]);
        assert!(read_records_strict(root.path(), 2).is_err());
        fs::write(directory.join("unexpected"), b"").unwrap();
        assert!(read_records_strict(root.path(), 16).is_err());
    }

    #[test]
    fn registry_preserves_distinct_config_scopes_in_one_state_root() {
        let directory = tempfile::tempdir().unwrap();
        let mut first = record_with_writer_epoch(Some(10));
        first.state_location_id = Some("scope-a".into());
        first.instance_id = "instance-a".into();
        let mut second = first.clone();
        second.state_location_id = Some("scope-b".into());
        second.instance_id = "instance-b".into();
        let first_path = write_record(directory.path(), &first).unwrap();
        let second_path = write_record(directory.path(), &second).unwrap();
        assert_ne!(first_path, second_path);
        assert_eq!(read_records_strict(directory.path(), 16).unwrap().len(), 2);
        remove_record_path(&first_path).unwrap();
        assert_eq!(
            read_records_strict(directory.path(), 16).unwrap(),
            vec![second]
        );
    }

    #[test]
    fn strict_inventory_never_converts_damage_or_partial_scans_to_absence() {
        let root = tempfile::tempdir().expect("root");
        assert!(read_records_strict(root.path(), 16).is_err());
        let directory = registry_dir(root.path());
        fs::create_dir(&directory).expect("registry");
        assert!(
            read_records_strict(root.path(), 16)
                .expect("empty")
                .is_empty()
        );
        let record = record_with_writer_epoch(Some(10));
        fs::write(
            directory.join("test.json"),
            serde_json::to_vec(&record).expect("json"),
        )
        .expect("record");
        assert_eq!(
            read_records_strict(root.path(), 1).expect("record"),
            vec![record]
        );
        fs::write(directory.join("broken.json"), b"broken").expect("broken");
        assert!(read_records_strict(root.path(), 16).is_err());
        assert!(read_records_strict(root.path(), 1).is_err());
        assert_eq!(
            read_records(root.path()).len(),
            1,
            "best-effort cleanup remains separate"
        );
        fs::remove_file(directory.join("broken.json")).expect("fixture cleanup");
        let mut future = record_with_writer_epoch(Some(10));
        future.schema_version += 1;
        fs::write(
            directory.join("test.json"),
            serde_json::to_vec(&future).expect("json"),
        )
        .expect("future");
        assert!(read_records_strict(root.path(), 16).is_err());
    }

    #[test]
    fn strict_inventory_rejects_duplicate_instances_and_oversized_records() {
        let root = tempfile::tempdir().expect("root");
        let directory = registry_dir(root.path());
        fs::create_dir(&directory).expect("registry");
        let first = record_with_writer_epoch(Some(10));
        let mut second = first.clone();
        second.namespace = "other".into();
        fs::write(
            directory.join("test.json"),
            serde_json::to_vec(&first).expect("json"),
        )
        .expect("first");
        fs::write(
            directory.join("other.json"),
            serde_json::to_vec(&second).expect("json"),
        )
        .expect("duplicate");
        assert!(read_records_strict(root.path(), 16).is_err());
        fs::remove_file(directory.join("other.json")).expect("fixture cleanup");
        fs::write(directory.join("test.json"), vec![b' '; 65537]).expect("oversized");
        assert!(read_records_strict(root.path(), 16).is_err());
    }

    fn record_with_writer_epoch(storage_writer_epoch: Option<u32>) -> DaemonRecord {
        DaemonRecord {
            schema_version: DAEMON_RECORD_SCHEMA_VERSION,
            namespace: "test".to_string(),
            protocol_version: u32::from(CURRENT_PROTOCOL_VERSION),
            artifact_id: Some(bcode_ipc::ArtifactId::current()),
            build_fingerprint: "test-build".to_string(),
            storage_writer_epoch,
            state_location_id: Some(bcode_ipc::state_location_id()),
            pid: Some(std::process::id()),
            endpoint: DaemonEndpointRecord::Unknown {
                debug: "test".to_string(),
            },
            log_path: PathBuf::from("test.log"),
            executable_path: None,
            executable_digest: None,
            started_at_unix_ms: 0,
            last_seen_unix_ms: 0,
            instance_id: "test-instance".to_string(),
        }
    }

    fn stale_image_path(state_dir: &Path, namespace: &str, digest: &str) -> PathBuf {
        state_dir
            .join("daemon-images")
            .join(namespace)
            .join(digest)
            .join(if cfg!(windows) { "bcode.exe" } else { "bcode" })
    }

    fn write_test_image(path: &Path) {
        fs::create_dir_all(path.parent().expect("image parent")).expect("image directory");
        fs::write(path, b"stale daemon image").expect("image");
    }

    #[test]
    fn executable_digest_preserves_standard_sha256_encoding() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("fixture");
        for (bytes, expected) in [
            (
                b"".as_slice(),
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            ),
            (
                b"abc".as_slice(),
                "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
            ),
        ] {
            fs::write(&path, bytes).unwrap();
            assert_eq!(executable_sha256(&path).unwrap(), expected);
        }
    }

    #[test]
    fn readiness_identity_requires_pinned_executable_digest() {
        let matching = bcode_ipc::DaemonStatus {
            namespace: daemon_namespace(),
            protocol_version: u32::from(CURRENT_PROTOCOL_VERSION),
            artifact_id: Some(bcode_ipc::ArtifactId::current()),
            build_fingerprint: BUILD_FINGERPRINT.to_owned(),
            executable_digest: Some(initialize_artifact_bootstrap().unwrap().digest().unwrap()),
            storage_writer_epoch: Some(bcode_ipc::CURRENT_SESSION_STORAGE_WRITER_EPOCH),
            session_event_schema_version: Some(
                bcode_session_models::CURRENT_SESSION_EVENT_SCHEMA_VERSION,
            ),
            ..bcode_ipc::DaemonStatus::default()
        };
        assert!(daemon_status_matches_current_executable(&matching));
        assert!(!daemon_status_matches_current_executable(
            &bcode_ipc::DaemonStatus {
                executable_digest: Some("different-bytes".into()),
                ..matching.clone()
            }
        ));
        assert!(!daemon_status_matches_current_executable(
            &bcode_ipc::DaemonStatus {
                storage_writer_epoch: matching.storage_writer_epoch.map(|epoch| epoch + 1),
                ..matching.clone()
            }
        ));
        assert!(!daemon_status_matches_current_executable(
            &bcode_ipc::DaemonStatus {
                session_event_schema_version: matching
                    .session_event_schema_version
                    .map(|schema| schema + 1),
                ..matching
            }
        ));
    }

    #[test]
    fn daemon_image_cleanup_releases_lock_with_a_duplicated_handle() {
        let state_dir = std::env::temp_dir().join(format!(
            "bcode-daemon-image-cleanup-release-test-{}-{}",
            std::process::id(),
            unix_time_millis().expect("time")
        ));
        let guard = try_acquire_daemon_image_cleanup_lock(&state_dir)
            .expect("lock")
            .expect("acquired");
        let duplicate = guard.file.try_clone().expect("duplicate handle");
        assert!(
            try_acquire_daemon_image_cleanup_lock(&state_dir)
                .expect("contended lock")
                .is_none()
        );
        drop(guard);
        let next = try_acquire_daemon_image_cleanup_lock(&state_dir)
            .expect("released lock")
            .expect("reacquired despite duplicate");
        drop(next);
        drop(duplicate);
        fs::remove_dir_all(state_dir).expect("state cleanup");
    }

    #[test]
    fn daemon_image_cleanup_skips_while_any_artifact_start_uses_images() {
        let state_dir = std::env::temp_dir().join(format!(
            "bcode-daemon-image-use-lock-test-{}-{}",
            std::process::id(),
            unix_time_millis().expect("time")
        ));
        let stale_image = stale_image_path(&state_dir, "historical", "in-use");
        write_test_image(&stale_image);
        let use_guard = DaemonImageUseGuard::acquire(&state_dir).expect("image use guard");

        assert_eq!(cleanup_stale_daemon_images(&state_dir).expect("cleanup"), 0);
        assert!(stale_image.exists());

        drop(use_guard);
        assert_eq!(cleanup_stale_daemon_images(&state_dir).expect("cleanup"), 1);
        assert!(!stale_image.exists());
        fs::remove_dir_all(state_dir).expect("state cleanup");
    }

    #[test]
    fn daemon_image_cleanup_retains_images_for_artifacts_owning_durable_work() {
        let state_dir = std::env::temp_dir().join(format!(
            "bcode-daemon-image-retention-test-{}-{}",
            std::process::id(),
            unix_time_millis().expect("time")
        ));
        let fenced_image = stale_image_path(&state_dir, "artifact-with-work", "digest");
        let unreferenced_image = stale_image_path(&state_dir, "artifact-without-work", "digest");
        write_test_image(&fenced_image);
        write_test_image(&unreferenced_image);

        let retained = std::collections::BTreeSet::from(["artifact-with-work".to_owned()]);
        assert_eq!(
            cleanup_stale_daemon_images_retaining_artifacts(&state_dir, &retained)
                .expect("cleanup"),
            1
        );
        // Deleting this image would strand the fenced work permanently.
        assert!(fenced_image.exists());
        assert!(!unreferenced_image.exists());
        assert!(artifact_image_is_available(
            &state_dir,
            "artifact-with-work"
        ));
        assert!(!artifact_image_is_available(
            &state_dir,
            "artifact-without-work"
        ));

        // Once the work no longer requires the artifact, its image becomes collectable.
        assert_eq!(
            cleanup_stale_daemon_images_retaining_artifacts(
                &state_dir,
                &std::collections::BTreeSet::new()
            )
            .expect("cleanup"),
            1
        );
        assert!(!fenced_image.exists());
        fs::remove_dir_all(state_dir).expect("state cleanup");
    }

    #[test]
    fn registered_retained_artifact_providers_contribute_retention_evidence() {
        fn provider() -> std::collections::BTreeSet<String> {
            std::collections::BTreeSet::from(["provider-artifact".to_owned()])
        }

        register_retained_artifact_provider(provider);

        assert!(registered_retained_artifact_ids().contains("provider-artifact"));
    }

    #[test]
    fn daemon_image_cleanup_retains_record_references_and_removes_only_unreferenced_images() {
        let state_dir = std::env::temp_dir().join(format!(
            "bcode-daemon-image-cleanup-test-{}-{}",
            std::process::id(),
            unix_time_millis().expect("time")
        ));
        let retained_image = stale_image_path(&state_dir, "historical", "retained");
        let stale_image = stale_image_path(&state_dir, "historical", "stale");
        write_test_image(&retained_image);
        write_test_image(&stale_image);
        let record = DaemonRecord {
            namespace: "historical-cleanup-record".to_owned(),
            executable_path: Some(retained_image.clone()),
            ..record_with_writer_epoch(Some(2))
        };
        let record_path = write_record(&state_dir, &record).expect("record");

        assert_eq!(cleanup_stale_daemon_images(&state_dir).expect("cleanup"), 1);
        assert!(retained_image.exists());
        assert!(!stale_image.exists());

        remove_record_path(&record_path).expect("remove record");
        assert_eq!(cleanup_stale_daemon_images(&state_dir).expect("cleanup"), 1);
        assert!(!retained_image.exists());
        fs::remove_dir_all(state_dir).expect("state cleanup");
    }

    #[test]
    fn daemon_image_cleanup_fails_closed_for_ambiguous_registry_evidence() {
        for (case, contents) in [
            ("malformed", b"not valid json".to_vec()),
            (
                "future-schema",
                serde_json::to_vec(&DaemonRecord {
                    schema_version: DAEMON_RECORD_SCHEMA_VERSION + 1,
                    namespace: "future-record".to_owned(),
                    ..record_with_writer_epoch(Some(2))
                })
                .expect("future record"),
            ),
        ] {
            let state_dir = std::env::temp_dir().join(format!(
                "bcode-daemon-image-ambiguous-{case}-{}-{}",
                std::process::id(),
                unix_time_millis().expect("time")
            ));
            let stale_image = stale_image_path(&state_dir, "historical", "ambiguous");
            write_test_image(&stale_image);
            let registry = registry_dir(&state_dir);
            fs::create_dir_all(&registry).expect("registry");
            fs::write(registry.join("ambiguous.json"), contents).expect("ambiguous record");

            assert_eq!(cleanup_stale_daemon_images(&state_dir).expect("cleanup"), 0);
            assert!(stale_image.exists());
            fs::remove_dir_all(state_dir).expect("state cleanup");
        }
    }

    #[test]
    fn current_process_identity_evidence_rejects_pid_reuse_and_accepts_exact_record() {
        let (executable_path, executable_digest) = current_executable_identity().expect("identity");
        let mut system = System::new();
        let pid = Pid::from_u32(std::process::id());
        system.refresh_processes(ProcessesToUpdate::Some(&[pid]), true);
        let process = system.process(pid).expect("current process");
        let record = DaemonRecord {
            pid: Some(std::process::id()),
            executable_path: Some(executable_path),
            executable_digest: Some(executable_digest),
            started_at_unix_ms: process.start_time().saturating_mul(1_000),
            ..record_with_writer_epoch(Some(2))
        };
        assert_eq!(
            process_identity_evidence(&record),
            ProcessIdentityEvidence::Exact
        );
        assert_eq!(
            process_identity_evidence(&DaemonRecord {
                started_at_unix_ms: record.started_at_unix_ms.saturating_add(1_000),
                ..record.clone()
            }),
            ProcessIdentityEvidence::MissingOrReused
        );
        // The test binary runs from a mutable pathname, so a digest mismatch is ambiguous and
        // must not be reported as positive PID-reuse evidence.
        assert_eq!(
            process_identity_evidence(&DaemonRecord {
                executable_digest: Some("reused-image".to_owned()),
                ..record
            }),
            ProcessIdentityEvidence::Unverifiable
        );
    }

    #[test]
    fn rebuilt_mutable_executable_path_is_ambiguous_and_preserves_the_record() {
        // A rebuilt source path must never be classified as stale while the daemon still answers,
        // so a live daemon spawned from `target/` keeps serving its own artifact after a rebuild.
        let current = DaemonRecord {
            namespace: bcode_ipc::daemon_namespace(),
            ..record_with_writer_epoch(Some(2))
        };
        assert_eq!(
            classify_daemon_record_evidence(
                &current,
                None,
                true,
                ProcessIdentityEvidence::Unverifiable,
            ),
            DaemonRecordClassification::Unverifiable
        );
        assert_eq!(
            classify_daemon_record_evidence(
                &current,
                None,
                false,
                ProcessIdentityEvidence::Unverifiable,
            ),
            DaemonRecordClassification::Unverifiable
        );
    }

    #[test]
    fn stale_plugin_state_cleanup_is_namespace_confined_and_symlink_safe() {
        let state = tempfile::tempdir().expect("state");
        let plugins = state.path().join("derived/plugins");
        let stale_root = plugins.join("ipc-v1-stale");
        let retained = plugins.join("ipc-v1-retained");
        fs::create_dir_all(&stale_root).expect("stale state");
        fs::create_dir_all(&retained).expect("retained state");
        fs::write(stale_root.join("provider.json"), b"derived").expect("provider state");

        remove_stale_plugin_state(state.path(), "ipc-v1-stale").expect("cleanup stale state");
        assert!(!stale_root.exists());
        assert!(retained.exists());
        remove_stale_plugin_state(state.path(), "../ipc-v1-retained")
            .expect("reject hostile namespace");
        assert!(retained.exists());

        #[cfg(unix)]
        {
            use std::os::unix::fs::symlink;
            let external = tempfile::tempdir().expect("external");
            let link = plugins.join("ipc-v1-link");
            symlink(external.path(), &link).expect("namespace symlink");
            remove_stale_plugin_state(state.path(), "ipc-v1-link")
                .expect("symlink cleanup fails closed");
            assert!(link.exists());
            assert!(external.path().exists());
        }
    }

    #[test]
    fn daemon_launch_preserves_exclusive_config_as_one_argument() {
        let mut command = tokio::process::Command::new("bcode");
        let path = Path::new("trusted directory/config ; $(ignored).toml");
        super::configure_daemon_config(&mut command, Some(path));
        command.args(["server", "run"]);
        let args: Vec<_> = command.as_std().get_args().collect();
        assert_eq!(
            args,
            vec![
                std::ffi::OsStr::new("--config-only"),
                path.as_os_str(),
                std::ffi::OsStr::new("server"),
                std::ffi::OsStr::new("run"),
            ]
        );
        let mut ordinary = tokio::process::Command::new("bcode");
        super::configure_daemon_config(&mut ordinary, None);
        assert_eq!(ordinary.as_std().get_args().count(), 0);
    }

    #[test]
    fn daemon_config_home_reproduces_the_resolved_config_directory() {
        // A spawned daemon resolves `<XDG_CONFIG_HOME>/bcode`, so the parent must be
        // passed for the child to land on the same directory the client resolved.
        assert_eq!(
            super::config_home_for_daemon(Path::new("/home/user/.config/bcode")),
            PathBuf::from("/home/user/.config")
        );
        assert_eq!(
            super::config_home_for_daemon(Path::new("/opt/custom/bcode")),
            PathBuf::from("/opt/custom")
        );
        // A directory that is not the expected `bcode` leaf is passed through rather
        // than guessed, so a mismatch surfaces at the handshake instead of silently
        // redirecting the daemon's config.
        assert_eq!(
            super::config_home_for_daemon(Path::new("/tmp/unexpected")),
            PathBuf::from("/tmp/unexpected")
        );
    }

    #[test]
    fn daemon_record_identity_fields_are_independently_validated() {
        let record = record_with_writer_epoch(Some(2));
        let exact = bcode_ipc::DaemonStatus {
            namespace: record.namespace.clone(),
            protocol_version: record.protocol_version,
            artifact_id: record.artifact_id.clone(),
            build_fingerprint: record.build_fingerprint.clone(),
            executable_digest: record.executable_digest.clone(),
            storage_writer_epoch: record.storage_writer_epoch,
            state_location_id: record.state_location_id.clone(),
            session_event_schema_version: None,
            pid: record.pid,
            instance_id: record.instance_id.clone(),
            started_at_unix_ms: record.started_at_unix_ms,
        };
        assert!(daemon_status_matches_record(&record, &exact));

        let cases = [
            bcode_ipc::DaemonStatus {
                instance_id: "other-instance".to_owned(),
                ..exact.clone()
            },
            bcode_ipc::DaemonStatus {
                namespace: "other-namespace".to_owned(),
                ..exact.clone()
            },
            bcode_ipc::DaemonStatus {
                protocol_version: exact.protocol_version.saturating_add(1),
                ..exact.clone()
            },
            bcode_ipc::DaemonStatus {
                artifact_id: Some(
                    bcode_ipc::ArtifactId::parse("other-artifact")
                        .expect("other artifact identity"),
                ),
                ..exact.clone()
            },
            bcode_ipc::DaemonStatus {
                build_fingerprint: "other-build".to_owned(),
                ..exact.clone()
            },
            bcode_ipc::DaemonStatus {
                executable_digest: Some("other-digest".to_owned()),
                ..exact.clone()
            },
            bcode_ipc::DaemonStatus {
                storage_writer_epoch: exact.storage_writer_epoch.map(|epoch| epoch + 1),
                ..exact.clone()
            },
            bcode_ipc::DaemonStatus {
                pid: exact.pid.map(|pid| pid.saturating_add(1)),
                ..exact.clone()
            },
            bcode_ipc::DaemonStatus {
                started_at_unix_ms: exact.started_at_unix_ms.saturating_add(1),
                ..exact
            },
        ];
        for status in cases {
            assert!(!daemon_status_matches_record(&record, &status));
        }
    }

    #[test]
    fn daemon_record_classification_preserves_historical_and_ambiguous_evidence() {
        let current = record_with_writer_epoch(Some(2));
        let exact = bcode_ipc::DaemonStatus {
            namespace: current.namespace.clone(),
            protocol_version: current.protocol_version,
            artifact_id: current.artifact_id.clone(),
            build_fingerprint: current.build_fingerprint.clone(),
            executable_digest: current.executable_digest.clone(),
            storage_writer_epoch: current.storage_writer_epoch,
            state_location_id: current.state_location_id.clone(),
            session_event_schema_version: None,
            pid: current.pid,
            instance_id: current.instance_id.clone(),
            started_at_unix_ms: current.started_at_unix_ms,
        };
        assert_eq!(
            classify_daemon_record_evidence(
                &current,
                Some(&exact),
                true,
                ProcessIdentityEvidence::Exact,
            ),
            DaemonRecordClassification::HistoricalExactResponsive
        );
        assert_eq!(
            classify_daemon_record_evidence(&current, None, true, ProcessIdentityEvidence::Exact,),
            DaemonRecordClassification::HistoricalProcessVerifiedProtocolUnsupported
        );
        assert_eq!(
            classify_daemon_record_evidence(
                &current,
                Some(&bcode_ipc::DaemonStatus {
                    instance_id: "replacement".to_owned(),
                    ..exact
                }),
                true,
                ProcessIdentityEvidence::MissingOrReused,
            ),
            DaemonRecordClassification::ResponsiveIdentityMismatch
        );
        assert_eq!(
            classify_daemon_record_evidence(
                &current,
                None,
                false,
                ProcessIdentityEvidence::MissingOrReused,
            ),
            DaemonRecordClassification::UnreachableStale
        );
        assert_eq!(
            classify_daemon_record_evidence(
                &current,
                None,
                false,
                ProcessIdentityEvidence::Unverifiable,
            ),
            DaemonRecordClassification::Unverifiable
        );
    }

    #[test]
    fn storage_writer_compatibility_fails_closed_for_legacy_records() {
        assert!(storage_writer_is_incompatible(
            &record_with_writer_epoch(None),
            2
        ));
        assert!(storage_writer_is_incompatible(
            &record_with_writer_epoch(Some(1)),
            2
        ));
        assert!(!storage_writer_is_incompatible(
            &record_with_writer_epoch(Some(2)),
            2
        ));
    }

    #[test]
    fn daemon_record_accepts_verified_executable_outside_cache() {
        let (executable_path, digest) = current_executable_identity().unwrap();
        let record = DaemonRecord::current(
            &bcode_ipc::default_endpoint(),
            PathBuf::from("test.log"),
            Some(executable_path.clone()),
            "foreground-test".to_string(),
        )
        .unwrap();

        assert_eq!(
            record.executable_path.as_deref(),
            Some(executable_path.as_path())
        );
        assert_eq!(record.executable_digest.as_deref(), Some(digest.as_str()));
    }

    #[test]
    fn cached_daemon_executable_path_is_content_addressed() {
        assert_eq!(
            cached_daemon_executable_path_for_digest(Path::new("/state"), "abc123"),
            Path::new("/state")
                .join("daemon-images")
                .join(bcode_ipc::ArtifactId::current().as_str())
                .join("abc123")
                .join(if cfg!(windows) { "bcode.exe" } else { "bcode" })
        );
    }

    #[test]
    fn bootstrap_rejects_identity_from_different_executable_bytes() {
        let root = std::env::temp_dir().join(format!(
            "bcode-bootstrap-identity-{}-{}",
            std::process::id(),
            unix_time_millis().unwrap()
        ));
        fs::create_dir_all(&root).unwrap();
        let path = root.join("bcode");
        fs::write(&path, b"retained bytes").unwrap();
        let identity =
            bcode_ipc::ArtifactId::for_executable(&mut b"retained bytes".as_slice()).unwrap();
        let bootstrap = ArtifactBootstrap::open_verified(path.clone(), identity.clone()).unwrap();
        assert_eq!(bootstrap.artifact_id(), &identity);
        assert_eq!(
            bootstrap.digest().unwrap(),
            executable_sha256(&path).unwrap()
        );
        let foreign = bcode_ipc::ArtifactId::parse("foreign-bootstrap-identity").unwrap();
        assert!(ArtifactBootstrap::open_verified(path, foreign).is_err());
        fs::remove_dir_all(root).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn retained_artifact_handle_survives_source_path_replacement() {
        let root = std::env::temp_dir().join(format!(
            "bcode-retained-artifact-test-{}-{}",
            std::process::id(),
            unix_time_millis().unwrap()
        ));
        fs::create_dir_all(&root).unwrap();
        let source = root.join("bcode");
        fs::write(&source, b"original artifact bytes").unwrap();
        let bootstrap = ArtifactBootstrap::open(
            source.clone(),
            bcode_ipc::ArtifactId::parse("retained-test").unwrap(),
        )
        .unwrap();
        let original_digest = bootstrap.digest().unwrap();
        assert!(bootstrap.source_path_still_current());
        let replacement = root.join("replacement");
        fs::write(&replacement, b"replacement bytes").unwrap();
        fs::rename(&replacement, &source).unwrap();
        assert!(!bootstrap.source_path_still_current());
        let copied = root.join("copied");
        let copied_digest = bootstrap.copy_to(&copied).unwrap();

        assert_eq!(copied_digest, original_digest);
        assert_eq!(executable_sha256(&copied).unwrap(), original_digest);
        assert_ne!(executable_sha256(&source).unwrap(), original_digest);
        fs::remove_dir_all(root).unwrap();
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn foreign_record_classification_never_connects_to_its_socket() {
        let directory = tempfile::tempdir().unwrap();
        let socket = directory.path().join("foreign.sock");
        let listener = tokio::net::UnixListener::bind(&socket).unwrap();
        let endpoint = IpcEndpoint::unix_socket(socket);
        let mut record = DaemonRecord::current(
            &endpoint,
            directory.path().join("log"),
            None,
            "foreign".into(),
        )
        .unwrap();
        record.artifact_id = Some(bcode_ipc::ArtifactId::parse("foreign-artifact").unwrap());
        assert!(pinned_daemon_endpoint(&record).is_err());
        let _ = classify_daemon_record(&record).await;
        assert!(
            tokio::time::timeout(Duration::from_millis(25), listener.accept())
                .await
                .is_err()
        );
        record.artifact_id = Some(bcode_ipc::ArtifactId::current());
        record.executable_digest = Some("foreign-bytes".into());
        assert!(pinned_daemon_endpoint(&record).is_err());
        let _ = classify_daemon_record(&record).await;
        assert!(
            tokio::time::timeout(Duration::from_millis(25), listener.accept())
                .await
                .is_err()
        );
    }

    #[test]
    fn cached_image_with_same_artifact_but_different_bytes_is_not_selected() {
        let state_dir = std::env::temp_dir().join(format!(
            "bcode-wrong-image-{}-{}",
            std::process::id(),
            unix_time_millis().unwrap()
        ));
        let other = b"another executable with the same artifact identity";
        let digest = hex::encode(Sha256::digest(other));
        let path = cached_daemon_executable_path_for_digest(&state_dir, &digest);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, other).unwrap();
        write_daemon_image_metadata(&path, &digest).unwrap();
        assert!(daemon_image_is_valid(&path, &digest).unwrap());
        assert!(current_cached_daemon_image(&state_dir).unwrap().is_none());
        let selected = ensure_current_executable_cached_in_state(&state_dir).unwrap();
        assert_ne!(selected, path);
        assert_eq!(
            executable_sha256(&selected).unwrap(),
            initialize_artifact_bootstrap().unwrap().digest().unwrap()
        );
        fs::remove_dir_all(state_dir).unwrap();
    }

    #[test]
    fn corrupt_cached_image_is_repaired_with_exact_metadata() {
        let state_dir = std::env::temp_dir().join(format!(
            "bcode-daemon-image-repair-test-{}-{}",
            std::process::id(),
            unix_time_millis().unwrap()
        ));
        let cached = ensure_current_executable_cached_in_state(&state_dir).unwrap();
        fs::write(&cached, b"corrupt").unwrap();

        let repaired = ensure_current_executable_cached_in_state(&state_dir).unwrap();
        let (_source, digest) = current_executable_identity().unwrap();
        assert_eq!(repaired, cached);
        assert!(daemon_image_is_valid(&repaired, &digest).unwrap());
        assert_eq!(
            ensure_current_executable_cached_in_state(&state_dir).unwrap(),
            repaired
        );
        assert!(
            fs::read_dir(repaired.parent().expect("cached image parent"))
                .unwrap()
                .all(|entry| !entry
                    .unwrap()
                    .file_name()
                    .to_string_lossy()
                    .starts_with(".bcode.tmp-"))
        );
        fs::remove_dir_all(state_dir).unwrap();
    }

    #[test]
    fn interrupted_cache_copy_is_removed_before_verified_publication() {
        let state_dir = std::env::temp_dir().join(format!(
            "bcode-daemon-image-interrupted-test-{}-{}",
            std::process::id(),
            unix_time_millis().unwrap()
        ));
        let (_source, digest) = current_executable_identity().unwrap();
        let target = cached_daemon_executable_path_for_digest(&state_dir, &digest);
        let parent = target.parent().expect("cached image parent");
        fs::create_dir_all(parent).unwrap();
        let interrupted = parent.join(format!(".bcode.tmp-{}", std::process::id()));
        fs::write(&interrupted, b"partial executable bytes").unwrap();

        let cached = ensure_current_executable_cached_in_state(&state_dir).unwrap();

        assert_eq!(cached, target);
        assert!(!interrupted.exists());
        assert!(daemon_image_is_valid(&cached, &digest).unwrap());
        fs::remove_dir_all(state_dir).unwrap();
    }

    #[test]
    fn pinned_image_verification_never_repairs_or_substitutes() {
        let root = tempfile::tempdir().unwrap();
        let path = ensure_current_executable_cached_in_state(root.path()).unwrap();
        let digest = executable_sha256(&path).unwrap();
        let pinned = PinnedBcodeExecutable { path, digest };
        assert!(verify_pinned_bcode_executable(&pinned).is_ok());
        fs::write(pinned.path(), b"replacement").unwrap();
        assert!(verify_pinned_bcode_executable(&pinned).is_err());
        assert_eq!(fs::read(pinned.path()).unwrap(), b"replacement");
        fs::remove_file(pinned.path()).unwrap();
        assert!(verify_pinned_bcode_executable(&pinned).is_err());
        assert!(!pinned.path().exists());
    }

    #[test]
    fn content_addressed_paths_are_verified() {
        let path = cached_daemon_executable_path_for_digest(Path::new("/state"), "abc123");
        assert!(executable_path_matches_digest(&path, "abc123"));
        assert!(!executable_path_matches_digest(&path, "other"));
        assert!(!executable_path_matches_digest(
            Path::new("/state/daemon-images/legacy/bcode"),
            "abc123"
        ));
    }

    #[test]
    fn caches_current_executable_into_immutable_digest_directory() {
        let state_dir = std::env::temp_dir().join(format!(
            "bcode-daemon-image-test-{}-{}",
            std::process::id(),
            unix_time_millis().unwrap()
        ));

        let cached = ensure_current_executable_cached_in_state(&state_dir).unwrap();
        let (_source, digest) = current_executable_identity().unwrap();

        assert!(cached.exists());
        assert_eq!(
            cached,
            cached_daemon_executable_path_for_digest(&state_dir, &digest)
        );
        assert_eq!(executable_sha256(&cached).unwrap(), digest);
        assert!(daemon_image_is_valid(&cached, &digest).unwrap());
        assert_eq!(
            serde_json::from_slice::<DaemonImageMetadata>(
                &fs::read(daemon_image_metadata_path(&cached)).unwrap()
            )
            .unwrap()
            .artifact_id,
            bcode_ipc::ArtifactId::current()
        );
        assert_eq!(
            ensure_current_executable_cached_in_state(&state_dir).unwrap(),
            cached
        );
        let _ = fs::remove_dir_all(state_dir);
    }
}

/// Options controlling daemon startup orchestration.
#[derive(Debug, Clone)]
pub struct EnsureDaemonOptions {
    /// Endpoint the daemon should serve.
    pub endpoint: IpcEndpoint,
    /// Suppress user-facing status output.
    pub quiet: bool,
    /// Path used for daemon stdout/stderr logs.
    pub log_path: PathBuf,
}

impl EnsureDaemonOptions {
    /// Build default daemon startup options for the current namespace.
    #[must_use]
    pub fn default_for_current_namespace() -> Self {
        Self {
            endpoint: bcode_ipc::default_endpoint(),
            quiet: true,
            log_path: default_daemon_log_path(),
        }
    }
}

/// Error returned when daemon process startup fails.
#[derive(Debug, Error)]
pub enum DaemonStartError {
    /// Daemon lifecycle registry cleanup failed.
    #[error("daemon lifecycle error: {0}")]
    Lifecycle(#[from] DaemonLifecycleError),
    /// Daemon process I/O failed.
    #[error("daemon process I/O error: {0}")]
    Io(#[from] std::io::Error),
    /// The detached child's readiness notification was not observed before the deadline.
    /// This records the failed wait, not the child's current readiness or execution lifetime.
    #[error(
        "daemon readiness notification deadline elapsed; child readiness and execution lifetime are unknown; log: {log_path}\ntry `bcode server run` to see startup failures in the foreground\n\n{recent_log}"
    )]
    NotificationTimeout {
        /// Daemon log path.
        log_path: String,
        /// Recent daemon log excerpt.
        recent_log: String,
    },
    /// Daemon did not become ready before the startup timeout.
    #[error(
        "daemon did not become ready after auto-start; log: {log_path}\ntry `bcode server run` to see startup failures in the foreground\n\n{recent_log}"
    )]
    StartTimeout {
        /// Daemon log path.
        log_path: String,
        /// Recent daemon log excerpt.
        recent_log: String,
    },
    /// Daemon process exited before readiness.
    #[error(
        "daemon exited before becoming ready ({status}); log: {log_path}\ntry `bcode server run` to see startup failures in the foreground\n\n{recent_log}"
    )]
    Exited {
        /// Child process exit status.
        status: String,
        /// Daemon log path.
        log_path: String,
        /// Recent daemon log excerpt.
        recent_log: String,
    },
    /// Daemon readiness was transient and failed a follow-up health check.
    #[error(
        "daemon became ready but failed a follow-up health check; log: {log_path}\ntry `bcode server run` to see startup failures in the foreground\n\n{recent_log}"
    )]
    HealthCheckFailed {
        /// Daemon log path.
        log_path: String,
        /// Recent daemon log excerpt.
        recent_log: String,
    },
    /// A live process occupies the target endpoint but did not complete a compatible handshake.
    #[error(
        "daemon endpoint {endpoint} is occupied by a live process that did not become ready; refusing to start a competing daemon"
    )]
    EndpointOccupied {
        /// Display form of the occupied endpoint.
        endpoint: String,
    },
    /// Another process held the namespace startup lock beyond the bounded startup window.
    #[error("timed out waiting for daemon startup coordination lock at {}", lock_path.display())]
    StartupCoordinationTimeout {
        /// Namespace-scoped startup lock path.
        lock_path: PathBuf,
    },
}

impl DaemonStartError {
    /// Return true when startup likely lost a race to an already-running daemon.
    #[must_use]
    pub fn is_existing_daemon_race(&self) -> bool {
        match self {
            Self::Exited { recent_log, .. }
            | Self::NotificationTimeout { recent_log, .. }
            | Self::StartTimeout { recent_log, .. }
            | Self::HealthCheckFailed { recent_log, .. } => {
                recent_log.contains("refusing to replace live IPC socket")
                    || recent_log.contains("another bcode daemon is listening")
                    || recent_log.contains("Address already in use")
            }
            Self::Io(error) => error.kind() == std::io::ErrorKind::AddrInUse,
            Self::Lifecycle(_)
            | Self::EndpointOccupied { .. }
            | Self::StartupCoordinationTimeout { .. } => false,
        }
    }
}

/// Return the `XDG_CONFIG_HOME` value that reproduces `config_dir` in a child process.
///
/// `bcode_config::default_config_dir()` resolves to `<config-home>/bcode`, so the
/// daemon must inherit the parent of that directory for its own resolution to land on
/// the same path. When the resolved directory has no parent — or is not the expected
/// `bcode` leaf, which can happen for a temp-dir fallback — the directory is passed
/// through unchanged rather than guessing, so a mismatch surfaces at the handshake
/// instead of silently redirecting the daemon's config.
fn config_home_for_daemon(config_dir: &Path) -> PathBuf {
    if config_dir.file_name().and_then(|name| name.to_str()) == Some("bcode")
        && let Some(parent) = config_dir.parent()
    {
        return parent.to_path_buf();
    }
    config_dir.to_path_buf()
}

fn daemon_command(exe: &Path) -> tokio::process::Command {
    let mut command = tokio::process::Command::new(exe);
    detach_daemon_process(&mut command);
    configure_daemon_config(
        &mut command,
        bcode_config::process_exclusive_config_path().as_deref(),
    );
    command
}

fn configure_daemon_config(command: &mut tokio::process::Command, path: Option<&Path>) {
    if let Some(path) = path {
        command.arg("--config-only").arg(path);
    }
}

fn diagnostic_startup_id() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| duration.as_nanos())
}

/// Prepare and execute the immutable current-artifact image without starting a daemon.
///
/// Uses the normal startup fence and image retention guard. Preparation is explicit
/// so installer/build time can absorb first-execution OS validation without weakening it.
///
/// # Errors
/// Returns normal lifecycle errors or a failed cached-image identity probe.
pub async fn prepare_daemon_image(endpoint: &IpcEndpoint) -> Result<(), DaemonStartError> {
    let Some(_startup) = StartupLock::acquire(endpoint).await? else {
        return Ok(());
    };
    let _retention = DaemonImageUseGuard::acquire(&bcode_config::default_state_dir())?;
    let image = ensure_current_executable_cached()?;
    let output = tokio::time::timeout(
        Duration::from_secs(30),
        tokio::process::Command::new(image)
            .arg("artifact-id")
            .stdin(std::process::Stdio::null())
            .kill_on_drop(true)
            .output(),
    )
    .await
    .map_err(|_| {
        std::io::Error::new(
            std::io::ErrorKind::TimedOut,
            "prepared daemon image probe timed out",
        )
    })??;
    if !output.status.success()
        || output.stdout != format!("{}\n", bcode_ipc::ArtifactId::current()).as_bytes()
    {
        return Err(std::io::Error::other("prepared daemon image identity probe failed").into());
    }
    Ok(())
}

/// Ensure the current namespace daemon is running, starting it when needed.
///
/// # Errors
///
/// Returns an error when stale-record cleanup fails, spawning the daemon fails,
/// or the daemon does not pass bounded readiness checks.
pub async fn ensure_daemon_running(options: &EnsureDaemonOptions) -> Result<(), DaemonStartError> {
    use tracing::Instrument as _;

    let startup_id = diagnostic_startup_id();
    let launcher_pid = std::process::id();
    let span = tracing::debug_span!(
        target: "bcode_daemon_lifecycle::startup",
        "daemon_acquisition",
        startup_id,
        launcher_pid
    );
    let acquisition_phase = bcode_metrics::startup::phase_for(
        "launcher.acquire",
        &format!("{launcher_pid}-{startup_id}"),
    );
    let result = ensure_daemon_running_with_start(options, |options, startup_lock| {
        #[cfg(unix)]
        let handoff = format!("{}-{startup_id}", std::process::id());
        let inherited_startup_lock = startup_lock.file.try_clone();
        #[cfg(unix)]
        let descriptor_file = startup_lock.file.try_clone();
        let endpoint = options.endpoint.clone();
        let log_path = options.log_path.clone();
        async move {
            let log_file = open_startup_log(&log_path)?;
            let stderr_log = log_file.try_clone()?;

            let spawn_started_at = std::time::Instant::now();
            let phase = bcode_metrics::startup::phase("launcher.artifact_prepare");
            let cached_exe = ensure_current_executable_cached()?;
            phase.finish();
            let executable_digest = require_cached_executable_digest(&cached_exe)?;
            // Always spawn from the immutable content-addressed image. Spawning from the
            // bootstrap source path would pin the daemon to a mutable pathname (for example
            // `target/<triple>/release/bcode`), so rebuilding that path would later make the
            // running daemon's own identity unverifiable even though it keeps serving its
            // original artifact correctly.
            let exe = cached_exe;
            tracing::debug!(
                target: "bcode_daemon_lifecycle::startup",
                elapsed_ms = spawn_started_at.elapsed().as_millis(),
                "daemon image ready"
            );
            let (endpoint_env_name, endpoint_env_value) =
                bcode_ipc::endpoint_env_pair(&endpoint)
                    .map_err(|error| std::io::Error::other(error.to_string()))?;
            #[cfg(unix)]
            write_startup_owner(
                &descriptor_file?,
                &StartupOwnerDescriptor::current("handoff_pending", handoff.clone())?,
            )?;
            let mut command = daemon_command(&exe);
            #[cfg(unix)]
            command.env("BCODE_STARTUP_HANDOFF_V1", handoff);
            let spawn_phase = bcode_metrics::startup::phase("launcher.process_spawn");
            let mut child = command
                .args(["server", "run"])
                .env(endpoint_env_name, endpoint_env_value)
                .env(
                    bcode_ipc::BCODE_IPC_ENDPOINT_NAMESPACE_ENV,
                    bcode_ipc::daemon_namespace(),
                )
                // The daemon must serve the runtime scope this client resolved — both the
                // state location and the config directory — not whatever it would infer
                // from inherited environment. An explicit command-line `--state-root`
                // selection is process-scoped and would otherwise be lost across the
                // process boundary, silently starting a daemon on a different canonical
                // session root or under different plugin/permission policy.
                .env(
                    bcode_config::BCODE_STATE_DIR_ENV,
                    bcode_config::default_state_dir(),
                )
                .env(
                    bcode_config::BCODE_SESSION_STORE_DIR_ENV,
                    bcode_config::default_session_store_dir(),
                )
                .env(
                    "XDG_CONFIG_HOME",
                    config_home_for_daemon(&bcode_config::default_config_dir()),
                )
                .env(BCODE_EXECUTABLE_DIGEST_ENV, executable_digest)
                .env("BCODE_DAEMON_LOG", &log_path)
                .env("BCODE_DAEMON_READY_STDOUT", "v1")
                .env(
                    "BCODE_STARTUP_CORRELATION",
                    format!("{launcher_pid}-{startup_id}"),
                )
                // The daemon remains detached on cancellation. On Unix its inherited
                // startup lock fences later launchers even before endpoint publication.
                .kill_on_drop(false)
                // On Unix the inherited open file description retains startup ownership
                // even if the launcher exits before the child binds its endpoint.
                .stdin(startup_lock_stdio(inherited_startup_lock?))
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::from(stderr_log))
                .spawn()?;
            // Release Command's configured stdin duplicate; the child and scoped
            // StartupLock are now the only intentional owners of this OFD.
            drop(command);
            spawn_phase.finish();
            tracing::debug!(
                target: "bcode_daemon_lifecycle::startup",
                elapsed_ms = spawn_started_at.elapsed().as_millis(),
                "daemon child spawned"
            );

            measured_child_readiness(&endpoint, &mut child, &log_path).await
        }
    })
    .instrument(span)
    .await;
    acquisition_phase.finish_result(&result);
    result
}

fn require_cached_executable_digest(path: &Path) -> Result<String, DaemonLifecycleError> {
    cached_executable_digest(path)
        .map(ToOwned::to_owned)
        .ok_or_else(|| DaemonLifecycleError::Io {
            path: path.to_owned(),
            source: std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "cached daemon executable path has no digest component",
            ),
        })
}

fn open_startup_log(path: &Path) -> std::io::Result<fs::File> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    // Truncate before opening append-only handles: launcher and child stderr
    // share this path, so positional writes would overwrite trace records.
    fs::File::create(path)?;
    let mut file = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    writeln!(file, "--- bcode daemon start ---")?;
    Ok(file)
}

/// Detach the child from the launching terminal, not merely its stdio handles.
fn detach_daemon_process(command: &mut tokio::process::Command) {
    #[cfg(unix)]
    // SAFETY: setsid is async-signal-safe and touches no Rust state in the
    // post-fork child. The child starts a new session before exec, so terminal
    // closure cannot deliver SIGHUP to the daemon's process group.
    unsafe {
        command.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
    #[cfg(windows)]
    command.creation_flags(0x0000_0008 | 0x0000_0200); // DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
    #[cfg(not(any(unix, windows)))]
    let _ = command;
}

#[cfg(all(test, unix))]
#[tokio::test]
async fn daemon_child_has_a_new_session_and_process_group() {
    let mut command = tokio::process::Command::new("sleep");
    command.arg("10").kill_on_drop(true);
    detach_daemon_process(&mut command);
    let mut child = command.spawn().expect("spawn detached child");
    let pid = i32::try_from(child.id().expect("child pid")).expect("pid fits");
    // SAFETY: read-only process identity queries for the child we just spawned.
    let (session, group) = unsafe { (libc::getsid(pid), libc::getpgid(pid)) };
    child.kill().await.expect("stop test child");
    assert_eq!(
        session, pid,
        "daemon must not inherit the launching terminal session"
    );
    assert_eq!(
        group, pid,
        "daemon must not inherit the launching process group"
    );
}

/// Ensure the current namespace daemon is running using an in-process start callback.
///
/// # Errors
///
/// Returns an error when stale endpoint cleanup fails, the callback fails, or the daemon does not
/// pass bounded readiness checks.
pub async fn ensure_daemon_running_in_process(
    options: &EnsureDaemonOptions,
    mut start: impl FnMut() -> Result<(), DaemonStartError>,
) -> Result<(), DaemonStartError> {
    let log_path = options.log_path.clone();
    ensure_daemon_running_with_start(options, move |options, _startup_lock| {
        let result = start();
        let endpoint = options.endpoint.clone();
        let log_path = log_path.clone();
        async move {
            result?;
            wait_for_daemon_ready(&endpoint, &log_path).await
        }
    })
    .await
}

async fn ensure_daemon_running_with_start<F, Fut>(
    options: &EnsureDaemonOptions,
    mut start: F,
) -> Result<(), DaemonStartError>
where
    F: FnMut(&EnsureDaemonOptions, &StartupLock) -> Fut,
    Fut: std::future::Future<Output = Result<(), DaemonStartError>>,
{
    if ping_ready(&options.endpoint).await {
        print_daemon_status(options, "server already running");
        return Ok(());
    }

    let phase = bcode_metrics::startup::phase("launcher.startup_lock");
    let acquired = StartupLock::acquire(&options.endpoint).await;
    phase.finish_result(&acquired);
    let Some(lock) = acquired? else {
        print_daemon_status(options, "server already running");
        return Ok(());
    };
    #[cfg(unix)]
    if endpoint_has_listener(&options.endpoint).await {
        if wait_for_existing_daemon(&options.endpoint).await {
            drop(lock);
            print_daemon_status(options, "server already running");
            return Ok(());
        }
        return Err(DaemonStartError::EndpointOccupied {
            endpoint: format!("{:?}", options.endpoint),
        });
    }
    let image_use_guard = DaemonImageUseGuard::acquire(&bcode_config::default_state_dir())?;
    #[cfg(unix)]
    cleanup_stale_endpoint(&options.endpoint)?;
    if ping_ready(&options.endpoint).await {
        drop(image_use_guard);
        drop(lock);
        print_daemon_status(options, "server already running");
        return Ok(());
    }

    start(options, &lock).await?;
    drop(image_use_guard);
    let _cleanup_task = tokio::spawn(async {
        let _ = cleanup_stale_daemon_records().await;
        let _ = cleanup_stale_daemon_images_retaining_artifacts(
            &bcode_config::default_state_dir(),
            &registered_retained_artifact_ids(),
        );
    });
    drop(lock);
    print_daemon_status(options, "server started");
    Ok(())
}

/// Report whether any cached daemon image exists for one artifact identity.
///
/// Durable work fenced to an artifact can only be recovered by launching a daemon of exactly that
/// identity. When no cached image remains, that work is unrecoverable rather than merely deferred.
#[must_use]
pub fn artifact_image_is_available(state_dir: &Path, artifact_id: &str) -> bool {
    let namespace = state_dir.join("daemon-images").join(artifact_id);
    fs::read_dir(namespace).is_ok_and(|mut entries| entries.any(|entry| entry.is_ok()))
}

/// Supplies artifact identities whose cached daemon images must be preserved.
///
/// Domains that fence durable work to an exact daemon artifact register a provider so background
/// image cleanup cannot delete the only launchable daemon for still-recoverable work. The hook
/// keeps this crate free of any dependency on those domains.
type RetainedArtifactProvider = fn() -> std::collections::BTreeSet<String>;

static RETAINED_ARTIFACT_PROVIDERS: std::sync::Mutex<Vec<RetainedArtifactProvider>> =
    std::sync::Mutex::new(Vec::new());

/// Register a provider of artifact identities that must keep their cached daemon images.
///
/// Providers are consulted by background image cleanup. Registration is additive and idempotent
/// only by caller discipline; register each provider once during startup.
pub fn register_retained_artifact_provider(provider: RetainedArtifactProvider) {
    RETAINED_ARTIFACT_PROVIDERS
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .push(provider);
}

/// Collect retained artifact identities from every registered provider.
#[must_use]
pub fn registered_retained_artifact_ids() -> std::collections::BTreeSet<String> {
    let providers = RETAINED_ARTIFACT_PROVIDERS
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .clone();
    providers
        .into_iter()
        .flat_map(|provider| provider())
        .collect()
}

fn print_daemon_status(options: &EnsureDaemonOptions, status: &str) {
    if !options.quiet {
        println!("{status}");
        println!("namespace: {}", daemon_namespace());
        println!("log: {}", display_from_current_dir(&options.log_path));
    }
}

/// Return the default daemon log path for the current namespace.
#[must_use]
pub fn default_daemon_log_path() -> PathBuf {
    std::env::var_os("BCODE_DAEMON_LOG").map_or_else(
        || {
            bcode_config::default_state_dir()
                .join("logs")
                .join(format!("daemon-{}.log", daemon_namespace()))
        },
        PathBuf::from,
    )
}

#[cfg(unix)]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StartupOwnerDescriptor {
    version: u32,
    artifact: String,
    state: String,
    executable_digest: String,
    pid: u32,
    process_start_seconds: u64,
    phase: String,
    handoff: String,
}

#[cfg(unix)]
impl StartupOwnerDescriptor {
    fn current(phase: &str, handoff: String) -> std::io::Result<Self> {
        let pid = std::process::id();
        let mut system = System::new();
        system.refresh_processes(ProcessesToUpdate::Some(&[Pid::from_u32(pid)]), true);
        let process_start_seconds = system
            .process(Pid::from_u32(pid))
            .ok_or_else(|| std::io::Error::other("startup process identity unavailable"))?
            .start_time();
        Ok(Self {
            version: 1,
            artifact: bcode_ipc::ArtifactId::current().to_string(),
            state: bcode_ipc::state_location_id(),
            executable_digest: initialize_artifact_bootstrap()
                .and_then(ArtifactBootstrap::digest)
                .map_err(std::io::Error::other)?,
            pid,
            process_start_seconds,
            phase: phase.to_owned(),
            handoff,
        })
    }

    fn matches_scope(&self) -> bool {
        self.version == 1
            && matches!(
                self.phase.as_str(),
                "preparing" | "handoff_pending" | "daemon_ready"
            )
            && !self.handoff.is_empty()
            && self.handoff.len() <= 128
            && self.artifact == bcode_ipc::ArtifactId::current().to_string()
            && self.state == bcode_ipc::state_location_id()
            && initialize_artifact_bootstrap()
                .and_then(ArtifactBootstrap::digest)
                .is_ok_and(|digest| digest == self.executable_digest)
    }

    fn process_verified(&self) -> bool {
        let pid = Pid::from_u32(self.pid);
        let mut system = System::new();
        system.refresh_processes(ProcessesToUpdate::Some(&[pid]), true);
        system.process(pid).is_some_and(|process| {
            process.start_time() == self.process_start_seconds
                && process.exe().is_some_and(|exe| {
                    executable_path_matches_digest(exe, &self.executable_digest)
                        && executable_sha256(exe)
                            .is_ok_and(|digest| digest == self.executable_digest)
                })
        })
    }
}

// Positional access avoids the shared OFD cursor. Partial concurrent snapshots are
// explicitly unknown; they never authorize takeover or a second spawn.
#[cfg(unix)]
fn read_startup_owner(file: &fs::File) -> std::io::Result<Option<StartupOwnerDescriptor>> {
    use std::os::unix::fs::FileExt as _;
    let mut bytes = [0_u8; 8193];
    let size = file.read_at(&mut bytes, 0)?;
    if size == 0 || bytes[..size].starts_with(b"pid=") {
        return Ok(None);
    }
    if size > 8192 {
        return Err(std::io::Error::other("startup descriptor exceeds bound"));
    }
    serde_json::from_slice(&bytes[..size])
        .map(Some)
        .map_err(std::io::Error::other)
}

#[cfg(unix)]
fn write_startup_owner(file: &fs::File, owner: &StartupOwnerDescriptor) -> std::io::Result<()> {
    use std::os::unix::fs::FileExt as _;
    let bytes = serde_json::to_vec(owner).map_err(std::io::Error::other)?;
    if bytes.len() > 8192 {
        return Err(std::io::Error::other("startup descriptor exceeds bound"));
    }
    file.write_all_at(&bytes, 0)?;
    file.set_len(u64::try_from(bytes.len()).map_err(std::io::Error::other)?)?;
    file.sync_data()
}

#[cfg(unix)]
fn publish_daemon_startup_owner() -> std::io::Result<()> {
    use std::os::fd::BorrowedFd;
    let handoff = std::env::var("BCODE_STARTUP_HANDOFF_V1").map_err(std::io::Error::other)?;
    // SAFETY: duplicate process-owned stdin without taking ownership of it.
    let file = fs::File::from(unsafe { BorrowedFd::borrow_raw(0) }.try_clone_to_owned()?);
    let path = startup_lock_path(
        &bcode_config::default_state_dir(),
        &daemon_namespace(),
        &bcode_ipc::state_location_id(),
    );
    publish_startup_owner_at(&file, &path, &handoff)?;
    close_startup_stdin_on_exec()
}

#[cfg(unix)]
fn close_startup_stdin_on_exec() -> std::io::Result<()> {
    // Keep stdin open for this daemon's lifetime, but never transfer its fence
    // through a subsequent exec. F_GETFD/F_SETFD affect this process's fd only.
    let flags = unsafe { libc::fcntl(0, libc::F_GETFD) };
    if flags == -1 || unsafe { libc::fcntl(0, libc::F_SETFD, flags | libc::FD_CLOEXEC) } == -1 {
        return Err(std::io::Error::last_os_error());
    }
    Ok(())
}

#[cfg(unix)]
fn publish_startup_owner_at(file: &fs::File, path: &Path, handoff: &str) -> std::io::Result<()> {
    use std::os::unix::fs::MetadataExt as _;
    let expected = fs::symlink_metadata(path)?;
    let actual = file.metadata()?;
    if !expected.is_file() || expected.dev() != actual.dev() || expected.ino() != actual.ino() {
        return Err(std::io::Error::other(
            "startup descriptor path identity mismatch",
        ));
    }
    let owner = read_startup_owner(file)?
        .ok_or_else(|| std::io::Error::other("startup descriptor unavailable"))?;
    if !owner.matches_scope() || owner.phase != "handoff_pending" || owner.handoff != handoff {
        return Err(std::io::Error::other("startup descriptor handoff mismatch"));
    }
    write_startup_owner(
        file,
        &StartupOwnerDescriptor::current("daemon_ready", handoff.to_owned())?,
    )
}

#[cfg(unix)]
fn observe_startup_owner(file: &fs::File) {
    let owner = read_startup_owner(file)
        .ok()
        .flatten()
        .filter(StartupOwnerDescriptor::matches_scope);
    tracing::debug!(target: "bcode_daemon_lifecycle::startup",
        claimed_pid = ?owner.as_ref().map(|value| value.pid),
        claimed_process_start_seconds = ?owner.as_ref().map(|value| value.process_start_seconds),
        artifact = ?owner.as_ref().map(|value| value.artifact.as_str()),
        state = ?owner.as_ref().map(|value| value.state.as_str()),
        executable_digest = ?owner.as_ref().map(|value| value.executable_digest.as_str()),
        phase = ?owner.as_ref().map(|value| value.phase.as_str()),
        verified_process = owner.as_ref().is_some_and(StartupOwnerDescriptor::process_verified),
        kernel_lock_owner = "unknown",
        "fresh startup descriptor observation");
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StartupLockObservation {
    Waiting,
    Acquired,
    ConcurrentReady,
    Timeout,
}

impl StartupLockObservation {
    const fn phase_name(self) -> &'static str {
        match self {
            Self::Waiting => "launcher.lock_wait",
            Self::Acquired => "launcher.lock_acquired",
            Self::ConcurrentReady => "launcher.lock_concurrent_ready",
            Self::Timeout => "launcher.lock_timeout",
        }
    }
}

#[derive(Debug)]
struct StartupLock {
    file: fs::File,
}

impl StartupLock {
    // Covers the bounded 30s explicit image probe plus scheduling/verification.
    const ACQUIRE_TIMEOUT: Duration = Duration::from_secs(35);
    const POLL_INTERVAL: Duration = Duration::from_millis(25);

    async fn acquire(endpoint: &IpcEndpoint) -> Result<Option<Self>, DaemonStartError> {
        let path = startup_lock_path(
            &bcode_config::default_state_dir(),
            &daemon_namespace(),
            &bcode_ipc::state_location_id(),
        );
        let artifact = bcode_ipc::ArtifactId::current().to_string();
        let state = bcode_ipc::state_location_id();
        let scope = format!("{artifact}.{state}");
        let acquired = Self::acquire_observed(
            path,
            Self::ACQUIRE_TIMEOUT,
            &scope,
            || ping_ready(endpoint),
            |observation, elapsed| {
                // Terminal outcomes are point observations in tracing below.
                // The scoped lock_wait phase owns the actual elapsed interval.
                tracing::debug!(
                    target: "bcode_daemon_lifecycle::startup",
                    artifact_id = %artifact,
                    state_location_id = %state,
                    phase = observation.phase_name(),
                    elapsed_us = elapsed.as_micros(),
                    holder_identity = "unknown",
                    lock_pid_evidence = "unverified_hint_not_read",
                    "startup coordination observation"
                );
            },
        )
        .await?;
        #[cfg(unix)]
        if let Some(lock) = &acquired {
            if read_startup_owner(&lock.file)?.is_some_and(|owner| !owner.matches_scope()) {
                return Err(
                    std::io::Error::other("unsupported or foreign startup descriptor").into(),
                );
            }
            write_startup_owner(
                &lock.file,
                &StartupOwnerDescriptor::current(
                    "preparing",
                    format!("{}-{}", std::process::id(), diagnostic_startup_id()),
                )?,
            )?;
        }
        Ok(acquired)
    }

    async fn acquire_observed<F, Fut>(
        path: PathBuf,
        timeout: Duration,
        scope: &str,
        mut ready: F,
        mut observe: impl FnMut(StartupLockObservation, Duration),
    ) -> Result<Option<Self>, DaemonStartError>
    where
        F: FnMut() -> Fut,
        Fut: std::future::Future<Output = bool>,
    {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let started = std::time::Instant::now();
        let wait_phase = bcode_metrics::startup::phase_for("launcher.lock_wait", scope);
        let mut waiting = false;
        loop {
            let mut open = fs::OpenOptions::new();
            open.read(true).write(true).create(true).truncate(false);
            #[cfg(unix)]
            {
                use std::os::unix::fs::OpenOptionsExt as _;
                open.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
                    .mode(0o600);
            }
            let file = open.open(&path)?;
            if !file.metadata()?.is_file() {
                return Err(
                    std::io::Error::other("startup descriptor is not a regular file").into(),
                );
            }
            match file.try_lock() {
                Ok(()) => {
                    #[cfg(not(unix))]
                    {
                        file.set_len(0)?;
                        writeln!(&file, "pid={}", std::process::id())?;
                        file.sync_data()?;
                    }
                    observe(StartupLockObservation::Acquired, started.elapsed());
                    wait_phase.finish();
                    return Ok(Some(Self { file }));
                }
                Err(std::fs::TryLockError::WouldBlock) => {
                    if !waiting {
                        observe(StartupLockObservation::Waiting, started.elapsed());
                        waiting = true;
                    }
                    let remaining = timeout.saturating_sub(started.elapsed());
                    if tokio::time::timeout(remaining, ready())
                        .await
                        .unwrap_or(false)
                    {
                        observe(StartupLockObservation::ConcurrentReady, started.elapsed());
                        wait_phase.finish();
                        return Ok(None);
                    }
                    if started.elapsed() >= timeout {
                        #[cfg(unix)]
                        observe_startup_owner(&file);
                        observe(StartupLockObservation::Timeout, started.elapsed());
                        wait_phase.fail();
                        return Err(DaemonStartError::StartupCoordinationTimeout {
                            lock_path: path,
                        });
                    }
                    tokio::time::sleep(
                        Self::POLL_INTERVAL.min(timeout.saturating_sub(started.elapsed())),
                    )
                    .await;
                }
                Err(std::fs::TryLockError::Error(error)) => return Err(error.into()),
            }
        }
    }

    #[cfg(test)]
    async fn acquire_at(path: PathBuf, timeout: Duration) -> Result<Self, DaemonStartError> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let started = std::time::Instant::now();
        loop {
            let file = fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(&path)?;
            match file.try_lock() {
                Ok(()) => {
                    file.set_len(0)?;
                    writeln!(&file, "pid={}", std::process::id())?;
                    file.sync_data()?;
                    return Ok(Self { file });
                }
                Err(std::fs::TryLockError::WouldBlock) => {
                    if started.elapsed() >= timeout {
                        return Err(DaemonStartError::StartupCoordinationTimeout {
                            lock_path: path,
                        });
                    }
                    tokio::time::sleep(Self::POLL_INTERVAL).await;
                }
                Err(std::fs::TryLockError::Error(error)) => return Err(error.into()),
            }
        }
    }
}

// Unix file locks are attached to the open file description. Passing a duplicate
// through stdin transfers ownership atomically with spawn, before child Rust code
// runs. Do not explicitly unlock the parent's description: that would also unlock
// the child's duplicate. The daemon retains stdin for its lifetime.
fn startup_lock_stdio(file: fs::File) -> std::process::Stdio {
    #[cfg(unix)]
    {
        std::process::Stdio::from(file)
    }
    #[cfg(not(unix))]
    {
        drop(file);
        std::process::Stdio::null()
    }
}

#[cfg(not(unix))]
impl Drop for StartupLock {
    fn drop(&mut self) {
        let _ = self.file.unlock();
    }
}

const READINESS_TIMEOUT: Duration = Duration::from_secs(20);
const READINESS_RETRY_DELAY: Duration = Duration::from_millis(25);

/// Notify the launching client that the daemon is ready to accept connections.
///
/// This private, versioned launch-channel signal is only a wakeup: callers must
/// still verify the normal IPC identity handshake. Foreground servers do nothing.
/// A departed launcher must not prevent the daemon from serving other clients.
pub fn notify_launcher_ready() {
    if std::env::var("BCODE_DAEMON_READY_STDOUT").as_deref() == Ok("v1") {
        #[cfg(unix)]
        if publish_daemon_startup_owner().is_err() {
            tracing::error!(target: "bcode_daemon_lifecycle::startup",
                "startup descriptor publication failed; readiness notification withheld");
            return;
        }
        let mut stdout = std::io::stdout().lock();
        let _ = stdout.write_all(b"BCODE_READY_V1\n");
        let _ = stdout.flush();
    }
}

async fn measured_child_readiness(
    endpoint: &IpcEndpoint,
    child: &mut tokio::process::Child,
    log_path: &Path,
) -> Result<(), DaemonStartError> {
    let phase = bcode_metrics::startup::phase("launcher.spawn_to_notification");
    let result = wait_for_child_notification(endpoint, child, log_path).await;
    phase.finish_result(&result);
    result
}

async fn wait_for_child_notification(
    endpoint: &IpcEndpoint,
    child: &mut tokio::process::Child,
    log_path: &Path,
) -> Result<(), DaemonStartError> {
    wait_for_child_notification_with_timeout(endpoint, child, log_path, READINESS_TIMEOUT).await
}

async fn wait_for_child_notification_with_timeout(
    endpoint: &IpcEndpoint,
    child: &mut tokio::process::Child,
    log_path: &Path,
    timeout: Duration,
) -> Result<(), DaemonStartError> {
    use tokio::io::AsyncReadExt as _;

    let started = std::time::Instant::now();
    let mut stdout = child
        .stdout
        .take()
        .ok_or_else(|| std::io::Error::other("daemon startup notification channel missing"))?;
    let mut token = [0_u8; 15];
    let notification = tokio::time::timeout(timeout, stdout.read_exact(&mut token));
    tokio::pin!(notification);
    tokio::select! {
        status = child.wait() => {
            return Err(DaemonStartError::Exited {
                status: status?.to_string(),
                log_path: display_from_current_dir(log_path).to_string(),
                recent_log: recent_log_excerpt(log_path),
            });
        }
        result = &mut notification => {
            match result {
                Ok(Ok(_)) if &token == b"BCODE_READY_V1\n" => {}
                Ok(_) => return Err(std::io::Error::other("invalid or closed daemon startup notification channel").into()),
                Err(_) => return Err(DaemonStartError::NotificationTimeout {
                    log_path: display_from_current_dir(log_path).to_string(),
                    recent_log: recent_log_excerpt(log_path),
                }),
            }
        }
    }
    tracing::debug!(
        target: "bcode_daemon_lifecycle::startup",
        elapsed_us = started.elapsed().as_micros(),
        "daemon readiness notification received"
    );
    // A notification is only a wakeup, not verified readiness.
    let remaining = timeout.saturating_sub(started.elapsed());
    let phase = bcode_metrics::startup::phase("launcher.verified_handshake");
    let result = tokio::time::timeout(remaining, wait_for_daemon_ready(endpoint, log_path))
        .await
        .unwrap_or_else(|_| {
            Err(DaemonStartError::HealthCheckFailed {
                log_path: display_from_current_dir(log_path).to_string(),
                recent_log: recent_log_excerpt(log_path),
            })
        });
    phase.finish_result(&result);
    result
}

async fn wait_for_daemon_ready(
    endpoint: &IpcEndpoint,
    log_path: &Path,
) -> Result<(), DaemonStartError> {
    let deadline = tokio::time::Instant::now() + READINESS_TIMEOUT;
    loop {
        if ping_ready(endpoint).await {
            return Ok(());
        }
        if tokio::time::Instant::now() >= deadline {
            return Err(DaemonStartError::StartTimeout {
                log_path: display_from_current_dir(log_path).to_string(),
                recent_log: recent_log_excerpt(log_path),
            });
        }
        tokio::time::sleep(READINESS_RETRY_DELAY).await;
    }
}

async fn ping_ready(endpoint: &IpcEndpoint) -> bool {
    matches!(
        tokio::time::timeout(Duration::from_millis(500), async {
            let Some(status) = probe_daemon_status(endpoint).await else {
                return false;
            };
            daemon_status_matches_current_executable(&status)
        })
        .await,
        Ok(true)
    )
}

fn daemon_status_matches_current_executable(status: &bcode_ipc::DaemonStatus) -> bool {
    status.namespace == daemon_namespace()
        && initialize_artifact_bootstrap()
            .and_then(ArtifactBootstrap::digest)
            .is_ok_and(|digest| status.executable_digest.as_deref() == Some(digest.as_str()))
        && status.protocol_version == u32::from(CURRENT_PROTOCOL_VERSION)
        && status.artifact_id.as_ref() == Some(&bcode_ipc::ArtifactId::current())
        && status.build_fingerprint == BUILD_FINGERPRINT
        && status.storage_writer_epoch == Some(bcode_ipc::CURRENT_SESSION_STORAGE_WRITER_EPOCH)
        && status.session_event_schema_version
            == Some(bcode_session_models::CURRENT_SESSION_EVENT_SCHEMA_VERSION)
}

#[cfg(unix)]
async fn wait_for_existing_daemon(endpoint: &IpcEndpoint) -> bool {
    for delay in [50, 100, 200, 400, 800, 1_000] {
        if ping_ready(endpoint).await {
            return true;
        }
        tokio::time::sleep(Duration::from_millis(delay)).await;
    }
    false
}

#[cfg(unix)]
async fn endpoint_has_listener(endpoint: &IpcEndpoint) -> bool {
    let Some(path) = endpoint.as_unix_socket() else {
        return false;
    };
    let path = path.to_path_buf();
    tokio::task::spawn_blocking(move || unix_socket_has_listener(&path))
        .await
        .unwrap_or(true)
}

fn remove_stale_plugin_state(
    state_dir: &Path,
    namespace: &str,
) -> Result<(), DaemonLifecycleError> {
    if namespace.is_empty()
        || namespace.len() > 256
        || !namespace
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
    {
        return Ok(());
    }
    let plugins_root = state_dir.join("derived").join("plugins");
    let namespace_root = plugins_root.join(namespace);
    let metadata = match fs::symlink_metadata(&namespace_root) {
        Ok(metadata) => metadata,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(source) => {
            return Err(DaemonLifecycleError::Io {
                path: namespace_root,
                source,
            });
        }
    };
    if !metadata.file_type().is_dir() || metadata.file_type().is_symlink() {
        return Ok(());
    }
    fs::remove_dir_all(&namespace_root).map_err(|source| DaemonLifecycleError::Io {
        path: namespace_root.clone(),
        source,
    })?;
    if fs::read_dir(&plugins_root).is_ok_and(|mut entries| entries.next().is_none()) {
        let _ = fs::remove_dir(&plugins_root);
    }
    Ok(())
}

async fn cleanup_stale_daemon_records() -> Result<(), DaemonLifecycleError> {
    let state_dir = bcode_config::default_state_dir();
    for (path, record) in read_records(&state_dir) {
        if record.is_current_namespace() {
            continue;
        }
        if !matches!(
            classify_daemon_record(&record).await,
            DaemonRecordClassification::UnreachableStale
        ) {
            continue;
        }
        remove_stale_plugin_state(&state_dir, &record.namespace)?;
        remove_record_path(&path)?;
        remove_stale_socket(&record);
    }
    Ok(())
}

#[cfg(unix)]
fn remove_stale_socket(record: &DaemonRecord) {
    if let DaemonEndpointRecord::UnixSocket { path } = &record.endpoint {
        let _ = remove_stale_unix_socket_path(path);
    }
}

#[cfg(not(unix))]
const fn remove_stale_socket(_record: &DaemonRecord) {}

#[cfg(unix)]
fn cleanup_stale_endpoint(endpoint: &IpcEndpoint) -> Result<(), DaemonLifecycleError> {
    if let Some(path) = endpoint.as_unix_socket() {
        remove_stale_unix_socket_path(path)?;
    }
    Ok(())
}

#[cfg(unix)]
fn remove_stale_unix_socket_path(path: &Path) -> Result<(), DaemonLifecycleError> {
    if !path.exists() || !is_bcode_socket_path(path) || unix_socket_has_listener(path) {
        return Ok(());
    }
    std::thread::sleep(Duration::from_millis(100));
    if unix_socket_has_listener(path) {
        return Ok(());
    }
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(source) => Err(DaemonLifecycleError::Io {
            path: path.to_path_buf(),
            source,
        }),
    }
}

#[cfg(unix)]
fn is_bcode_socket_path(path: &Path) -> bool {
    path.file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| {
            name.starts_with("bcode-")
                && Path::new(name)
                    .extension()
                    .is_some_and(|extension| extension.eq_ignore_ascii_case("sock"))
        })
}

#[cfg(unix)]
fn unix_socket_has_listener(path: &Path) -> bool {
    std::os::unix::net::UnixStream::connect(path).is_ok()
}

#[cfg(test)]
fn run_isolated_fork_fixture(test_name: &str) -> bool {
    const ENV: &str = "BCODE_ISOLATED_FORK_FIXTURE";
    if std::env::var(ENV).as_deref() == Ok(test_name) {
        return false;
    }
    // A gated pre-exec/fork child copies every live OFD in its process, not
    // merely this fixture's handles. Execute the owning test alone so that its
    // intentional gate cannot retain unrelated parallel-test fences.
    let mut child = std::process::Command::new(std::env::current_exe().unwrap())
        .args([test_name, "--exact", "--nocapture"])
        .env(ENV, test_name)
        .stdin(std::process::Stdio::null())
        .spawn()
        .expect("isolated fork fixture spawn");
    let deadline = std::time::Instant::now() + Duration::from_secs(15);
    loop {
        if let Some(status) = child.try_wait().expect("isolated fixture status") {
            assert!(
                status.success(),
                "isolated fixture failed: {test_name}: {status}"
            );
            return true;
        }
        if std::time::Instant::now() >= deadline {
            child.kill().expect("terminate timed-out fixture");
            child.wait().expect("reap timed-out fixture");
            panic!("isolated fixture deadline exceeded: {test_name}");
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

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

    #[tokio::test]
    async fn startup_lock_observations_timeout_preserve_held_file() {
        let directory = tempfile::tempdir().expect("lock directory");
        let path = directory.path().join("startup.lock");
        let owner = StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
            .await
            .expect("owner");
        let original = fs::read(&path).expect("owner hint");
        let mut observations = Vec::new();
        let result = StartupLock::acquire_observed(
            path.clone(),
            Duration::from_millis(50),
            "test-artifact.test-state",
            || std::future::ready(false),
            |event, elapsed| observations.push((event, elapsed)),
        )
        .await;
        assert!(matches!(
            result,
            Err(DaemonStartError::StartupCoordinationTimeout { .. })
        ));
        assert_eq!(observations.len(), 2);
        assert_eq!(observations[0].0, StartupLockObservation::Waiting);
        assert_eq!(observations[1].0, StartupLockObservation::Timeout);
        assert!(observations[1].1 >= Duration::from_millis(50));
        assert_eq!(fs::read(&path).expect("preserved hint"), original);
        drop(owner);
    }

    #[tokio::test]
    async fn startup_lock_observations_concurrent_ready_does_not_acquire() {
        let directory = tempfile::tempdir().expect("lock directory");
        let path = directory.path().join("startup.lock");
        let owner = StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
            .await
            .expect("owner");
        let mut observations = Vec::new();
        let result = StartupLock::acquire_observed(
            path,
            Duration::from_millis(50),
            "test-artifact.test-state",
            || std::future::ready(true),
            |event, _| observations.push(event),
        )
        .await
        .expect("ready observation");
        assert!(result.is_none());
        assert_eq!(
            observations,
            [
                StartupLockObservation::Waiting,
                StartupLockObservation::ConcurrentReady
            ]
        );
        drop(owner);
    }

    #[tokio::test]
    async fn startup_lock_observations_acquired_after_contention() {
        let directory = tempfile::tempdir().expect("lock directory");
        let path = directory.path().join("startup.lock");
        let mut owner = Some(
            StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
                .await
                .expect("owner"),
        );
        let mut observations = Vec::new();
        let replacement = StartupLock::acquire_observed(
            path,
            Duration::from_secs(1),
            "test-artifact.test-state",
            || {
                drop(owner.take());
                std::future::ready(false)
            },
            |event, _| observations.push(event),
        )
        .await
        .expect("replacement")
        .expect("acquired lock");
        assert_eq!(
            observations,
            [
                StartupLockObservation::Waiting,
                StartupLockObservation::Acquired
            ]
        );
        drop(replacement);
    }

    fn lock_path(name: &str) -> PathBuf {
        std::env::temp_dir().join(format!(
            "bcode-daemon-startup-lock-{name}-{}-{}",
            std::process::id(),
            unix_time_millis().expect("time")
        ))
    }

    #[cfg(unix)]
    #[test]
    fn stale_socket_cleanup_preserves_live_listener_then_removes_stale_path() {
        let root = PathBuf::from(format!(
            "/tmp/bcode-ds-{}-{}",
            std::process::id(),
            unix_time_millis().expect("time")
        ));
        fs::create_dir_all(&root).expect("socket directory");
        let live_path = root.join("bcode-foreign-artifact.sock");
        let listener =
            std::os::unix::net::UnixListener::bind(&live_path).expect("bind live listener");

        remove_stale_unix_socket_path(&live_path).expect("preserve live endpoint");
        assert!(live_path.exists());
        let connection = std::os::unix::net::UnixStream::connect(&live_path)
            .expect("live foreign endpoint remains reachable");
        drop(connection);
        drop(listener);

        let stale_path = root.join("bcode-stale-artifact.sock");
        drop(std::os::unix::net::UnixDatagram::bind(&stale_path).expect("bind stale socket"));
        remove_stale_unix_socket_path(&stale_path).expect("remove stale endpoint");
        assert!(!stale_path.exists());
        fs::remove_file(live_path).expect("live socket cleanup");
        fs::remove_dir_all(root).expect("socket directory cleanup");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn occupied_unresponsive_endpoint_does_not_start_competing_daemon() {
        let root = PathBuf::from(format!(
            "/tmp/bcode-do-{}-{}",
            std::process::id(),
            unix_time_millis().expect("time")
        ));
        fs::create_dir_all(&root).expect("socket directory");
        let socket_path = root.join("bcode-occupied.sock");
        let listener =
            std::os::unix::net::UnixListener::bind(&socket_path).expect("bind occupied endpoint");
        let options = EnsureDaemonOptions {
            endpoint: IpcEndpoint::unix_socket(socket_path.clone()),
            quiet: true,
            log_path: root.join("daemon.log"),
        };
        let starts = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let observed_starts = std::sync::Arc::clone(&starts);
        let error = ensure_daemon_running_with_start(&options, move |_, _| {
            observed_starts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            async { Ok(()) }
        })
        .await
        .expect_err("occupied endpoint must block startup");

        assert!(matches!(error, DaemonStartError::EndpointOccupied { .. }));
        assert_eq!(starts.load(std::sync::atomic::Ordering::SeqCst), 0);
        drop(listener);
        fs::remove_file(socket_path).expect("socket cleanup");
        fs::remove_dir_all(root).expect("directory cleanup");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn notification_timeout_preserves_failure_and_does_not_terminate_child() {
        let directory = tempfile::tempdir().expect("notification directory");
        let endpoint = IpcEndpoint::unix_socket(directory.path().join("absent.sock"));
        let release = directory.path().join("release");
        let late = directory.path().join("late");
        let mut child = tokio::process::Command::new("sh")
            .args([
                "-c",
                "trap '' PIPE; while [ ! -f \"$1\" ]; do sleep 0.01; done; printf late > \"$2\"; printf 'BCODE_READY_V1\\n' 2>/dev/null || :; exec sleep 30",
                "notification-test",
            ])
            .arg(&release)
            .arg(&late)
            .stdout(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .expect("notification child");
        let result = wait_for_child_notification_with_timeout(
            &endpoint,
            &mut child,
            &directory.path().join("daemon.log"),
            Duration::ZERO,
        )
        .await;
        assert!(matches!(
            result,
            Err(DaemonStartError::NotificationTimeout { .. })
        ));
        assert!(child.try_wait().expect("observe child").is_none());
        fs::write(&release, b"release").expect("release late notification");
        tokio::time::timeout(Duration::from_secs(5), async {
            while !late.exists() {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("child continued after deadline");
        child.kill().await.expect("stop child");
        // A later notification cannot change the already returned failure into readiness.
        assert!(matches!(
            result,
            Err(DaemonStartError::NotificationTimeout { .. })
        ));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn readiness_notification_does_not_substitute_for_identity_verification() {
        let directory = tempfile::tempdir().expect("notification directory");
        let endpoint = IpcEndpoint::unix_socket(directory.path().join("absent.sock"));
        let published = directory.path().join("notification-published");
        let mut child = tokio::process::Command::new("sh")
            .args([
                "-c",
                "printf 'BCODE_READY_V1\\n'; printf ready > \"$1\"; exec sleep 30",
                "notification",
            ])
            .arg(&published)
            .stdout(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .expect("notification child");
        // This test targets identity verification after notification, not shell
        // scheduling within the 100ms handshake budget. Gate that boundary.
        tokio::time::timeout(Duration::from_secs(3), async {
            while !published.exists() {
                assert!(child.try_wait().expect("fixture status").is_none());
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("fixture did not publish readiness notification");
        let result = super::wait_for_child_notification_with_timeout(
            &endpoint,
            &mut child,
            &directory.path().join("daemon.log"),
            Duration::from_millis(100),
        )
        .await;
        child.kill().await.expect("stop child");
        assert!(
            matches!(&result, Err(DaemonStartError::HealthCheckFailed { .. })),
            "expected verified-handshake failure after published notification; actual={result:?}"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn unsupported_readiness_notification_fails_closed() {
        let directory = tempfile::tempdir().expect("notification directory");
        let endpoint = IpcEndpoint::unix_socket(directory.path().join("absent.sock"));
        let mut child = tokio::process::Command::new("sh")
            .args(["-c", "printf 'BCODE_READY_V2\\n'; exec sleep 30"])
            .stdout(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .expect("notification child");
        let result = super::wait_for_child_notification(
            &endpoint,
            &mut child,
            &directory.path().join("daemon.log"),
        )
        .await;
        child.kill().await.expect("stop child");
        assert!(matches!(result, Err(DaemonStartError::Io(_))));
    }

    #[tokio::test]
    async fn startup_locks_isolate_scopes_and_fence_same_scope() {
        let directory = tempfile::tempdir().unwrap();
        let first_path = super::startup_lock_path(directory.path(), "artifact", "scope-a");
        std::fs::create_dir_all(first_path.parent().unwrap()).unwrap();
        let first = StartupLock::acquire_at(first_path.clone(), Duration::from_secs(1))
            .await
            .unwrap();
        let second = StartupLock::acquire_at(
            super::startup_lock_path(directory.path(), "artifact", "scope-b"),
            Duration::from_secs(1),
        )
        .await
        .unwrap();
        assert!(matches!(
            StartupLock::acquire_at(first_path, Duration::from_millis(50)).await,
            Err(DaemonStartError::StartupCoordinationTimeout { .. })
        ));
        drop((first, second));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn startup_lock_probe_timeout_is_bounded_and_preserves_descriptor() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("startup.lock");
        let owner = StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
            .await
            .unwrap();
        let descriptor =
            super::StartupOwnerDescriptor::current("handoff_pending", "test".to_owned()).unwrap();
        super::write_startup_owner(&owner.file, &descriptor).unwrap();
        let original = fs::read(&path).unwrap();
        let result = tokio::time::timeout(
            Duration::from_secs(1),
            StartupLock::acquire_observed(
                path.clone(),
                Duration::from_millis(40),
                "test",
                std::future::pending::<bool>,
                |_, _| {},
            ),
        )
        .await
        .unwrap();
        assert!(matches!(
            result,
            Err(DaemonStartError::StartupCoordinationTimeout { .. })
        ));
        assert_eq!(fs::read(&path).unwrap(), original);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn startup_descriptor_symlink_is_rejected_without_modifying_target() {
        let directory = tempfile::tempdir().unwrap();
        let target = directory.path().join("target");
        let path = directory.path().join("startup.lock");
        fs::write(&target, b"preserve").unwrap();
        std::os::unix::fs::symlink(&target, &path).unwrap();
        assert!(
            StartupLock::acquire_observed(
                path,
                Duration::from_millis(40),
                "test",
                || std::future::ready(false),
                |_, _| {}
            )
            .await
            .is_err()
        );
        assert_eq!(fs::read(target).unwrap(), b"preserve");
    }

    #[cfg(unix)]
    #[test]
    fn startup_descriptor_handoff_child() {
        use std::os::fd::BorrowedFd;

        let Ok(path) = std::env::var("BCODE_TEST_STARTUP_DESCRIPTOR") else {
            return;
        };
        let file = fs::File::from(
            unsafe { BorrowedFd::borrow_raw(0) }
                .try_clone_to_owned()
                .unwrap(),
        );
        super::publish_startup_owner_at(&file, Path::new(&path), "test-handoff").unwrap();
        super::close_startup_stdin_on_exec().unwrap();
        // A surviving exec descendant must not retain the daemon's lifetime fence.
        let mut grandchild_command = std::process::Command::new("sh");
        let grandchild_release = format!("{path}.grandchild-release");
        let mut grandchild = grandchild_command
            .args([
                "-c",
                "n=0; while [ ! -f \"$1\" ] && [ \"$n\" -lt 500 ]; do sleep 0.01; n=$((n+1)); done",
                "grandchild",
            ])
            .arg(&grandchild_release)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
            .unwrap();
        drop(grandchild_command);
        fs::write(
            format!("{path}.grandchild-pid"),
            grandchild.id().to_string(),
        )
        .unwrap();
        // Own the wait while this fixture process lives. On deliberate daemon
        // exit its surviving descendant is reparented to the OS reaper.
        std::thread::spawn(move || grandchild.wait().expect("grandchild wait"));
        println!("descriptor-published");
        std::io::stdout().flush().unwrap();
        // Separate release channel: never read the descriptor through shared stdin.
        let release = format!("{path}.release");
        let deadline = std::time::Instant::now() + Duration::from_secs(5);
        while !Path::new(&release).exists() {
            assert!(std::time::Instant::now() < deadline);
            std::thread::sleep(Duration::from_millis(10));
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn startup_descriptor_detached_child_replaces_launcher_claim_and_retains_fence() {
        use tokio::io::{AsyncBufReadExt as _, BufReader};

        const FIXTURE: &str = "BCODE_TEST_DESCRIPTOR_ISOLATED";
        if std::env::var_os(FIXTURE).is_none() {
            let mut child = tokio::process::Command::new(std::env::current_exe().unwrap())
                .args(["startup_lock_tests::startup_descriptor_detached_child_replaces_launcher_claim_and_retains_fence", "--exact", "--nocapture"])
                .env(FIXTURE, "1")
                .stdin(std::process::Stdio::null())
                .kill_on_drop(true)
                .spawn().unwrap();
            assert!(
                tokio::time::timeout(Duration::from_secs(10), child.wait())
                    .await
                    .unwrap()
                    .unwrap()
                    .success()
            );
            return;
        }
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("startup.lock");
        let owner = StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
            .await
            .unwrap();
        let pending =
            super::StartupOwnerDescriptor::current("handoff_pending", "test-handoff".to_owned())
                .unwrap();
        super::write_startup_owner(&owner.file, &pending).unwrap();
        let mut command = tokio::process::Command::new(std::env::current_exe().unwrap());
        super::detach_daemon_process(&mut command);
        let mut child = command
            .args([
                "startup_lock_tests::startup_descriptor_handoff_child",
                "--exact",
                "--nocapture",
            ])
            .env("BCODE_TEST_STARTUP_DESCRIPTOR", &path)
            .stdin(super::startup_lock_stdio(owner.file.try_clone().unwrap()))
            .stdout(std::process::Stdio::piped())
            .kill_on_drop(true)
            .spawn()
            .unwrap();
        // Command retains its configured Stdio even after spawn; it must not
        // remain a second launcher-side owner during the release assertion.
        drop(command);
        let child_pid = child.id().unwrap();
        let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
        let mut published = false;
        tokio::time::timeout(Duration::from_secs(3), async {
            while let Some(line) = lines.next_line().await.unwrap() {
                if line.contains("descriptor-published") {
                    published = true;
                    break;
                }
            }
        })
        .await
        .unwrap();
        assert!(published);
        drop(owner);
        let file = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&path)
            .unwrap();
        let actual = super::read_startup_owner(&file).unwrap().unwrap();
        assert_eq!(actual.pid, child_pid);
        assert_ne!(actual.pid, pending.pid);
        assert_eq!(actual.phase, "daemon_ready");
        assert!(matches!(
            file.try_lock(),
            Err(std::fs::TryLockError::WouldBlock)
        ));
        assert!(super::publish_startup_owner_at(&file, &path, "test-handoff").is_err());
        assert_eq!(
            super::read_startup_owner(&file).unwrap().unwrap().pid,
            child_pid
        );
        fs::write(path.with_extension("lock.release"), b"release").unwrap();
        assert!(
            tokio::time::timeout(Duration::from_secs(3), child.wait())
                .await
                .unwrap()
                .unwrap()
                .success()
        );
        let grandchild_pid: u32 = fs::read_to_string(format!("{}.grandchild-pid", path.display()))
            .unwrap()
            .parse()
            .unwrap();
        // SAFETY: signal zero only observes the isolated fixture descendant.
        assert_eq!(
            unsafe { libc::kill(i32::try_from(grandchild_pid).unwrap(), 0) },
            0
        );
        let release_result = file.try_lock();
        // Release the fixture descendant even if the lock assertion fails.
        fs::write(format!("{}.grandchild-release", path.display()), b"release").unwrap();
        release_result.unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn startup_descriptor_rejects_foreign_future_legacy_and_reused_process() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("startup.lock");
        let file = fs::OpenOptions::new()
            .create(true)
            .truncate(true)
            .read(true)
            .write(true)
            .open(&path)
            .unwrap();
        file.lock().unwrap();
        let mut owner =
            super::StartupOwnerDescriptor::current("handoff_pending", "test".to_owned()).unwrap();
        owner.process_start_seconds = owner.process_start_seconds.saturating_add(1);
        assert!(!owner.process_verified());
        for (version, state) in [(2, owner.state.clone()), (1, "foreign".to_owned())] {
            owner.version = version;
            owner.state = state;
            super::write_startup_owner(&file, &owner).unwrap();
            let before = fs::read(&path).unwrap();
            assert!(super::publish_startup_owner_at(&file, &path, "test").is_err());
            assert_eq!(fs::read(&path).unwrap(), before);
        }
        fs::write(&path, b"pid=123\n").unwrap();
        assert!(super::read_startup_owner(&file).unwrap().is_none());
        assert!(super::publish_startup_owner_at(&file, &path, "test").is_err());
        let other = directory.path().join("other.lock");
        fs::write(&other, b"").unwrap();
        assert!(super::publish_startup_owner_at(&file, &other, "test").is_err());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn inherited_startup_lock_fences_launchers_until_child_exit() {
        let directory = tempfile::tempdir().expect("lock directory");
        let path = directory.path().join("startup.lock");
        let owner = StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
            .await
            .expect("launcher lock");
        let inherited = owner.file.try_clone().expect("inherited lock");
        let mut child = tokio::process::Command::new("sleep")
            .arg("30")
            .stdin(super::startup_lock_stdio(inherited))
            .kill_on_drop(true)
            .spawn()
            .expect("spawn child before endpoint publication");
        drop(owner);
        let result = StartupLock::acquire_at(path.clone(), Duration::from_millis(75)).await;
        assert!(matches!(
            result,
            Err(DaemonStartError::StartupCoordinationTimeout { .. })
        ));
        child.kill().await.expect("stop child");
        let replacement = StartupLock::acquire_at(path, Duration::from_secs(1))
            .await
            .expect("ownership released only after child exit");
        drop(replacement);
    }

    #[cfg(unix)]
    struct HandshakeChild {
        release: Option<std::io::PipeWriter>,
        spawning: Option<std::thread::JoinHandle<std::io::Result<std::process::Child>>>,
        child: Option<std::process::Child>,
        readers: Vec<std::thread::JoinHandle<()>>,
    }

    #[cfg(unix)]
    static INCOMPLETE_HANDSHAKE_CLEANUP: std::sync::Mutex<Vec<HandshakeChild>> =
        std::sync::Mutex::new(Vec::new());

    #[cfg(unix)]
    impl HandshakeChild {
        fn release_preexec(&mut self) {
            // At most two one-byte releases are written to a fresh pipe, so
            // this cannot fill its buffer. EOF alone cannot release the child:
            // it inherited a copy of the parent's write end too.
            if let Some(mut release) = self.release.take() {
                use std::io::Write as _;
                let _ = release.write_all(b"G");
            }
        }

        fn collect_spawn_if_finished(&mut self) {
            if self
                .spawning
                .as_ref()
                .is_some_and(std::thread::JoinHandle::is_finished)
                && let Some(spawning) = self.spawning.take()
                && let Ok(Ok(child)) = spawning.join()
            {
                self.child = Some(child);
            }
        }

        fn cleanup_until(&mut self, deadline: std::time::Instant) -> bool {
            self.release_preexec();
            loop {
                self.collect_spawn_if_finished();
                if let Some(child) = self.child.as_mut() {
                    let _ = child.kill();
                    // try_wait reaps an exited child without blocking. Keep
                    // ownership on errors as well as a still-running result.
                    if matches!(child.try_wait(), Ok(Some(_))) {
                        self.child = None;
                    }
                }
                let mut index = 0;
                while index < self.readers.len() {
                    if self.readers[index].is_finished() {
                        let _ = self.readers.swap_remove(index).join();
                    } else {
                        index += 1;
                    }
                }
                if self.spawning.is_none() && self.child.is_none() && self.readers.is_empty() {
                    return true;
                }
                if std::time::Instant::now() >= deadline {
                    return false;
                }
                std::thread::yield_now();
            }
        }
    }

    #[cfg(unix)]
    impl Drop for HandshakeChild {
        fn drop(&mut self) {
            if !self.cleanup_until(std::time::Instant::now() + Duration::from_secs(1)) {
                eprintln!(
                    "handshake_cleanup_timeout: budget_ms=1000, spawn_pending={}, child_pid={:?}, readers_pending={}, ownership=retained",
                    self.spawning.is_some(),
                    self.child.as_ref().map(std::process::Child::id),
                    self.readers.len()
                );
                // Static storage deliberately retains all unfinished ownership
                // until test-process exit. Never detach join handles, discard
                // an unreaped child, or falsely report cleanup completion.
                let retained = Self {
                    release: self.release.take(),
                    spawning: self.spawning.take(),
                    child: self.child.take(),
                    readers: std::mem::take(&mut self.readers),
                };
                match INCOMPLETE_HANDSHAKE_CLEANUP.try_lock() {
                    Ok(mut retained_cleanup) => retained_cleanup.push(retained),
                    Err(std::sync::TryLockError::Poisoned(error)) => {
                        error.into_inner().push(retained);
                    }
                    Err(std::sync::TryLockError::WouldBlock) => {
                        // Even the retention registry must not block Drop.
                        // Preserve an addressable owner rather than dropping
                        // its child or detaching its join handles.
                        let retained = Box::leak(Box::new(retained));
                        eprintln!("handshake_cleanup_retained_owner: address={retained:p}");
                    }
                }
            }
        }
    }

    #[cfg(unix)]
    fn handshake_marker(
        reader: impl std::io::Read + Send + 'static,
        owner: &mut HandshakeChild,
    ) -> std::sync::mpsc::Receiver<std::io::Result<u8>> {
        let (sender, receiver) = std::sync::mpsc::channel();
        owner.readers.push(std::thread::spawn(move || {
            let mut reader = reader;
            let mut marker = [0_u8];
            let result = reader.read_exact(&mut marker).map(|()| marker[0]);
            let _ = sender.send(result);
        }));
        receiver
    }

    #[cfg(unix)]
    fn spawn_handshake_child(
        ready_write: std::io::PipeWriter,
        release_read: std::io::PipeReader,
        emit_ready: bool,
    ) -> std::thread::JoinHandle<std::io::Result<std::process::Child>> {
        use std::os::fd::AsRawFd as _;
        use std::os::unix::process::CommandExt as _;

        let ready_fd = ready_write.as_raw_fd();
        let release_fd = release_read.as_raw_fd();
        std::thread::spawn(move || {
            let mut command = std::process::Command::new("sh");
            command
                .args(["-c", "printf E; exec sleep 30"])
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::null());
            // SAFETY: the child closure only uses async-signal-safe pipe write,
            // read and _exit, stack bytes, and returns Ok after release. No
            // allocation, locks, logging, or runtime callbacks occur after fork.
            // The spawning thread owns both descriptors until spawn returns;
            // the parent guard sends release, observes finished spawn, then
            // kills and polls reaping within its deadline. On timeout it retains
            // every unfinished owner, including during assertion unwinding.
            unsafe {
                command.pre_exec(move || {
                    let ready = b'R';
                    if emit_ready
                        && libc::write(ready_fd, std::ptr::from_ref(&ready).cast(), 1) != 1
                    {
                        libc::_exit(125);
                    }
                    let mut release = 0_u8;
                    if libc::read(release_fd, std::ptr::from_mut(&mut release).cast(), 1) != 1
                        || release != b'G'
                    {
                        libc::_exit(126);
                    }
                    Ok(())
                });
            }
            let result = command.spawn();
            drop(command);
            drop((ready_write, release_read));
            result
        })
    }

    #[cfg(unix)]
    fn release_child_and_observe_exec(owner: &mut HandshakeChild) {
        use std::io::Write as _;

        owner
            .release
            .as_mut()
            .expect("release writer")
            .write_all(b"G")
            .expect("release child to exec");
        let deadline = std::time::Instant::now() + Duration::from_secs(1);
        while owner.spawning.is_some() {
            owner.collect_spawn_if_finished();
            assert!(
                owner.spawning.is_none() || std::time::Instant::now() < deadline,
                "exec_spawn_timeout: budget_ms=1000, ownership=retained"
            );
            std::thread::yield_now();
        }
        let stdout = owner
            .child
            .as_mut()
            .expect("owned child")
            .stdout
            .take()
            .expect("post-exec readiness pipe");
        let postexec_ready = handshake_marker(stdout, owner);
        assert_eq!(
            postexec_ready
                .recv_timeout(Duration::from_secs(1))
                .expect("post-exec readiness deadline")
                .expect("post-exec readiness byte"),
            b'E'
        );
    }

    #[cfg(unix)]
    async fn observe_lock_release(
        contender: &fs::File,
        path: &Path,
        deadline: tokio::time::Instant,
    ) {
        // Local close need not release a description copied by another test's
        // pre-exec child. Reuse the existing 75 ms observation budget; never
        // delete the file, unlock another description, or wait for child exit.
        loop {
            match contender.try_lock() {
                Ok(()) => break,
                Err(std::fs::TryLockError::WouldBlock) => {
                    assert!(
                        tokio::time::Instant::now() < deadline,
                        "lock_release_timeout: fixture={}, budget_ms=75, holder=unknown",
                        path.display()
                    );
                    tokio::task::yield_now().await;
                }
                Err(error) => panic!(
                    "unexpected lock release error: fixture={}, error={error}",
                    path.display()
                ),
            }
        }
    }

    #[cfg(unix)]
    #[test]
    fn startup_lock_missing_preexec_readiness_has_bounded_owned_cleanup() {
        if super::run_isolated_fork_fixture(
            "startup_lock_tests::startup_lock_missing_preexec_readiness_has_bounded_owned_cleanup",
        ) {
            return;
        }
        let (ready_read, ready_write) = std::io::pipe().expect("ready pipe");
        let (release_read, release_write) = std::io::pipe().expect("release pipe");
        let mut owner = HandshakeChild {
            release: Some(release_write),
            spawning: None,
            child: None,
            readers: Vec::new(),
        };
        let readiness = handshake_marker(ready_read, &mut owner);
        owner.spawning = Some(spawn_handshake_child(ready_write, release_read, false));
        assert!(matches!(
            readiness.recv_timeout(Duration::from_millis(75)),
            Err(std::sync::mpsc::RecvTimeoutError::Timeout)
        ));
        assert!(owner.cleanup_until(std::time::Instant::now() + Duration::from_secs(1)));
        assert!(owner.spawning.is_none() && owner.child.is_none() && owner.readers.is_empty());
    }

    #[cfg(unix)]
    #[test]
    fn startup_lock_cleanup_expiry_preserves_unfinished_reader_ownership() {
        let (reader, writer) = std::io::pipe().expect("held readiness pipe");
        let mut owner = HandshakeChild {
            release: None,
            spawning: None,
            child: None,
            readers: Vec::new(),
        };
        let readiness = handshake_marker(reader, &mut owner);
        assert!(matches!(
            readiness.recv_timeout(Duration::from_millis(75)),
            Err(std::sync::mpsc::RecvTimeoutError::Timeout)
        ));
        assert!(!owner.cleanup_until(std::time::Instant::now()));
        assert_eq!(owner.readers.len(), 1);
        drop(writer);
        assert!(owner.cleanup_until(std::time::Instant::now() + Duration::from_secs(1)));
        assert!(owner.readers.is_empty());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn startup_lock_preexec_listener_retention_ends_at_exec() {
        use std::os::fd::AsRawFd as _;

        if super::run_isolated_fork_fixture(
            "startup_lock_tests::startup_lock_preexec_listener_retention_ends_at_exec",
        ) {
            return;
        }
        let directory = tempfile::tempdir().expect("handshake directory");
        let lock_path = directory.path().join("startup.lock");
        let lock = StartupLock::acquire_at(lock_path.clone(), Duration::from_secs(1))
            .await
            .expect("fixture startup lock");
        let contender = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&lock_path)
            .expect("independent fixture contender");
        // SAFETY: F_GETFD only inspects this live, owned fixture description.
        let lock_flags = unsafe { libc::fcntl(lock.file.as_raw_fd(), libc::F_GETFD) };
        assert!(lock_flags >= 0 && lock_flags & libc::FD_CLOEXEC != 0);
        let socket = directory.path().join("daemon.sock");
        let listener = std::os::unix::net::UnixListener::bind(&socket).expect("listener");
        // SAFETY: F_GETFD only inspects this live, owned listener descriptor.
        let flags = unsafe { libc::fcntl(listener.as_raw_fd(), libc::F_GETFD) };
        assert!(flags >= 0 && flags & libc::FD_CLOEXEC != 0);
        let (ready_read, ready_write) = std::io::pipe().expect("pre-exec ready pipe");
        let (release_read, release_write) = std::io::pipe().expect("pre-exec release pipe");
        let mut owner = HandshakeChild {
            release: Some(release_write),
            spawning: None,
            child: None,
            readers: Vec::new(),
        };
        let preexec_ready = handshake_marker(ready_read, &mut owner);
        owner.spawning = Some(spawn_handshake_child(ready_write, release_read, true));
        assert_eq!(
            preexec_ready
                .recv_timeout(Duration::from_secs(1))
                .expect("pre-exec readiness deadline")
                .expect("pre-exec readiness byte"),
            b'R'
        );
        drop(listener);
        drop(lock);
        assert!(matches!(
            contender.try_lock(),
            Err(std::fs::TryLockError::WouldBlock)
        ));
        // This unique fixture's owned descriptions were closed in the parent;
        // the acknowledged child retains both socket and lock until exec.
        // The acknowledged child is still before exec and genuinely retains
        // the parent's CLOEXEC socket, despite the parent's local drop.
        let retained = tokio::time::timeout(
            Duration::from_millis(75),
            tokio::net::UnixStream::connect(&socket),
        )
        .await
        .expect("pre-exec connection deadline")
        .expect("pre-exec child retains listener");
        drop(retained);
        release_child_and_observe_exec(&mut owner);
        let deadline = tokio::time::Instant::now() + Duration::from_millis(75);
        loop {
            let connection =
                tokio::time::timeout_at(deadline, tokio::net::UnixStream::connect(&socket))
                    .await
                    .expect("post-exec connection deadline");
            match connection {
                Err(error) if error.kind() == std::io::ErrorKind::ConnectionRefused => break,
                Err(error) => panic!("unexpected post-exec connection error: {error}"),
                Ok(stream) => {
                    drop(stream);
                    assert!(
                        tokio::time::Instant::now() < deadline,
                        "listener retained after acknowledged exec"
                    );
                    tokio::task::yield_now().await;
                }
            }
        }
        observe_lock_release(&contender, &lock_path, deadline).await;
        assert!(
            owner
                .child
                .as_mut()
                .expect("owned child")
                .try_wait()
                .expect("child status")
                .is_none(),
            "listener refusal and lock release must precede child exit"
        );
        assert!(
            owner.cleanup_until(std::time::Instant::now() + Duration::from_secs(1)),
            "handshake_cleanup_timeout: budget_ms=1000, ownership=retained"
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn listener_release_during_gated_cleanup_retains_inherited_startup_fence() {
        // Parallel pre-exec fixtures deliberately retain every open description
        // until their gate opens. Isolate this lifetime test instead of guessing
        // that another fixture has exec'd within the 75ms observation budget.
        const FIXTURE: &str = "BCODE_TEST_GATED_FENCE_ISOLATED";
        if std::env::var_os(FIXTURE).is_none() {
            let mut child = tokio::process::Command::new(std::env::current_exe().unwrap())
                .args(["startup_lock_tests::listener_release_during_gated_cleanup_retains_inherited_startup_fence", "--exact", "--nocapture"])
                .env(FIXTURE, "1")
                .stdin(std::process::Stdio::null())
                .kill_on_drop(true)
                .spawn().unwrap();
            assert!(
                tokio::time::timeout(Duration::from_secs(3), child.wait())
                    .await
                    .unwrap()
                    .unwrap()
                    .success()
            );
            return;
        }
        let directory = tempfile::tempdir().expect("temporary daemon directory");
        let path = directory.path().join("startup.lock");
        let owner = StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
            .await
            .expect("launcher lock");
        let inherited = startup_lock_stdio(owner.file.try_clone().expect("inherited lock"));
        drop(owner);
        let socket = directory.path().join("daemon.sock");
        let listener = std::os::unix::net::UnixListener::bind(&socket).expect("listener");
        let contender = fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&path)
            .expect("contender description");
        let (release, gate) = tokio::sync::oneshot::channel();
        let cleanup = async move {
            drop(listener);
            gate.await.expect("cleanup release");
            // Model the daemon's lifetime stdin: release only after cleanup settles.
            drop(inherited);
        };
        tokio::pin!(cleanup);
        std::future::poll_fn(|cx| {
            assert!(std::future::Future::poll(cleanup.as_mut(), cx).is_pending());
            std::task::Poll::Ready(())
        })
        .await;
        // A concurrent spawn can briefly retain the listener until exec. Local
        // drop is not proof that every process has released its description.
        // Keep cleanup gated and require the startup fence on every observation;
        // a persistent inherited listener must fail, not be hidden by cleanup.
        let refusal_deadline = tokio::time::Instant::now() + Duration::from_millis(75);
        loop {
            assert!(matches!(
                contender.try_lock(),
                Err(std::fs::TryLockError::WouldBlock)
            ));
            let connection =
                tokio::time::timeout_at(refusal_deadline, tokio::net::UnixStream::connect(&socket))
                    .await
                    .expect("listener connection did not settle within the refusal budget");
            match connection {
                Err(error) if error.kind() == std::io::ErrorKind::ConnectionRefused => break,
                Err(error) => panic!("unexpected stale-listener connection error: {error}"),
                Ok(stream) => {
                    drop(stream);
                    assert!(
                        tokio::time::Instant::now() < refusal_deadline,
                        "listener still accepts connections while cleanup is gated"
                    );
                    tokio::task::yield_now().await;
                }
            }
        }
        assert!(matches!(
            contender.try_lock(),
            Err(std::fs::TryLockError::WouldBlock)
        ));
        release.send(()).expect("cleanup still owns lifetime fence");
        cleanup.await;
        observe_lock_release(&contender, &path, refusal_deadline).await;
    }

    #[tokio::test]
    async fn concurrent_startup_lock_holders_are_exclusive() {
        let directory = tempfile::tempdir().expect("lock directory");
        let path = directory.path().join("startup.lock");
        let active = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let barrier = std::sync::Arc::new(tokio::sync::Barrier::new(16));
        let mut tasks = tokio::task::JoinSet::new();
        for _ in 0..16 {
            let path = path.clone();
            let active = active.clone();
            let barrier = barrier.clone();
            tasks.spawn(async move {
                barrier.wait().await;
                let lock = StartupLock::acquire_at(path, Duration::from_secs(5))
                    .await
                    .expect("acquire startup lock");
                assert_eq!(active.fetch_add(1, std::sync::atomic::Ordering::SeqCst), 0);
                tokio::task::yield_now().await;
                assert_eq!(active.fetch_sub(1, std::sync::atomic::Ordering::SeqCst), 1);
                drop(lock);
            });
        }
        while let Some(result) = tasks.join_next().await {
            result.expect("exclusive holder task");
        }
    }

    #[tokio::test]
    async fn startup_lock_waits_for_owner_instead_of_stealing_lock_file() {
        let path = lock_path("wait");
        let first = StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
            .await
            .expect("first lock");
        let waiter_path = path.clone();
        let waiter = tokio::spawn(async move {
            StartupLock::acquire_at(waiter_path, Duration::from_secs(1)).await
        });
        tokio::time::sleep(Duration::from_millis(100)).await;
        assert!(!waiter.is_finished());
        drop(first);
        let second = waiter.await.expect("waiter task").expect("second lock");
        drop(second);
        let _ = fs::remove_file(path);
    }

    #[tokio::test]
    async fn startup_lock_crash_helper() {
        let Some(path) = std::env::var_os("BCODE_STARTUP_LOCK_CRASH_PATH") else {
            return;
        };
        let marker =
            std::env::var_os("BCODE_STARTUP_LOCK_CRASH_MARKER").expect("crash helper marker path");
        let _lock = StartupLock::acquire_at(PathBuf::from(path), Duration::from_secs(2))
            .await
            .expect("crash helper lock");
        fs::write(marker, b"locked").expect("write crash helper marker");
        tokio::time::sleep(Duration::from_millis(250)).await;
        std::process::exit(70);
    }

    #[tokio::test]
    async fn startup_lock_owner_crash_permits_bounded_takeover() {
        let path = lock_path("crash");
        let marker = path.with_extension("locked");
        let mut child = tokio::process::Command::new(std::env::current_exe().expect("test binary"))
            .args(["startup_lock_crash_helper", "--nocapture"])
            .env("BCODE_STARTUP_LOCK_CRASH_PATH", &path)
            .env("BCODE_STARTUP_LOCK_CRASH_MARKER", &marker)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
            .expect("spawn crash helper");

        let marker_deadline = tokio::time::Instant::now() + Duration::from_secs(2);
        while !marker.exists() {
            assert!(
                tokio::time::Instant::now() < marker_deadline,
                "crash helper did not acquire startup lock"
            );
            assert!(
                child.try_wait().expect("query crash helper").is_none(),
                "crash helper exited before acquiring startup lock"
            );
            tokio::time::sleep(Duration::from_millis(10)).await;
        }

        let replacement = StartupLock::acquire_at(path.clone(), Duration::from_secs(2))
            .await
            .expect("take over lock after owner crash");
        let status = child.wait().await.expect("wait for crash helper");
        assert!(!status.success());
        drop(replacement);
        let _ = fs::remove_file(path);
        let _ = fs::remove_file(marker);
    }

    #[test]
    fn startup_errors_preserve_actionable_log_context() {
        let log_path = PathBuf::from("/tmp/bcode-daemon-test.log");
        let recent_log = "fatal startup detail\n".to_owned();
        let exited = DaemonStartError::Exited {
            status: "exit status: 70".to_owned(),
            log_path: log_path.display().to_string(),
            recent_log: recent_log.clone(),
        };
        let timeout = DaemonStartError::StartTimeout {
            log_path: log_path.display().to_string(),
            recent_log,
        };

        for error in [exited, timeout] {
            let message = error.to_string();
            assert!(message.contains("/tmp/bcode-daemon-test.log"));
            assert!(message.contains("fatal startup detail"));
            assert!(message.contains("bcode server run"));
        }
    }

    #[test]
    fn recent_log_excerpt_is_bounded_to_latest_context() {
        let path = lock_path("recent-log");
        let contents = (0..40)
            .map(|line| format!("line-{line}"))
            .collect::<Vec<_>>()
            .join("\n");
        fs::write(&path, contents).expect("write test log");

        let excerpt = recent_log_excerpt(&path);

        assert!(!excerpt.contains("line-0\n"));
        assert!(excerpt.starts_with("line-10\n"));
        assert!(excerpt.ends_with("line-39\n"));
        fs::remove_file(path).expect("remove test log");
    }

    #[tokio::test]
    async fn startup_lock_times_out_without_removing_active_owner() {
        let path = lock_path("timeout");
        let first = StartupLock::acquire_at(path.clone(), Duration::from_secs(1))
            .await
            .expect("first lock");
        let error = StartupLock::acquire_at(path.clone(), Duration::from_millis(50))
            .await
            .expect_err("active owner must not be replaced");
        assert!(matches!(
            error,
            DaemonStartError::StartupCoordinationTimeout { lock_path } if lock_path == path
        ));
        assert!(path.exists());
        drop(first);
        let _ = fs::remove_file(path);
    }
}

fn recent_log_excerpt(log_path: &Path) -> String {
    let Ok(contents) = fs::read_to_string(log_path) else {
        return "daemon log could not be read".to_string();
    };
    let lines = contents.lines().rev().take(30).collect::<Vec<_>>();
    if lines.is_empty() {
        return "daemon log is empty".to_string();
    }
    let mut excerpt = lines.into_iter().rev().collect::<Vec<_>>().join("\n");
    if !excerpt.ends_with('\n') {
        excerpt.push('\n');
    }
    excerpt
}