agent-team-mail-core 0.44.8

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

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Protocol version for the socket JSON protocol.
pub const PROTOCOL_VERSION: u32 = 1;

/// Lock metadata written by the daemon after acquiring the singleton lock.
///
/// This metadata is used by CLI autostart/health paths to validate daemon
/// identity (PID/home scope/executable) before trusting a pre-existing process.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DaemonLockMetadata {
    /// Daemon PID that currently owns the lock.
    pub pid: u32,
    /// Canonicalized executable path of the daemon process when available.
    pub executable_path: String,
    /// Canonicalized ATM home scope used by the daemon instance.
    pub home_scope: String,
    /// Daemon version string.
    pub version: String,
    /// RFC3339 UTC timestamp for metadata write.
    pub written_at: String,
}

/// Identifies the origin of a lifecycle event sent via the `hook-event` command.
///
/// The `source` field is optional in the hook-event payload for backward
/// compatibility — callers that do not set it will produce payloads that
/// deserialise successfully, defaulting to [`LifecycleSourceKind::Unknown`].
///
/// # Validation policy
///
/// | `kind`        | `session_start` / `session_end` restriction          |
/// |---------------|------------------------------------------------------|
/// | `claude_hook` | Team-lead only (strictest)                           |
/// | `unknown`     | Treated as `claude_hook` (fail-closed default)       |
/// | `atm_mcp`     | Any team member (MCP proxy manages its own sessions) |
/// | `agent_hook`  | Any team member (same policy as `atm_mcp`)           |
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LifecycleSource {
    /// Discriminator string identifying the lifecycle event origin.
    pub kind: LifecycleSourceKind,
}

impl LifecycleSource {
    /// Create a [`LifecycleSource`] with the given kind.
    pub fn new(kind: LifecycleSourceKind) -> Self {
        Self { kind }
    }
}

/// Discriminator for the origin of a lifecycle event.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LifecycleSourceKind {
    /// Event originated from a Claude Code hook (e.g., `session-start.py`).
    ///
    /// Strictest validation: only the team-lead may emit `session_start` and
    /// `session_end` events from this source.
    ClaudeHook,
    /// Event originated from the `atm-agent-mcp` proxy.
    ///
    /// Relaxed validation: any team member may emit lifecycle events because
    /// the MCP proxy manages its own Codex agent sessions, not the team-lead's
    /// Claude Code session.
    AtmMcp,
    /// Event originated from a non-Claude agent hook adapter (e.g., a Codex or
    /// Gemini relay script). Same validation policy as [`AtmMcp`](Self::AtmMcp).
    AgentHook,
    /// Origin unknown or not set by the sender.
    ///
    /// Treated as [`ClaudeHook`](Self::ClaudeHook) (strictest, fail-closed default).
    Unknown,
}

/// A request sent from CLI to daemon over the Unix socket.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SocketRequest {
    /// Protocol version. Must be [`PROTOCOL_VERSION`].
    pub version: u32,
    /// Unique identifier echoed back in the response.
    pub request_id: String,
    /// Command to execute (e.g., `"agent-state"`, `"list-agents"`).
    pub command: String,
    /// Command-specific payload.
    pub payload: serde_json::Value,
}

/// A response received from the daemon over the Unix socket.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SocketResponse {
    /// Protocol version.
    pub version: u32,
    /// Echoed `request_id` from the corresponding request.
    pub request_id: String,
    /// `"ok"` on success, `"error"` on failure.
    pub status: String,
    /// Response data on success (present when `status == "ok"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<serde_json::Value>,
    /// Error information on failure (present when `status == "error"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<SocketError>,
}

impl SocketResponse {
    /// Returns `true` if the response indicates success.
    pub fn is_ok(&self) -> bool {
        self.status == "ok"
    }
}

/// Error details returned by the daemon on failure.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SocketError {
    /// Machine-readable error code (e.g., `"AGENT_NOT_FOUND"`).
    pub code: String,
    /// Human-readable error message.
    pub message: String,
}

/// Agent state information returned by the `agent-state` command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentStateInfo {
    /// Current state: `"launching"`, `"busy"`, `"idle"`, or `"killed"`.
    pub state: String,
    /// ISO 8601 timestamp of the last state transition (if available).
    pub last_transition: Option<String>,
}

/// Summary of a single agent returned by the `list-agents` command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentSummary {
    /// Agent identifier.
    pub agent: String,
    /// Current state string.
    pub state: String,
}

/// Canonical daemon-backed member-state snapshot returned by team-scoped
/// `list-agents` queries.
///
/// This struct is the single liveness/status source consumed by CLI diagnostic
/// surfaces (`atm doctor`, `atm status`, `atm members`). It is derived by the
/// daemon from session-registry + tracker evidence and must not be inferred
/// from config `isActive`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CanonicalMemberState {
    /// Agent/member name.
    pub agent: String,
    /// Canonical daemon status (`active`, `idle`, `offline`, `unknown`).
    pub state: String,
    /// Canonical activity hint (`busy`, `idle`, `unknown`).
    #[serde(default)]
    pub activity: String,
    /// Session UUID from the daemon registry when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    /// Process ID from the daemon registry when available.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub process_id: Option<u32>,
    /// Most recent liveness confirmation timestamp from daemon PID checks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_alive_at: Option<String>,
    /// Human-readable derivation reason.
    #[serde(default)]
    pub reason: String,
    /// Source of truth used for state derivation.
    #[serde(default)]
    pub source: String,
    /// Whether this member currently exists in team `config.json`.
    ///
    /// Defaults to `true` for backward compatibility with older daemon payloads
    /// that did not include this field.
    #[serde(default = "default_in_config_true", skip_serializing_if = "is_true")]
    pub in_config: bool,
}

fn default_in_config_true() -> bool {
    true
}

fn is_true(value: &bool) -> bool {
    *value
}

/// Render CLI-facing status taxonomy from daemon canonical member state.
///
/// Output values are constrained to `Active|Idle|Dead|Unknown`.
pub fn canonical_status_label(state: Option<&CanonicalMemberState>) -> &'static str {
    match state.map(|s| s.state.as_str()) {
        Some("active") => "Active",
        Some("idle") => "Idle",
        Some("offline") | Some("dead") => "Dead",
        _ => "Unknown",
    }
}

/// Render CLI-facing activity taxonomy from daemon canonical member state.
///
/// Output values are constrained to `Busy|Idle|Unknown`.
pub fn canonical_activity_label(state: Option<&CanonicalMemberState>) -> &'static str {
    match state.map(|s| s.activity.as_str()) {
        Some("busy") => "Busy",
        Some("idle") => "Idle",
        _ => "Unknown",
    }
}

/// Return best-effort binary liveness from daemon canonical member state.
pub fn canonical_liveness_bool(state: Option<&CanonicalMemberState>) -> Option<bool> {
    match state.map(|s| s.state.as_str()) {
        Some("active") | Some("idle") => Some(true),
        Some("offline") | Some("dead") => Some(false),
        _ => None,
    }
}

/// Configuration for launching a new agent via the daemon.
///
/// Sent as the payload of a `"launch"` socket command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LaunchConfig {
    /// Agent identity name (e.g., `"arch-ctm"`).
    pub agent: String,
    /// Team name (e.g., `"atm-dev"`).
    pub team: String,
    /// Command to run in the tmux pane (e.g., `"codex --yolo"`).
    pub command: String,
    /// Optional initial prompt to send after the agent reaches the `Idle` state.
    pub prompt: Option<String>,
    /// Readiness timeout in seconds. The daemon waits up to this long for the
    /// agent state to transition to `Idle` before sending the initial prompt.
    /// Defaults to 30 if omitted.
    pub timeout_secs: u32,
    /// Extra environment variables to export in the pane before starting the agent.
    ///
    /// `ATM_IDENTITY` and `ATM_TEAM` are always set automatically and do not
    /// need to be included here.
    pub env_vars: std::collections::HashMap<String, String>,
    /// Runtime adapter kind (e.g., `"codex"`, `"gemini"`).
    ///
    /// Older clients may omit this field; daemon should treat missing as
    /// runtime default (`codex`).
    #[serde(default)]
    pub runtime: Option<String>,
    /// Optional runtime-native session ID used for resume-aware launches.
    ///
    /// For Gemini this maps to the Gemini session UUID that should be resumed.
    #[serde(default)]
    pub resume_session_id: Option<String>,
}

/// Result of a successful agent launch returned by the daemon.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LaunchResult {
    /// Agent identity name.
    pub agent: String,
    /// tmux pane ID assigned to the new agent (e.g., `"%42"`).
    pub pane_id: String,
    /// Agent state string immediately after launch (`"launching"`, `"idle"`, etc.).
    pub state: String,
    /// Non-fatal warning, e.g., readiness timeout was reached before the agent
    /// transitioned to `Idle`.
    pub warning: Option<String>,
}

/// Request the daemon to launch a new agent.
///
/// This is a synchronous call: the function blocks until the daemon responds
/// (the daemon itself may respond before full readiness, but the round-trip
/// completes within the socket timeout).
///
/// Returns `Ok(None)` when:
/// - The daemon is not running.
/// - The platform does not support Unix sockets.
/// - A connection-level I/O error occurs before any response is read.
///
/// Returns `Ok(Some(result))` on success.
///
/// Returns `Err` only for unexpected I/O errors *after* a connection is
/// established and a request has been written.
///
/// # Arguments
///
/// * `config` - Launch configuration for the new agent.
pub fn launch_agent(config: &LaunchConfig) -> anyhow::Result<Option<LaunchResult>> {
    let payload = match serde_json::to_value(config) {
        Ok(v) => v,
        Err(e) => anyhow::bail!("Failed to serialize LaunchConfig: {e}"),
    };

    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "launch".to_string(),
        payload,
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        let msg = response
            .error
            .map(|e| format!("{}: {}", e.code, e.message))
            .unwrap_or_else(|| "unknown daemon error".to_string());
        anyhow::bail!("Daemon returned error for launch command: {msg}");
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    match serde_json::from_value::<LaunchResult>(payload) {
        Ok(result) => Ok(Some(result)),
        Err(e) => anyhow::bail!("Failed to parse LaunchResult from daemon response: {e}"),
    }
}

/// Compute the daemon runtime directory.
///
/// The path is `${ATM_HOME}/.atm/daemon`, where `ATM_HOME` is resolved via
/// [`crate::home::get_home_dir`].
pub fn daemon_runtime_dir() -> anyhow::Result<PathBuf> {
    let home = crate::home::get_home_dir()?;
    Ok(home.join(".atm/daemon"))
}

/// Compute the daemon runtime directory for an explicit ATM home.
pub fn daemon_runtime_dir_for(home: &std::path::Path) -> PathBuf {
    home.join(".atm/daemon")
}

/// Compute the well-known socket path for the ATM daemon.
///
/// The path is `${ATM_HOME}/.atm/daemon/atm-daemon.sock`.
///
/// # Errors
///
/// Returns an error only if home directory resolution fails.
pub fn daemon_socket_path() -> anyhow::Result<PathBuf> {
    Ok(daemon_runtime_dir()?.join("atm-daemon.sock"))
}

/// Compute the well-known PID file path for the ATM daemon.
///
/// The path is `${ATM_HOME}/.atm/daemon/atm-daemon.pid`.
///
/// # Errors
///
/// Returns an error only if home directory resolution fails.
pub fn daemon_pid_path() -> anyhow::Result<PathBuf> {
    Ok(daemon_runtime_dir()?.join("atm-daemon.pid"))
}

/// Compute the daemon status snapshot path.
///
/// The path is `${ATM_HOME}/.atm/daemon/status.json`.
pub fn daemon_status_path() -> anyhow::Result<PathBuf> {
    Ok(daemon_runtime_dir()?.join("status.json"))
}

/// Compute the daemon status snapshot path for an explicit ATM home.
pub fn daemon_status_path_for(home: &std::path::Path) -> PathBuf {
    daemon_runtime_dir_for(home).join("status.json")
}

/// Compute the daemon singleton lock path.
///
/// The path is `${ATM_HOME}/.atm/daemon/daemon.lock`.
pub fn daemon_lock_path() -> anyhow::Result<PathBuf> {
    Ok(daemon_runtime_dir()?.join("daemon.lock"))
}

/// Compute the daemon singleton lock metadata path.
///
/// The path is `${ATM_HOME}/.atm/daemon/daemon.lock.meta.json`.
pub fn daemon_lock_metadata_path() -> anyhow::Result<PathBuf> {
    Ok(daemon_runtime_dir()?.join("daemon.lock.meta.json"))
}

/// Compute the daemon lock metadata path for an explicit ATM home.
pub fn daemon_lock_metadata_path_for(home: &std::path::Path) -> PathBuf {
    daemon_runtime_dir_for(home).join("daemon.lock.meta.json")
}

/// Compute the daemon startup serialization lock path.
///
/// The path is `${ATM_HOME}/.atm/daemon/daemon-start.lock`.
pub fn daemon_start_lock_path() -> anyhow::Result<PathBuf> {
    Ok(daemon_runtime_dir()?.join("daemon-start.lock"))
}

/// Compute the durable dedup store path for the ATM daemon.
///
/// The path is `${ATM_HOME}/.atm/daemon/dedup.jsonl`, where `ATM_HOME` is
/// resolved via [`crate::home::get_home_dir`].
///
/// # Errors
///
/// Returns an error only if home directory resolution fails.
pub fn daemon_dedup_path() -> anyhow::Result<PathBuf> {
    Ok(daemon_runtime_dir()?.join("dedup.jsonl"))
}

/// Compute the gh-monitor health snapshot path.
pub fn daemon_gh_monitor_health_path() -> anyhow::Result<PathBuf> {
    Ok(daemon_runtime_dir()?.join("gh-monitor-health.json"))
}

/// Compute the gh-monitor health snapshot path for an explicit ATM home.
pub fn daemon_gh_monitor_health_path_for(home: &std::path::Path) -> PathBuf {
    daemon_runtime_dir_for(home).join("gh-monitor-health.json")
}

/// Write daemon lock metadata atomically for the current process.
///
/// Called by `atm-daemon` after lock acquisition so CLI identity checks can
/// validate PID/home-scope/executable coherence.
pub fn write_daemon_lock_metadata(home: &std::path::Path, version: &str) -> anyhow::Result<()> {
    let metadata_path = daemon_lock_metadata_path_for(home);
    if let Some(parent) = metadata_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let executable_path = std::env::current_exe()
        .ok()
        .and_then(|p| std::fs::canonicalize(p).ok())
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_else(|| "<unknown>".to_string());
    let home_scope = std::fs::canonicalize(home)
        .unwrap_or_else(|_| home.to_path_buf())
        .to_string_lossy()
        .to_string();

    let metadata = DaemonLockMetadata {
        pid: std::process::id(),
        executable_path,
        home_scope,
        version: version.to_string(),
        written_at: chrono::Utc::now().to_rfc3339(),
    };
    let json = serde_json::to_vec_pretty(&metadata)?;
    let tmp = metadata_path.with_extension("json.tmp");
    std::fs::write(&tmp, json)?;
    std::fs::rename(tmp, metadata_path)?;
    Ok(())
}

/// Check whether the daemon appears to be running by reading its PID file and
/// verifying the process is alive.
///
/// Returns `false` on any error (missing file, invalid PID, dead process, etc.).
pub fn daemon_is_running() -> bool {
    #[cfg(unix)]
    {
        let pid_path = match daemon_pid_path() {
            Ok(p) => p,
            Err(_) => return false,
        };
        if let Ok(content) = std::fs::read_to_string(&pid_path) {
            if let Ok(pid) = content.trim().parse::<i32>() {
                return pid_alive(pid);
            }
        }
        false
    }

    #[cfg(not(unix))]
    {
        false
    }
}

/// Ensure the ATM daemon is running, starting it if needed.
///
/// On Unix:
/// - Delegates to the full Unix implementation used by runtime queries,
///   including startup lock coordination, socket probing, and event logging.
///
/// On non-Unix platforms this is a no-op and returns `Ok(())`.
pub fn ensure_daemon_running() -> anyhow::Result<()> {
    #[cfg(unix)]
    {
        ensure_daemon_running_unix()
    }

    #[cfg(not(unix))]
    {
        Ok(())
    }
}

/// Send a single request to the daemon and return the parsed response.
///
/// Returns `Ok(None)` when the daemon is not running or the socket cannot be
/// reached. Returns `Ok(Some(response))` on a successful exchange. Returns
/// `Err` only for I/O errors that occur *after* a connection is established.
///
/// # Platform Behaviour
///
/// On non-Unix platforms this function always returns `Ok(None)`.
pub fn query_daemon(request: &SocketRequest) -> anyhow::Result<Option<SocketResponse>> {
    #[cfg(unix)]
    {
        query_daemon_unix(request, std::time::Duration::from_millis(500))
    }

    #[cfg(not(unix))]
    {
        Ok(None)
    }
}

/// Send a single request to the daemon with a caller-specified socket timeout.
///
/// Use this variant for commands that may legitimately wait on external I/O
/// before returning (for example `gh-monitor` and `gh-monitor-control`).
pub fn query_daemon_with_timeout(
    request: &SocketRequest,
    read_timeout: std::time::Duration,
) -> anyhow::Result<Option<SocketResponse>> {
    #[cfg(unix)]
    {
        query_daemon_unix(request, read_timeout)
    }

    #[cfg(not(unix))]
    {
        Ok(None)
    }
}

/// Query the daemon for the current state of a specific agent.
///
/// Returns `Ok(None)` when the daemon is not reachable or the agent is not tracked.
///
/// # Arguments
///
/// * `agent` - Agent name (e.g., `"arch-ctm"`)
/// * `team`  - Team name (e.g., `"atm-dev"`)
pub fn query_agent_state(agent: &str, team: &str) -> anyhow::Result<Option<AgentStateInfo>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "agent-state".to_string(),
        payload: serde_json::json!({ "agent": agent, "team": team }),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        // Daemon returned an error (e.g., agent not found) — treat as no info
        return Ok(None);
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    match serde_json::from_value::<AgentStateInfo>(payload) {
        Ok(info) => Ok(Some(info)),
        Err(_) => Ok(None),
    }
}

/// Send a subscribe request to the daemon.
///
/// Registers the subscriber's interest in state changes for `agent`. This is a
/// best-effort operation: `Ok(None)` is returned when the daemon is not running.
///
/// # Arguments
///
/// * `subscriber` - ATM identity of the subscribing agent (e.g., `"team-lead"`)
/// * `agent`      - Agent to watch (e.g., `"arch-ctm"`)
/// * `team`       - Team name (informational; used for routing context)
/// * `events`     - State events to subscribe to (e.g., `&["idle"]`);
///   pass an empty slice to subscribe to all events.
pub fn subscribe_to_agent(
    subscriber: &str,
    agent: &str,
    team: &str,
    events: &[String],
) -> anyhow::Result<Option<SocketResponse>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "subscribe".to_string(),
        payload: serde_json::json!({
            "subscriber": subscriber,
            "agent": agent,
            "team": team,
            "events": events,
        }),
    };
    query_daemon(&request)
}

/// Send an unsubscribe request to the daemon.
///
/// Removes the subscription for `(subscriber, agent)`. This is a best-effort
/// operation: `Ok(None)` is returned when the daemon is not running.
///
/// # Arguments
///
/// * `subscriber` - ATM identity of the subscribing agent
/// * `agent`      - Agent to stop watching
/// * `team`       - Team name (informational)
pub fn unsubscribe_from_agent(
    subscriber: &str,
    agent: &str,
    team: &str,
) -> anyhow::Result<Option<SocketResponse>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "unsubscribe".to_string(),
        payload: serde_json::json!({
            "subscriber": subscriber,
            "agent": agent,
            "team": team,
        }),
    };
    query_daemon(&request)
}

/// Query the daemon for the list of all tracked agents.
///
/// Returns `Ok(None)` when the daemon is not reachable.
pub fn query_list_agents() -> anyhow::Result<Option<Vec<AgentSummary>>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "list-agents".to_string(),
        payload: serde_json::Value::Object(Default::default()),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        return Ok(None);
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    match serde_json::from_value::<Vec<AgentSummary>>(payload) {
        Ok(agents) => Ok(Some(agents)),
        Err(_) => Ok(None),
    }
}

/// Query the daemon for the list of tracked agents scoped to a specific team.
///
/// Returns `Ok(None)` when the daemon is not reachable.
pub fn query_list_agents_for_team(team: &str) -> anyhow::Result<Option<Vec<AgentSummary>>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "list-agents".to_string(),
        payload: serde_json::json!({ "team": team }),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        return Ok(None);
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    match serde_json::from_value::<Vec<AgentSummary>>(payload) {
        Ok(agents) => Ok(Some(agents)),
        Err(_) => Ok(None),
    }
}

/// Query the daemon for canonical member-state snapshots scoped to one team.
///
/// Returns:
/// - `Ok(None)` when the daemon is not reachable.
/// - `Err(...)` when daemon response payload is present but does not match the
///   canonical state schema.
pub fn query_team_member_states(team: &str) -> anyhow::Result<Option<Vec<CanonicalMemberState>>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "list-agents".to_string(),
        payload: serde_json::json!({ "team": team }),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        return Ok(None);
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    decode_canonical_member_states_payload(payload).map(Some)
}

fn decode_canonical_member_states_payload(
    payload: serde_json::Value,
) -> anyhow::Result<Vec<CanonicalMemberState>> {
    serde_json::from_value::<Vec<CanonicalMemberState>>(payload).map_err(|err| {
        anyhow::anyhow!(
            "invalid canonical member-state payload from daemon list-agents(team): {err}"
        )
    })
}

/// Pane and log file information returned by the `agent-pane` command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentPaneInfo {
    /// Backend pane identifier (e.g., `"%42"`).
    pub pane_id: String,
    /// Absolute path to the agent's log file.
    pub log_path: String,
}

/// Query the daemon for the pane ID and log file path of a specific agent.
///
/// Returns `Ok(None)` when the daemon is not reachable or the agent is not tracked.
///
/// # Arguments
///
/// * `agent` - Agent name (e.g., `"arch-ctm"`)
pub fn query_agent_pane(agent: &str) -> anyhow::Result<Option<AgentPaneInfo>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "agent-pane".to_string(),
        payload: serde_json::json!({ "agent": agent }),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        // Daemon returned an error (e.g., agent not found) — treat as no info
        return Ok(None);
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    match serde_json::from_value::<AgentPaneInfo>(payload) {
        Ok(info) => Ok(Some(info)),
        Err(_) => Ok(None),
    }
}

/// Session information returned by the `session-query` socket command.
///
/// Describes the Claude Code session and OS process currently registered for an
/// agent in the [`SessionRegistry`](crate) and whether the process is alive.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionQueryResult {
    /// Claude Code session UUID.
    pub session_id: String,
    /// OS process ID of the agent process.
    pub process_id: u32,
    /// Whether the OS process is currently running.
    pub alive: bool,
    /// Most recent successful daemon heartbeat for this session.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_seen_at: Option<String>,
    /// Runtime kind (`codex`, `gemini`, etc.) when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime: Option<String>,
    /// Runtime-native session/thread identifier when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_session_id: Option<String>,
    /// Backend pane identifier when applicable.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pane_id: Option<String>,
    /// Runtime home/state directory when configured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub runtime_home: Option<String>,
}

/// Result of attempting to register a daemon session hint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RegisterHintOutcome {
    /// Hint was accepted by the daemon.
    Registered,
    /// Daemon is unreachable; caller should continue without failing.
    DaemonUnavailable,
    /// Connected daemon does not support the register-hint command.
    UnsupportedDaemon,
}

/// GH monitor target kind.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GhMonitorTargetKind {
    Pr,
    Workflow,
    Run,
}

/// Request payload for daemon-routed `gh-monitor` command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GhMonitorRequest {
    pub team: String,
    pub target_kind: GhMonitorTargetKind,
    pub target: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_timeout_secs: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_cwd: Option<String>,
}

/// Request payload for daemon-routed `gh-status` command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GhStatusRequest {
    pub team: String,
    pub target_kind: GhMonitorTargetKind,
    pub target: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_cwd: Option<String>,
}

/// Lifecycle action for the GitHub monitor plugin.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum GhMonitorLifecycleAction {
    Start,
    Stop,
    Restart,
}

/// Request payload for daemon-routed `gh-monitor-control` command.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GhMonitorControlRequest {
    pub team: String,
    pub action: GhMonitorLifecycleAction,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drain_timeout_secs: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_cwd: Option<String>,
}

/// Daemon response payload for `gh-monitor-control` / `gh-monitor-health`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GhMonitorHealth {
    pub team: String,
    #[serde(default)]
    pub configured: bool,
    #[serde(default)]
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_path: Option<String>,
    pub lifecycle_state: String,
    pub availability_state: String,
    pub in_flight: u64,
    pub updated_at: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// Daemon response payload for `gh-monitor`/`gh-status`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GhMonitorStatus {
    pub team: String,
    #[serde(default)]
    pub configured: bool,
    #[serde(default)]
    pub enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_path: Option<String>,
    pub target_kind: GhMonitorTargetKind,
    pub target: String,
    pub state: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run_id: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reference: Option<String>,
    pub updated_at: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

/// Query the daemon for the session record of a named agent.
///
/// Returns:
/// - `Ok(Some(result))` when the agent is registered in the session registry.
/// - `Ok(None)` when the daemon is not running, the agent is not registered,
///   or the platform does not support Unix sockets.
/// - `Err` only for unexpected I/O errors *after* a connection is established.
///
/// # Arguments
///
/// * `name` - Agent name to look up (e.g., `"team-lead"`)
pub fn query_session(name: &str) -> anyhow::Result<Option<SessionQueryResult>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "session-query".to_string(),
        payload: serde_json::json!({ "name": name }),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        // Daemon returned error (agent not found) — treat as no session info
        return Ok(None);
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    match serde_json::from_value::<SessionQueryResult>(payload) {
        Ok(result) => Ok(Some(result)),
        Err(_) => Ok(None),
    }
}

/// Query the daemon for the session record of a named agent scoped to a team.
///
/// Returns:
/// - `Ok(Some(result))` when the agent is registered and matches the team's
///   current lead-session context.
/// - `Ok(None)` when the daemon is not running, the agent is not registered
///   for that team context, or the platform does not support Unix sockets.
/// - `Err` only for unexpected I/O errors *after* a connection is established.
///
/// # Arguments
///
/// * `team` - Team name (e.g., `"atm-dev"`)
/// * `name` - Agent name to look up (e.g., `"team-lead"`)
pub fn query_session_for_team(
    team: &str,
    name: &str,
) -> anyhow::Result<Option<SessionQueryResult>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "session-query-team".to_string(),
        payload: serde_json::json!({ "team": team, "name": name }),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        return Ok(None);
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    match serde_json::from_value::<SessionQueryResult>(payload) {
        Ok(result) => Ok(Some(result)),
        Err(_) => Ok(None),
    }
}

/// Query the daemon for the stream turn state of a named agent.
///
/// Returns:
/// - `Ok(Some(state))` when the daemon has stream state recorded for the agent.
/// - `Ok(None)` when the daemon is not running, the agent has no stream state,
///   or the platform does not support Unix sockets.
///
/// # Arguments
///
/// * `agent` - Agent name to look up (e.g., `"arch-ctm"`)
pub fn query_agent_stream_state(
    agent: &str,
) -> anyhow::Result<Option<crate::daemon_stream::AgentStreamState>> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "agent-stream-state".to_string(),
        payload: serde_json::json!({ "agent": agent }),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    if !response.is_ok() {
        return Ok(None);
    }

    let payload = match response.payload {
        Some(p) => p,
        None => return Ok(None),
    };

    match serde_json::from_value::<crate::daemon_stream::AgentStreamState>(payload) {
        Ok(state) => Ok(Some(state)),
        Err(_) => Ok(None),
    }
}

/// Handle for an active daemon stream subscription.
///
/// Dropping this value requests the background reader thread to stop.
pub struct StreamSubscription {
    /// Receiver of daemon stream events.
    pub rx: std::sync::mpsc::Receiver<crate::daemon_stream::DaemonStreamEvent>,
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
}

impl Drop for StreamSubscription {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
    }
}

/// Subscribe to daemon stream events over a long-lived socket connection.
///
/// Returns:
/// - `Ok(Some(rx))` when subscription succeeds.
/// - `Ok(None)` when daemon/socket is unavailable on this platform/session.
pub fn subscribe_stream_events() -> anyhow::Result<Option<StreamSubscription>> {
    #[cfg(unix)]
    {
        subscribe_stream_events_unix()
    }

    #[cfg(not(unix))]
    {
        Ok(None)
    }
}

/// Send a control request to the daemon and wait for an acknowledgement.
///
/// Sends `command: "control"` with the given [`ControlRequest`] as payload.
/// Returns the parsed [`ControlAck`] on success, or an error on socket/parse
/// failure.  A short read timeout is applied by the underlying
/// [`query_daemon`] call.
///
/// # Errors
///
/// Returns `Err` when:
/// - The daemon is not running or the socket cannot be reached (no graceful
///   `None` here — the caller needs to distinguish errors from timeouts).
/// - The daemon returns an error status.
/// - The response payload cannot be parsed as [`ControlAck`].
pub fn send_control(
    request: &crate::control::ControlRequest,
) -> anyhow::Result<crate::control::ControlAck> {
    let payload = serde_json::to_value(request)
        .map_err(|e| anyhow::anyhow!("Failed to serialize ControlRequest: {e}"))?;

    let socket_request = SocketRequest {
        version: PROTOCOL_VERSION,
        // Use an independent socket-level correlation ID; the control payload
        // carries its own stable idempotency key (`request.request_id`) that
        // must not change on retries.
        request_id: format!(
            "sock-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ),
        command: "control".to_string(),
        payload,
    };

    let response = match query_daemon(&socket_request)? {
        Some(r) => r,
        None => anyhow::bail!("Daemon not reachable (socket not found or connection refused)"),
    };

    if !response.is_ok() {
        let msg = response
            .error
            .map(|e| format!("{}: {}", e.code, e.message))
            .unwrap_or_else(|| "unknown daemon error".to_string());
        anyhow::bail!("Daemon returned error for control command: {msg}");
    }

    let payload = response
        .payload
        .ok_or_else(|| anyhow::anyhow!("Daemon returned ok status but no payload"))?;

    serde_json::from_value::<crate::control::ControlAck>(payload)
        .map_err(|e| anyhow::anyhow!("Failed to parse ControlAck from daemon response: {e}"))
}

/// Send a best-effort session registration hint to the daemon.
///
/// This command is used by external runtimes (Codex/Gemini) that cannot emit
/// Claude-style lifecycle hooks. It updates the daemon session registry using
/// canonical daemon paths instead of writing session identity into config.json.
///
/// Backward compatibility contract:
/// - daemon unreachable -> [`RegisterHintOutcome::DaemonUnavailable`] (silent skip)
/// - daemon unknown-command -> [`RegisterHintOutcome::UnsupportedDaemon`] so callers can
///   fail with explicit upgrade guidance.
#[allow(clippy::too_many_arguments)]
pub fn register_hint(
    team: &str,
    agent: &str,
    session_id: &str,
    process_id: u32,
    runtime: Option<&str>,
    runtime_session_id: Option<&str>,
    pane_id: Option<&str>,
    runtime_home: Option<&str>,
) -> anyhow::Result<RegisterHintOutcome> {
    let request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "register-hint".to_string(),
        payload: serde_json::json!({
            "team": team,
            "agent": agent,
            "session_id": session_id,
            "process_id": process_id,
            "runtime": runtime,
            "runtime_session_id": runtime_session_id,
            "pane_id": pane_id,
            "runtime_home": runtime_home,
            "identity": std::env::var("ATM_IDENTITY")
                .ok()
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty()),
        }),
    };

    let response = match query_daemon(&request)? {
        Some(r) => r,
        None => return Ok(RegisterHintOutcome::DaemonUnavailable),
    };

    decode_register_hint_response(response)
}

/// Send a daemon-routed GitHub monitor request (`command: "gh-monitor"`).
///
/// Returns:
/// - `Ok(Some(status))` when the daemon accepted the request and returned
///   monitor status.
/// - `Ok(None)` when daemon/socket is unavailable.
/// - `Err` when daemon returns an explicit command error.
pub fn gh_monitor(request: &GhMonitorRequest) -> anyhow::Result<Option<GhMonitorStatus>> {
    let socket_request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "gh-monitor".to_string(),
        payload: serde_json::to_value(request)?,
    };

    // `gh-monitor` may wait for CI run discovery up to start_timeout_secs.
    let start_timeout_secs = request.start_timeout_secs.unwrap_or(120);
    let read_timeout = std::time::Duration::from_secs((start_timeout_secs + 30).min(600));
    let response = match query_daemon_with_timeout(&socket_request, read_timeout)? {
        Some(r) => r,
        None => return Ok(None),
    };

    decode_gh_monitor_response(response).map(Some)
}

/// Query daemon-routed GitHub monitor status (`command: "gh-status"`).
///
/// Returns:
/// - `Ok(Some(status))` when daemon has monitor state for the target.
/// - `Ok(None)` when daemon/socket is unavailable.
/// - `Err` when daemon returns an explicit command error.
pub fn gh_status(request: &GhStatusRequest) -> anyhow::Result<Option<GhMonitorStatus>> {
    let socket_request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "gh-status".to_string(),
        payload: serde_json::to_value(request)?,
    };

    let response = match query_daemon(&socket_request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    decode_gh_monitor_response(response).map(Some)
}

/// Send a daemon-routed GitHub monitor lifecycle request
/// (`command: "gh-monitor-control"`).
pub fn gh_monitor_control(
    request: &GhMonitorControlRequest,
) -> anyhow::Result<Option<GhMonitorHealth>> {
    let socket_request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "gh-monitor-control".to_string(),
        payload: serde_json::to_value(request)?,
    };

    // Stop/restart can drain in-flight monitors for drain_timeout_secs.
    let drain_timeout_secs = request.drain_timeout_secs.unwrap_or(30);
    let read_timeout = std::time::Duration::from_secs((drain_timeout_secs + 30).min(600));
    let response = match query_daemon_with_timeout(&socket_request, read_timeout)? {
        Some(r) => r,
        None => return Ok(None),
    };

    decode_gh_monitor_health_response(response).map(Some)
}

/// Query daemon-routed GitHub monitor plugin health
/// (`command: "gh-monitor-health"`).
pub fn gh_monitor_health(team: &str) -> anyhow::Result<Option<GhMonitorHealth>> {
    gh_monitor_health_with_context(team, None)
}

/// Query daemon-routed GitHub monitor plugin health with explicit config cwd.
pub fn gh_monitor_health_with_context(
    team: &str,
    config_cwd: Option<String>,
) -> anyhow::Result<Option<GhMonitorHealth>> {
    let socket_request = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "gh-monitor-health".to_string(),
        payload: serde_json::json!({
            "team": team,
            "config_cwd": config_cwd,
        }),
    };

    let response = match query_daemon(&socket_request)? {
        Some(r) => r,
        None => return Ok(None),
    };

    decode_gh_monitor_health_response(response).map(Some)
}

fn decode_gh_monitor_response(response: SocketResponse) -> anyhow::Result<GhMonitorStatus> {
    if !response.is_ok() {
        let Some(err) = response.error else {
            anyhow::bail!("Daemon returned gh-monitor error status without error payload");
        };
        anyhow::bail!(
            "Daemon returned error for {} command: {}: {}",
            response.request_id,
            err.code,
            err.message
        );
    }

    let payload = response
        .payload
        .ok_or_else(|| anyhow::anyhow!("Daemon returned ok status but no payload"))?;

    serde_json::from_value::<GhMonitorStatus>(payload)
        .map_err(|e| anyhow::anyhow!("Failed to parse GhMonitorStatus from daemon response: {e}"))
}

fn decode_gh_monitor_health_response(response: SocketResponse) -> anyhow::Result<GhMonitorHealth> {
    if !response.is_ok() {
        let Some(err) = response.error else {
            anyhow::bail!("Daemon returned gh-monitor health error status without error payload");
        };
        anyhow::bail!(
            "Daemon returned error for {} command: {}: {}",
            response.request_id,
            err.code,
            err.message
        );
    }

    let payload = response
        .payload
        .ok_or_else(|| anyhow::anyhow!("Daemon returned ok status but no payload"))?;

    serde_json::from_value::<GhMonitorHealth>(payload)
        .map_err(|e| anyhow::anyhow!("Failed to parse GhMonitorHealth from daemon response: {e}"))
}

fn decode_register_hint_response(response: SocketResponse) -> anyhow::Result<RegisterHintOutcome> {
    if response.is_ok() {
        return Ok(RegisterHintOutcome::Registered);
    }

    let Some(err) = response.error else {
        anyhow::bail!("Daemon returned register-hint error status without error payload");
    };

    if err.code == "UNKNOWN_COMMAND" {
        return Ok(RegisterHintOutcome::UnsupportedDaemon);
    }

    anyhow::bail!(
        "Daemon returned error for register-hint command: {}: {}",
        err.code,
        err.message
    )
}

/// Generate a compact request identifier (UUID v4 as a short string).
fn new_request_id() -> String {
    // Use a simple monotonic counter for environments without UUID support.
    // In practice the daemon_client is always used in the atm crate which
    // has uuid available, but atm-core does not depend on uuid.
    use std::time::{SystemTime, UNIX_EPOCH};
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .subsec_nanos();
    let id = std::process::id();
    format!("req-{id}-{nanos}")
}

// ── Unix implementation ──────────────────────────────────────────────────────

#[cfg(unix)]
fn query_daemon_unix(
    request: &SocketRequest,
    read_timeout: std::time::Duration,
) -> anyhow::Result<Option<SocketResponse>> {
    use std::io::{BufRead, BufReader, Write};
    use std::os::unix::net::UnixStream;
    use std::time::{Duration, Instant};

    let socket_path = daemon_socket_path()?;

    // First attempt connection directly.
    let stream = match UnixStream::connect(&socket_path) {
        Ok(s) => s,
        Err(_) => {
            // Optional daemon auto-start path, enabled by ATM_DAEMON_AUTOSTART.
            if daemon_autostart_enabled() {
                ensure_daemon_running_unix()?;
                let deadline = Instant::now() + Duration::from_secs(5);
                loop {
                    match UnixStream::connect(&socket_path) {
                        Ok(s) => break s,
                        Err(e) if Instant::now() < deadline => {
                            let _ = e;
                            std::thread::sleep(Duration::from_millis(100));
                        }
                        Err(e) => {
                            anyhow::bail!(
                                "daemon auto-start attempted but socket remained unavailable at {}: {e}",
                                socket_path.display()
                            )
                        }
                    }
                }
            } else {
                // Autostart is disabled; the daemon is managed externally.
                // If the socket path already exists the daemon may be mid-startup
                // (socket bound but not yet accepting). Retry briefly before giving up
                // so we don't return Ok(None) during that narrow window.
                if socket_path.exists() {
                    let mut connected = None;
                    for _ in 0..3 {
                        match UnixStream::connect(&socket_path) {
                            Ok(s) => {
                                connected = Some(s);
                                break;
                            }
                            Err(_) => std::thread::sleep(Duration::from_millis(100)),
                        }
                    }
                    match connected {
                        Some(s) => s,
                        None => return Ok(None),
                    }
                } else {
                    return Ok(None);
                }
            }
        }
    };

    // Keep writes short; allow caller-specific read timeout for long-running
    // daemon operations such as gh monitor startup/drain paths.
    stream.set_read_timeout(Some(read_timeout)).ok();
    stream
        .set_write_timeout(Some(Duration::from_millis(500)))
        .ok();

    let request_line = serde_json::to_string(request)?;

    // Write request line (newline-delimited)
    {
        let mut writer = std::io::BufWriter::new(&stream);
        writer.write_all(request_line.as_bytes())?;
        writer.write_all(b"\n")?;
        writer.flush()?;
    }

    // Read response line
    let mut reader = BufReader::new(&stream);
    let mut response_line = String::new();
    match reader.read_line(&mut response_line) {
        Ok(0) | Err(_) => return Ok(None), // daemon closed connection or timed out
        Ok(_) => {}
    }

    let response: SocketResponse = match serde_json::from_str(response_line.trim()) {
        Ok(r) => r,
        Err(_) => return Ok(None),
    };

    Ok(Some(response))
}

#[cfg(unix)]
fn daemon_autostart_enabled() -> bool {
    let Ok(raw) = std::env::var("ATM_DAEMON_AUTOSTART") else {
        // Opt-out model: autostart is enabled by default when unset.
        return true;
    };
    !matches!(
        raw.trim().to_ascii_lowercase().as_str(),
        "0" | "false" | "no"
    )
}

#[cfg(unix)]
fn resolve_daemon_binary() -> std::ffi::OsString {
    if let Some(override_bin) = std::env::var_os("ATM_DAEMON_BIN")
        && !override_bin.is_empty()
    {
        return override_bin;
    }

    let name = std::ffi::OsString::from("atm-daemon");

    if let Ok(current_exe) = std::env::current_exe()
        && let Some(dir) = current_exe.parent()
    {
        let sibling = dir.join(std::path::Path::new(&name));
        if sibling.exists() {
            return sibling.into_os_string();
        }
    }

    name
}

#[cfg(unix)]
fn ensure_daemon_running_unix() -> anyhow::Result<()> {
    use crate::event_log::{EventFields, emit_event_best_effort};
    use crate::io::InboxError;
    use std::io::ErrorKind;
    use std::io::Read;
    use std::process::{Command, Stdio};
    use std::time::{Duration, Instant};

    // When autostart is disabled, the daemon lifecycle is managed externally.
    // Skip identity validation and restart logic — trust the external daemon as-is.
    if !daemon_autostart_enabled() {
        return Ok(());
    }

    let home = crate::home::get_home_dir()?;
    let daemon_running = daemon_is_running();
    let socket_connectable = daemon_socket_connectable(&home);
    if daemon_running || socket_connectable {
        if let Some(reason) = detect_daemon_identity_mismatch(&home, socket_connectable) {
            restart_mismatched_daemon(&home, &reason)?;
        } else {
            return Ok(());
        }
    }

    cleanup_stale_daemon_runtime_files(&home);

    let startup_lock_path = daemon_start_lock_path()?;
    if let Some(parent) = startup_lock_path.parent() {
        std::fs::create_dir_all(parent)?;
    }

    // Serialize daemon startup across concurrent CLI processes.
    let _startup_lock = match crate::io::lock::acquire_lock(&startup_lock_path, 3) {
        Ok(lock) => Some(lock),
        Err(InboxError::LockTimeout { .. }) => {
            // Another process likely holds the startup lock and is spawning the daemon.
            // Wait briefly for that startup attempt to converge.
            for _ in 0..10 {
                if daemon_is_running() || daemon_socket_connectable(&home) {
                    return Ok(());
                }
                std::thread::sleep(Duration::from_millis(100));
            }
            // Startup did not converge yet. Re-attempt lock acquisition so any
            // fallback spawn still occurs under lock (single-daemon invariant).
            match crate::io::lock::acquire_lock(&startup_lock_path, 10) {
                Ok(lock) => Some(lock),
                Err(e) => anyhow::bail!(
                    "timed out waiting for daemon startup lock holder to bring daemon online: {} ({e})",
                    startup_lock_path.display()
                ),
            }
        }
        Err(e) => anyhow::bail!(
            "failed to acquire daemon startup lock {}: {e}",
            startup_lock_path.display()
        ),
    };

    let daemon_running = daemon_is_running();
    let socket_connectable = daemon_socket_connectable(&home);
    if daemon_running || socket_connectable {
        if let Some(reason) = detect_daemon_identity_mismatch(&home, socket_connectable) {
            restart_mismatched_daemon(&home, &reason)?;
        } else {
            return Ok(());
        }
    }

    let daemon_bin = resolve_daemon_binary();
    emit_event_best_effort(EventFields {
        level: "info",
        source: "atm",
        action: "daemon_autostart_attempt",
        result: Some("attempt".to_string()),
        target: Some(std::path::PathBuf::from(&daemon_bin).display().to_string()),
        ..Default::default()
    });
    let mut child = match Command::new(&daemon_bin)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(child) => child,
        Err(e) => {
            let error = if e.kind() == ErrorKind::NotFound {
                format!(
                    "failed to auto-start daemon: binary '{}' not found in PATH (or ATM_DAEMON_BIN override)",
                    std::path::PathBuf::from(&daemon_bin).display()
                )
            } else {
                format!(
                    "failed to auto-start daemon via '{}': {e}",
                    std::path::PathBuf::from(&daemon_bin).display()
                )
            };
            emit_event_best_effort(EventFields {
                level: "error",
                source: "atm",
                action: "daemon_autostart_failure",
                result: Some("spawn_error".to_string()),
                target: Some(std::path::PathBuf::from(&daemon_bin).display().to_string()),
                error: Some(error.clone()),
                ..Default::default()
            });
            anyhow::bail!("{error}");
        }
    };

    let deadline = Instant::now() + Duration::from_secs(5);
    while Instant::now() < deadline {
        if daemon_is_running() || daemon_socket_connectable(&home) {
            emit_event_best_effort(EventFields {
                level: "info",
                source: "atm",
                action: "daemon_autostart_success",
                result: Some("ok".to_string()),
                target: Some(std::path::PathBuf::from(&daemon_bin).display().to_string()),
                ..Default::default()
            });
            return Ok(());
        }
        if let Some(status) = child.try_wait()? {
            let stderr_tail = child.stderr.take().and_then(|mut stderr| {
                let mut buf = Vec::new();
                stderr.read_to_end(&mut buf).ok()?;
                if buf.is_empty() {
                    return None;
                }
                let trimmed = if buf.len() > 4096 {
                    &buf[buf.len() - 4096..]
                } else {
                    &buf
                };
                let text = String::from_utf8_lossy(trimmed).trim().to_string();
                if text.is_empty() { None } else { Some(text) }
            });
            let error = match stderr_tail {
                Some(tail) => {
                    format!(
                        "daemon process exited during startup with status {status}; stderr_tail={tail}"
                    )
                }
                None => format!("daemon process exited during startup with status {status}"),
            };
            emit_event_best_effort(EventFields {
                level: "error",
                source: "atm",
                action: "daemon_autostart_failure",
                result: Some("process_exit".to_string()),
                target: Some(std::path::PathBuf::from(&daemon_bin).display().to_string()),
                error: Some(error.clone()),
                ..Default::default()
            });
            anyhow::bail!("{error}");
        }
        std::thread::sleep(Duration::from_millis(100));
    }

    let socket_path = daemon_socket_path()?;
    let pid_path = daemon_pid_path()?;
    let timeout_error = format!(
        "daemon startup timed out after 5s; pid_file_exists={}, socket_exists={}, pid_path={}, socket_path={}",
        pid_path.exists(),
        socket_path.exists(),
        pid_path.display(),
        socket_path.display()
    );
    emit_event_best_effort(EventFields {
        level: "warn",
        source: "atm",
        action: "daemon_autostart_timeout",
        result: Some("timeout".to_string()),
        target: Some(std::path::PathBuf::from(&daemon_bin).display().to_string()),
        error: Some(timeout_error.clone()),
        ..Default::default()
    });
    emit_event_best_effort(EventFields {
        level: "error",
        source: "atm",
        action: "daemon_autostart_failure",
        result: Some("timeout".to_string()),
        target: Some(std::path::PathBuf::from(&daemon_bin).display().to_string()),
        error: Some(timeout_error.clone()),
        ..Default::default()
    });
    anyhow::bail!("{timeout_error}")
}

#[cfg(unix)]
fn daemon_socket_connectable(home: &std::path::Path) -> bool {
    use std::os::unix::net::UnixStream;
    let socket_path = home.join(".atm/daemon/atm-daemon.sock");
    UnixStream::connect(socket_path).is_ok()
}

#[cfg(unix)]
fn cleanup_stale_daemon_runtime_files(home: &std::path::Path) {
    let socket_path = home.join(".atm/daemon/atm-daemon.sock");
    let pid_path = home.join(".atm/daemon/atm-daemon.pid");

    let pid_state = read_daemon_pid_state(&pid_path);
    if matches!(
        pid_state,
        PidState::Dead | PidState::Missing | PidState::Malformed
    ) {
        let _ = std::fs::remove_file(&pid_path);
    }

    // Remove stale socket only when daemon ownership is known-dead.
    let ownership_known_dead = matches!(
        pid_state,
        PidState::Dead | PidState::Missing | PidState::Malformed
    );
    if socket_path.exists() && ownership_known_dead && !daemon_socket_connectable(home) {
        let _ = std::fs::remove_file(&socket_path);
    }
}

#[cfg(unix)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PidState {
    Missing,
    Malformed,
    Unreadable,
    Dead,
    Alive,
}

#[cfg(unix)]
fn read_daemon_pid_state(pid_path: &std::path::Path) -> PidState {
    if !pid_path.exists() {
        return PidState::Missing;
    }
    let content = match std::fs::read_to_string(pid_path) {
        Ok(s) => s,
        Err(_) => return PidState::Unreadable,
    };
    let pid = match content.trim().parse::<i32>() {
        Ok(pid) => pid,
        Err(_) => return PidState::Malformed,
    };
    if pid_alive(pid) {
        PidState::Alive
    } else {
        PidState::Dead
    }
}

#[cfg(unix)]
#[derive(Debug, Clone, Default)]
struct DaemonIdentitySnapshot {
    pid_from_file: Option<u32>,
    pid_from_status: Option<u32>,
    version_from_status: Option<String>,
    metadata: Option<DaemonLockMetadata>,
    socket_connectable: bool,
}

#[cfg(unix)]
fn evaluate_daemon_identity_mismatch(
    snapshot: &DaemonIdentitySnapshot,
    expected_home: &str,
    expected_bin: &std::ffi::OsStr,
    expected_version: &str,
    pid_alive_fn: impl Fn(i32) -> bool,
    pid_command_line_fn: impl Fn(i32) -> Option<String>,
) -> Option<String> {
    if snapshot.metadata.is_none() && !snapshot.socket_connectable {
        return None;
    }

    if snapshot.metadata.is_none() {
        return Some(
            "daemon identity mismatch: lock metadata missing (soft mismatch, restart required)"
                .to_string(),
        );
    }

    let pid = snapshot
        .metadata
        .as_ref()
        .map(|m| m.pid)
        .or(snapshot.pid_from_file)
        .or(snapshot.pid_from_status)?;

    if !pid_alive_fn(pid as i32) {
        return Some(format!("daemon identity mismatch: pid {pid} is not alive"));
    }

    if let Some(meta) = &snapshot.metadata {
        if let Some(file_pid) = snapshot.pid_from_file
            && file_pid != meta.pid
        {
            return Some(format!(
                "daemon identity mismatch: pid file ({file_pid}) != lock metadata ({})",
                meta.pid
            ));
        }

        if !meta.home_scope.is_empty() && meta.home_scope != expected_home {
            return Some(format!(
                "daemon identity mismatch: home scope '{}' != expected '{}'",
                meta.home_scope, expected_home
            ));
        }

        if let Some(cmdline) = pid_command_line_fn(pid as i32)
            && let Some(matches) = pid_command_matches_expected_binary(&cmdline, expected_bin)
            && !matches
        {
            return Some(format!(
                "daemon identity mismatch: running command '{}' != expected daemon binary '{}'",
                cmdline,
                std::path::PathBuf::from(expected_bin).display()
            ));
        }
    }

    if let Some(ver) = snapshot.version_from_status.as_deref()
        && ver != expected_version
    {
        return Some(format!(
            "daemon version mismatch: running={ver} expected={expected_version}"
        ));
    }

    None
}

#[cfg(unix)]
fn detect_daemon_identity_mismatch(
    home: &std::path::Path,
    socket_connectable: bool,
) -> Option<String> {
    let pid_path = home.join(".atm/daemon/atm-daemon.pid");
    let status_path = daemon_status_path_for(home);
    let metadata_path = daemon_lock_metadata_path_for(home);

    let pid_from_file = std::fs::read_to_string(&pid_path)
        .ok()
        .and_then(|s| s.trim().parse::<u32>().ok());
    let status_json = std::fs::read_to_string(&status_path)
        .ok()
        .and_then(|content| serde_json::from_str::<serde_json::Value>(&content).ok());
    let pid_from_status = status_json
        .as_ref()
        .and_then(|json| json.get("pid").and_then(serde_json::Value::as_u64))
        .map(|pid| pid as u32);
    let version_from_status = status_json
        .as_ref()
        .and_then(|json| json.get("version").and_then(serde_json::Value::as_str))
        .map(std::string::ToString::to_string);
    let mut metadata = std::fs::read_to_string(&metadata_path)
        .ok()
        .and_then(|s| serde_json::from_str::<DaemonLockMetadata>(&s).ok());

    if metadata.is_none()
        && let Some(candidate_pid) = pid_from_file.or(pid_from_status)
        && pid_alive(candidate_pid as i32)
    {
        std::thread::sleep(std::time::Duration::from_millis(150));
        metadata = std::fs::read_to_string(&metadata_path)
            .ok()
            .and_then(|s| serde_json::from_str::<DaemonLockMetadata>(&s).ok());
    }

    let expected_home = std::fs::canonicalize(home)
        .unwrap_or_else(|_| home.to_path_buf())
        .to_string_lossy()
        .to_string();
    let expected_bin = resolve_daemon_binary();
    let snapshot = DaemonIdentitySnapshot {
        pid_from_file,
        pid_from_status,
        version_from_status,
        metadata,
        socket_connectable,
    };

    evaluate_daemon_identity_mismatch(
        &snapshot,
        &expected_home,
        expected_bin.as_os_str(),
        env!("CARGO_PKG_VERSION"),
        pid_alive,
        pid_command_line,
    )
}

#[cfg(unix)]
fn pid_command_line(pid: i32) -> Option<String> {
    let output = std::process::Command::new("ps")
        .arg("-p")
        .arg(pid.to_string())
        .arg("-o")
        .arg("command=")
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if text.is_empty() { None } else { Some(text) }
}

#[cfg(unix)]
fn pid_command_matches_expected_binary(
    cmdline: &str,
    expected_bin: &std::ffi::OsStr,
) -> Option<bool> {
    let actual = cmdline.split_whitespace().next()?;
    let expected = std::path::PathBuf::from(expected_bin);
    let actual_path = std::path::PathBuf::from(actual);

    if expected.as_os_str().is_empty() {
        return None;
    }

    if expected.components().count() > 1 {
        let expected_canon = std::fs::canonicalize(&expected).unwrap_or(expected.clone());
        let actual_canon = std::fs::canonicalize(&actual_path).unwrap_or(actual_path.clone());
        Some(expected_canon == actual_canon)
    } else {
        let expected_name = expected.file_name()?;
        Some(actual_path.file_name() == Some(expected_name))
    }
}

#[cfg(unix)]
fn restart_mismatched_daemon(home: &std::path::Path, reason: &str) -> anyhow::Result<()> {
    use crate::event_log::{EventFields, emit_event_best_effort};
    use std::time::Duration;

    let pid_path = home.join(".atm/daemon/atm-daemon.pid");
    let pid = std::fs::read_to_string(&pid_path)
        .ok()
        .and_then(|s| s.trim().parse::<i32>().ok());

    emit_event_best_effort(EventFields {
        level: "warn",
        source: "atm",
        action: "daemon_identity_restart",
        result: Some("restart_attempt".to_string()),
        error: Some(reason.to_string()),
        ..Default::default()
    });

    if let Some(pid) = pid
        && pid_alive(pid)
    {
        send_signal(pid, 15);
        for _ in 0..20 {
            if !pid_alive(pid) {
                break;
            }
            std::thread::sleep(Duration::from_millis(100));
        }
        if pid_alive(pid) {
            send_signal(pid, 9);
            for _ in 0..20 {
                if !pid_alive(pid) {
                    break;
                }
                std::thread::sleep(Duration::from_millis(100));
            }
        }
        if pid_alive(pid) {
            emit_event_best_effort(EventFields {
                level: "warn",
                source: "atm",
                action: "daemon_identity_restart",
                result: Some("kill_incomplete".to_string()),
                error: Some(format!(
                    "stale daemon pid {pid} still alive after SIGTERM/SIGKILL; proceeding with runtime file replacement"
                )),
                ..Default::default()
            });
        }
    }

    let lock_path = home.join(".atm/daemon/daemon.lock");
    if let Some(parent) = lock_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    let _lock_guard = crate::io::lock::acquire_lock(&lock_path, 5).map_err(|e| {
        anyhow::anyhow!(
            "failed to acquire daemon lock at {} before runtime cleanup: {e}",
            lock_path.display()
        )
    })?;

    // Replace runtime files aggressively for identity-mismatch recovery. This is
    // scope-local and avoids broad process sweeps while allowing a fresh daemon
    // to bind canonical paths.
    let daemon_dir = home.join(".atm/daemon");
    let _ = std::fs::remove_file(daemon_dir.join("atm-daemon.sock"));
    let _ = std::fs::remove_file(daemon_dir.join("atm-daemon.pid"));
    let _ = std::fs::remove_file(daemon_dir.join("status.json"));
    cleanup_stale_daemon_runtime_files(home);
    Ok(())
}

#[cfg(unix)]
fn send_signal(pid: i32, sig: i32) {
    // SAFETY: kill is invoked with a specific PID and signal; errors are ignored
    // by design because this is a best-effort stale-daemon cleanup path.
    unsafe extern "C" {
        fn kill(pid: i32, sig: i32) -> i32;
    }
    // SAFETY: FFI call to libc kill; inputs are plain integers.
    let _ = unsafe { kill(pid, sig) };
}

#[cfg(unix)]
fn subscribe_stream_events_unix() -> anyhow::Result<Option<StreamSubscription>> {
    use std::io::{BufRead, BufReader, Write};
    use std::os::unix::net::UnixStream;

    let socket_path = daemon_socket_path()?;
    let mut stream = match UnixStream::connect(&socket_path) {
        Ok(s) => s,
        Err(_) => return Ok(None),
    };

    let req = SocketRequest {
        version: PROTOCOL_VERSION,
        request_id: new_request_id(),
        command: "stream-subscribe".to_string(),
        payload: serde_json::json!({}),
    };
    let req_line = serde_json::to_string(&req)?;
    stream.write_all(req_line.as_bytes())?;
    stream.write_all(b"\n")?;
    stream.flush()?;

    // Must receive an explicit stream ACK before treating the subscription as live.
    {
        let mut ack_reader = BufReader::new(stream.try_clone()?);
        let mut ack_line = String::new();
        if ack_reader.read_line(&mut ack_line)? == 0 {
            return Ok(None);
        }
        let ack_json: serde_json::Value = match serde_json::from_str(ack_line.trim()) {
            Ok(v) => v,
            Err(_) => return Ok(None),
        };
        let ok = ack_json
            .get("status")
            .and_then(|v| v.as_str())
            .map(|s| s == "ok")
            .unwrap_or(false);
        let streaming = ack_json
            .get("streaming")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        if !(ok && streaming) {
            return Ok(None);
        }
    }

    let (tx, rx) = std::sync::mpsc::channel::<crate::daemon_stream::DaemonStreamEvent>();
    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let stop_thread = std::sync::Arc::clone(&stop);
    stream
        .set_read_timeout(Some(std::time::Duration::from_millis(500)))
        .ok();
    std::thread::spawn(move || {
        let mut reader = BufReader::new(stream);
        loop {
            if stop_thread.load(std::sync::atomic::Ordering::Relaxed) {
                break;
            }
            let mut line = String::new();
            let n = match reader.read_line(&mut line) {
                Ok(n) => n,
                Err(e)
                    if e.kind() == std::io::ErrorKind::WouldBlock
                        || e.kind() == std::io::ErrorKind::TimedOut =>
                {
                    continue;
                }
                Err(_) => break,
            };
            if n == 0 {
                break;
            }
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            if let Ok(event) =
                serde_json::from_str::<crate::daemon_stream::DaemonStreamEvent>(trimmed)
            {
                if tx.send(event).is_err() {
                    break;
                }
            }
        }
    });

    Ok(Some(StreamSubscription { rx, stop }))
}

/// Check whether a Unix PID is alive using `kill -0`.
#[cfg(unix)]
fn pid_alive(pid: i32) -> bool {
    // SAFETY: kill(pid, 0) is a read-only existence check; no signal is sent.
    // We declare the extern fn inline to avoid a compile-time libc dependency
    // at the crate level (libc is only in [target.'cfg(unix)'.dependencies]).
    unsafe extern "C" {
        fn kill(pid: i32, sig: i32) -> i32;
    }
    // SAFETY: kill with sig=0 never sends a signal; it only checks PID existence.
    let result = unsafe { kill(pid, 0) };
    result == 0
}

// ── Tests ────────────────────────────────────────────────────────────────────

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

    #[cfg(unix)]
    fn wait_for_daemon_runtime_ready(home: &std::path::Path) -> bool {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        let pid_path = home.join(".atm/daemon/atm-daemon.pid");
        while std::time::Instant::now() < deadline {
            if pid_path.exists() && super::daemon_socket_connectable(home) {
                return true;
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
        false
    }

    #[cfg(unix)]
    fn wait_for_daemon_version(home: &std::path::Path, expected_version: &str) -> Option<i32> {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        let pid_path = home.join(".atm/daemon/atm-daemon.pid");
        let status_path = home.join(".atm/daemon/status.json");
        while std::time::Instant::now() < deadline {
            let pid = std::fs::read_to_string(&pid_path)
                .ok()
                .and_then(|raw| raw.trim().parse::<i32>().ok());
            let status_version = std::fs::read_to_string(&status_path)
                .ok()
                .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
                .and_then(|json| {
                    json.get("version")
                        .and_then(serde_json::Value::as_str)
                        .map(str::to_string)
                });
            if let Some(pid) = pid
                && super::pid_alive(pid)
                && status_version.as_deref() == Some(expected_version)
            {
                return Some(pid);
            }
            std::thread::sleep(std::time::Duration::from_millis(25));
        }
        None
    }

    #[cfg(unix)]
    fn fake_lock_metadata(home: &str, pid: u32) -> DaemonLockMetadata {
        DaemonLockMetadata {
            pid,
            executable_path: std::env::temp_dir()
                .join("fake-atm-daemon")
                .to_string_lossy()
                .into_owned(),
            home_scope: home.to_string(),
            version: "0.0.1".to_string(),
            written_at: chrono::Utc::now().to_rfc3339(),
        }
    }
    use serial_test::serial;

    fn with_autostart_disabled<T>(f: impl FnOnce() -> T) -> T {
        let old = std::env::var("ATM_DAEMON_AUTOSTART").ok();
        // SAFETY: test-only env mutation guarded by #[serial] on callers.
        unsafe { std::env::set_var("ATM_DAEMON_AUTOSTART", "0") };
        let out = f();
        // SAFETY: test-only env mutation guarded by #[serial] on callers.
        unsafe {
            match old {
                Some(v) => std::env::set_var("ATM_DAEMON_AUTOSTART", v),
                None => std::env::remove_var("ATM_DAEMON_AUTOSTART"),
            }
        }
        out
    }

    #[test]
    fn test_socket_request_serialization() {
        let req = SocketRequest {
            version: 1,
            request_id: "req-123".to_string(),
            command: "agent-state".to_string(),
            payload: serde_json::json!({ "agent": "arch-ctm", "team": "atm-dev" }),
        };

        let json = serde_json::to_string(&req).unwrap();
        let decoded: SocketRequest = serde_json::from_str(&json).unwrap();

        assert_eq!(decoded.version, 1);
        assert_eq!(decoded.request_id, "req-123");
        assert_eq!(decoded.command, "agent-state");
    }

    #[test]
    fn test_socket_response_ok_deserialization() {
        let json = r#"{"version":1,"request_id":"req-123","status":"ok","payload":{"state":"idle","last_transition":"2026-02-16T22:30:00Z"}}"#;
        let resp: SocketResponse = serde_json::from_str(json).unwrap();

        assert!(resp.is_ok());
        assert_eq!(resp.request_id, "req-123");
        assert!(resp.payload.is_some());
        assert!(resp.error.is_none());
    }

    #[test]
    fn test_socket_response_error_deserialization() {
        let json = r#"{"version":1,"request_id":"req-456","status":"error","error":{"code":"AGENT_NOT_FOUND","message":"Agent 'unknown' is not tracked"}}"#;
        let resp: SocketResponse = serde_json::from_str(json).unwrap();

        assert!(!resp.is_ok());
        let err = resp.error.unwrap();
        assert_eq!(err.code, "AGENT_NOT_FOUND");
    }

    #[test]
    fn test_agent_state_info_deserialization() {
        let json = r#"{"state":"idle","last_transition":"2026-02-16T22:30:00Z"}"#;
        let info: AgentStateInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.state, "idle");
        assert_eq!(
            info.last_transition.as_deref(),
            Some("2026-02-16T22:30:00Z")
        );
    }

    #[test]
    fn test_agent_state_info_missing_transition() {
        let json = r#"{"state":"launching"}"#;
        let info: AgentStateInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.state, "launching");
        assert!(info.last_transition.is_none());
    }

    #[test]
    #[serial]
    fn test_query_daemon_no_socket_returns_none() {
        with_autostart_disabled(|| {
            // Without a running daemon the query should gracefully return None.
            // We ensure no real socket path is present by using a non-existent dir.
            // This test is platform-independent: on non-unix it always returns None.
            let req = SocketRequest {
                version: PROTOCOL_VERSION,
                request_id: "req-test".to_string(),
                command: "agent-state".to_string(),
                payload: serde_json::json!({}),
            };
            // Override socket path resolution is not straightforward without DI;
            // the test relies on the daemon not being present in the test environment.
            // On CI this will always be None. Locally too unless daemon is running.
            let result = query_daemon(&req);
            assert!(result.is_ok());
            // If daemon happens to be running, we just check the call didn't panic.
        });
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_daemon_autostart_flag_parsing() {
        let old = std::env::var("ATM_DAEMON_AUTOSTART").ok();

        // Unset => enabled (opt-out model).
        // SAFETY: serialized env mutation in test.
        unsafe { std::env::remove_var("ATM_DAEMON_AUTOSTART") };
        assert!(daemon_autostart_enabled());

        // SAFETY: serialized env mutation in test.
        unsafe { std::env::set_var("ATM_DAEMON_AUTOSTART", "1") };
        assert!(daemon_autostart_enabled());
        // SAFETY: serialized env mutation in test.
        unsafe { std::env::set_var("ATM_DAEMON_AUTOSTART", "true") };
        assert!(daemon_autostart_enabled());
        // SAFETY: serialized env mutation in test.
        unsafe { std::env::set_var("ATM_DAEMON_AUTOSTART", "yes") };
        assert!(daemon_autostart_enabled());
        // SAFETY: serialized env mutation in test.
        unsafe { std::env::set_var("ATM_DAEMON_AUTOSTART", "0") };
        assert!(!daemon_autostart_enabled());
        // SAFETY: serialized env mutation in test.
        unsafe { std::env::set_var("ATM_DAEMON_AUTOSTART", "false") };
        assert!(!daemon_autostart_enabled());
        // SAFETY: serialized env mutation in test.
        unsafe { std::env::set_var("ATM_DAEMON_AUTOSTART", "no") };
        assert!(!daemon_autostart_enabled());
        // Invalid values remain enabled unless explicitly falsey.
        // SAFETY: serialized env mutation in test.
        unsafe { std::env::set_var("ATM_DAEMON_AUTOSTART", "maybe") };
        assert!(daemon_autostart_enabled());

        // SAFETY: serialized env mutation in test.
        unsafe {
            match old {
                Some(v) => std::env::set_var("ATM_DAEMON_AUTOSTART", v),
                None => std::env::remove_var("ATM_DAEMON_AUTOSTART"),
            }
        }
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_resolve_daemon_binary_honors_override() {
        let old = std::env::var("ATM_DAEMON_BIN").ok();
        let tmp = tempfile::tempdir().unwrap();
        let custom = tmp.path().join("custom-atm-daemon");
        std::fs::write(&custom, "#!/bin/sh\nexit 0\n").unwrap();
        // SAFETY: serialized env mutation in test.
        unsafe { std::env::set_var("ATM_DAEMON_BIN", &custom) };
        let resolved = resolve_daemon_binary();
        assert_eq!(std::path::PathBuf::from(resolved), custom);
        // SAFETY: serialized env mutation in test.
        unsafe {
            match old {
                Some(v) => std::env::set_var("ATM_DAEMON_BIN", v),
                None => std::env::remove_var("ATM_DAEMON_BIN"),
            }
        }
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_cleanup_stale_runtime_files_removes_dead_pid_file() {
        use std::fs;

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let daemon_dir = home.join(".atm/daemon");
        fs::create_dir_all(&daemon_dir).unwrap();

        let pid_path = daemon_dir.join("atm-daemon.pid");
        fs::write(&pid_path, "999999\n").unwrap();
        assert!(pid_path.exists());

        cleanup_stale_daemon_runtime_files(home);
        assert!(
            !pid_path.exists(),
            "stale PID file should be removed when PID is not alive"
        );
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_cleanup_stale_runtime_files_handles_malformed_pid() {
        use std::fs;

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let daemon_dir = home.join(".atm/daemon");
        fs::create_dir_all(&daemon_dir).unwrap();

        let pid_path = daemon_dir.join("atm-daemon.pid");
        let socket_path = daemon_dir.join("atm-daemon.sock");
        fs::write(&pid_path, "not-a-pid\n").unwrap();
        fs::write(&socket_path, "stale").unwrap();

        cleanup_stale_daemon_runtime_files(home);

        assert!(
            !pid_path.exists(),
            "malformed PID file should be removed during cleanup"
        );
        assert!(
            !socket_path.exists(),
            "stale socket should be removed when PID ownership is known-dead"
        );
    }

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

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();
        let daemon_dir = home.join(".atm/daemon");
        fs::create_dir_all(&daemon_dir).unwrap();

        let pid_path = daemon_dir.join("atm-daemon.pid");
        let socket_path = daemon_dir.join("atm-daemon.sock");
        fs::write(&pid_path, "123\n").unwrap();
        fs::write(&socket_path, "stale").unwrap();
        let mut perms = fs::metadata(&pid_path).unwrap().permissions();
        perms.set_mode(0o000);
        fs::set_permissions(&pid_path, perms).unwrap();

        cleanup_stale_daemon_runtime_files(home);
        assert!(
            socket_path.exists(),
            "socket must not be removed when PID ownership cannot be read"
        );

        // Restore permissions so tempdir cleanup succeeds.
        let mut restore = fs::metadata(&pid_path).unwrap().permissions();
        restore.set_mode(0o600);
        fs::set_permissions(&pid_path, restore).unwrap();
    }

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

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_path_buf();
        let script_path = home.join("fake-daemon-fail.sh");
        let script = r#"#!/bin/sh
set -eu
echo "fatal: invalid plugin config" >&2
exit 42
"#;
        fs::write(&script_path, script).unwrap();
        let mut perms = fs::metadata(&script_path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap();

        let old_home = std::env::var("ATM_HOME").ok();
        let old_bin = std::env::var("ATM_DAEMON_BIN").ok();
        let old_auto = std::env::var("ATM_DAEMON_AUTOSTART").ok();
        unsafe {
            std::env::set_var("ATM_HOME", &home);
            std::env::set_var("ATM_DAEMON_BIN", &script_path);
            std::env::set_var("ATM_DAEMON_AUTOSTART", "1");
        }

        let err = ensure_daemon_running_unix().expect_err("startup should fail");
        let msg = err.to_string();
        assert!(
            msg.contains("stderr_tail="),
            "error must include captured stderr tail: {msg}"
        );
        assert!(
            msg.contains("invalid plugin config"),
            "stderr tail should include daemon stderr content: {msg}"
        );

        unsafe {
            match old_home {
                Some(v) => std::env::set_var("ATM_HOME", v),
                None => std::env::remove_var("ATM_HOME"),
            }
            match old_bin {
                Some(v) => std::env::set_var("ATM_DAEMON_BIN", v),
                None => std::env::remove_var("ATM_DAEMON_BIN"),
            }
            match old_auto {
                Some(v) => std::env::set_var("ATM_DAEMON_AUTOSTART", v),
                None => std::env::remove_var("ATM_DAEMON_AUTOSTART"),
            }
        }
    }

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

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_path_buf();
        let script_path = home.join("fake-daemon-never-ready.sh");
        let script = r#"#!/bin/sh
set -eu
sleep 10
"#;
        fs::write(&script_path, script).unwrap();
        let mut perms = fs::metadata(&script_path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap();

        let old_home = std::env::var("ATM_HOME").ok();
        let old_bin = std::env::var("ATM_DAEMON_BIN").ok();
        let old_auto = std::env::var("ATM_DAEMON_AUTOSTART").ok();
        unsafe {
            std::env::set_var("ATM_HOME", &home);
            std::env::set_var("ATM_DAEMON_BIN", &script_path);
            std::env::set_var("ATM_DAEMON_AUTOSTART", "1");
        }

        let err = ensure_daemon_running_unix().expect_err("startup should time out");
        let msg = err.to_string();
        assert!(
            msg.contains("daemon startup timed out after 5s"),
            "timeout error should include actionable timeout details: {msg}"
        );
        assert!(
            msg.contains("pid_path="),
            "timeout error should include pid path"
        );
        assert!(
            msg.contains("socket_path="),
            "timeout error should include socket path"
        );

        unsafe {
            match old_home {
                Some(v) => std::env::set_var("ATM_HOME", v),
                None => std::env::remove_var("ATM_HOME"),
            }
            match old_bin {
                Some(v) => std::env::set_var("ATM_DAEMON_BIN", v),
                None => std::env::remove_var("ATM_DAEMON_BIN"),
            }
            match old_auto {
                Some(v) => std::env::set_var("ATM_DAEMON_AUTOSTART", v),
                None => std::env::remove_var("ATM_DAEMON_AUTOSTART"),
            }
        }
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_ensure_daemon_running_serializes_concurrent_start() {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;
        use std::sync::Arc;
        use std::thread;

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_path_buf();
        let script_path = home.join("fake-daemon.sh");

        let script = r#"#!/bin/sh
set -eu
home="${ATM_HOME:?}"
mkdir -p "$home/.atm/daemon"
mkdir -p "$home/spawn-markers"
touch "$home/spawn-markers/spawn.$$"
echo $$ > "$home/.atm/daemon/atm-daemon.pid"
sleep 2
"#;
        fs::write(&script_path, script).unwrap();
        let mut perms = fs::metadata(&script_path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap();

        let old_home = std::env::var("ATM_HOME").ok();
        let old_bin = std::env::var("ATM_DAEMON_BIN").ok();
        let old_auto = std::env::var("ATM_DAEMON_AUTOSTART").ok();
        unsafe {
            std::env::set_var("ATM_HOME", &home);
            std::env::set_var("ATM_DAEMON_BIN", &script_path);
            std::env::set_var("ATM_DAEMON_AUTOSTART", "1");
        }

        let mut handles = Vec::new();
        let barrier = Arc::new(std::sync::Barrier::new(2));
        for _ in 0..2 {
            let b = Arc::clone(&barrier);
            handles.push(thread::spawn(move || {
                b.wait();
                ensure_daemon_running_unix().unwrap();
            }));
        }
        for h in handles {
            h.join().unwrap();
        }

        let count = fs::read_dir(home.join("spawn-markers"))
            .ok()
            .into_iter()
            .flatten()
            .filter_map(Result::ok)
            .count();
        assert_eq!(
            count, 1,
            "concurrent startup attempts should spawn at most one daemon process"
        );

        unsafe {
            match old_home {
                Some(v) => std::env::set_var("ATM_HOME", v),
                None => std::env::remove_var("ATM_HOME"),
            }
            match old_bin {
                Some(v) => std::env::set_var("ATM_DAEMON_BIN", v),
                None => std::env::remove_var("ATM_DAEMON_BIN"),
            }
            match old_auto {
                Some(v) => std::env::set_var("ATM_DAEMON_AUTOSTART", v),
                None => std::env::remove_var("ATM_DAEMON_AUTOSTART"),
            }
        }
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_write_daemon_lock_metadata_contains_identity_fields() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path();

        write_daemon_lock_metadata(home, "9.9.9-test").expect("write lock metadata");

        let path = home.join(".atm/daemon/daemon.lock.meta.json");
        let raw = std::fs::read_to_string(&path).expect("read lock metadata");
        let meta: DaemonLockMetadata = serde_json::from_str(&raw).expect("parse lock metadata");

        assert_eq!(meta.pid, std::process::id());
        assert_eq!(meta.version, "9.9.9-test");
        assert!(
            !meta.executable_path.trim().is_empty(),
            "executable path must be populated"
        );
        assert!(
            !meta.home_scope.trim().is_empty(),
            "home scope must be populated"
        );
    }

    #[cfg(unix)]
    #[test]
    fn test_evaluate_daemon_identity_mismatch_requires_metadata_or_socket() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_string_lossy().into_owned();
        let snapshot = DaemonIdentitySnapshot::default();
        let reason = evaluate_daemon_identity_mismatch(
            &snapshot,
            &home,
            std::ffi::OsStr::new("atm-daemon"),
            env!("CARGO_PKG_VERSION"),
            |_| true,
            |_| Some("atm-daemon".to_string()),
        );

        assert_eq!(reason, None);
    }

    #[cfg(unix)]
    #[test]
    fn test_evaluate_daemon_identity_mismatch_reports_missing_metadata_when_socket_live() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_string_lossy().into_owned();
        let snapshot = DaemonIdentitySnapshot {
            socket_connectable: true,
            ..Default::default()
        };
        let reason = evaluate_daemon_identity_mismatch(
            &snapshot,
            &home,
            std::ffi::OsStr::new("atm-daemon"),
            env!("CARGO_PKG_VERSION"),
            |_| true,
            |_| Some("atm-daemon".to_string()),
        )
        .expect("expected mismatch");

        assert!(reason.contains("lock metadata missing"));
    }

    #[cfg(unix)]
    #[test]
    fn test_evaluate_daemon_identity_mismatch_reports_command_mismatch() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_string_lossy().into_owned();
        let snapshot = DaemonIdentitySnapshot {
            metadata: Some(fake_lock_metadata(&home, 4242)),
            pid_from_file: Some(4242),
            socket_connectable: true,
            ..Default::default()
        };
        let reason = evaluate_daemon_identity_mismatch(
            &snapshot,
            &home,
            std::ffi::OsStr::new("atm-daemon"),
            env!("CARGO_PKG_VERSION"),
            |_| true,
            |_| Some("/usr/bin/python3 -m stale-daemon".to_string()),
        )
        .expect("expected mismatch");

        assert!(reason.contains("running command"));
        assert!(reason.contains("expected daemon binary"));
    }

    #[cfg(unix)]
    #[test]
    fn test_evaluate_daemon_identity_mismatch_reports_version_mismatch() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_string_lossy().into_owned();
        let snapshot = DaemonIdentitySnapshot {
            metadata: Some(fake_lock_metadata(&home, 4242)),
            pid_from_file: Some(4242),
            version_from_status: Some("0.0.1".to_string()),
            socket_connectable: true,
            ..Default::default()
        };
        let reason = evaluate_daemon_identity_mismatch(
            &snapshot,
            &home,
            std::ffi::OsStr::new("atm-daemon"),
            env!("CARGO_PKG_VERSION"),
            |_| true,
            |_| Some("atm-daemon".to_string()),
        )
        .expect("expected mismatch");

        assert!(reason.contains("daemon version mismatch"));
        assert!(reason.contains("running=0.0.1"));
    }

    #[cfg(unix)]
    #[test]
    fn test_evaluate_daemon_identity_mismatch_accepts_matching_identity() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_string_lossy().into_owned();
        let snapshot = DaemonIdentitySnapshot {
            metadata: Some(fake_lock_metadata(&home, 4242)),
            pid_from_file: Some(4242),
            version_from_status: Some(env!("CARGO_PKG_VERSION").to_string()),
            socket_connectable: true,
            ..Default::default()
        };
        let reason = evaluate_daemon_identity_mismatch(
            &snapshot,
            &home,
            std::ffi::OsStr::new("atm-daemon"),
            env!("CARGO_PKG_VERSION"),
            |_| true,
            |_| Some("atm-daemon --serve".to_string()),
        );

        assert_eq!(reason, None);
    }

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

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_path_buf();
        fs::create_dir_all(home.join(".atm/daemon")).unwrap();

        // Simulate stale metadata from a dead prior daemon instance.
        fs::write(home.join(".atm/daemon/atm-daemon.pid"), "999999\n").unwrap();
        let stale = DaemonLockMetadata {
            pid: 999999,
            executable_path: std::env::temp_dir()
                .join("old-atm-daemon")
                .to_string_lossy()
                .to_string(),
            home_scope: home.to_string_lossy().to_string(),
            version: "0.0.1".to_string(),
            written_at: chrono::Utc::now().to_rfc3339(),
        };
        fs::write(
            home.join(".atm/daemon/daemon.lock.meta.json"),
            serde_json::to_string_pretty(&stale).unwrap(),
        )
        .unwrap();

        let script_path = home.join("fake-daemon-start.sh");
        let script = format!(
            r#"#!/bin/sh
set -eu
home="${{ATM_HOME:?}}"
mkdir -p "$home/.atm/daemon"
pid=$$
echo "$pid" > "$home/.atm/daemon/atm-daemon.pid"
cat > "$home/.atm/daemon/status.json" <<'JSON'
{{"timestamp":"2026-01-01T00:00:00Z","pid":0,"version":"{}","uptime_secs":1,"plugins":[],"teams":[]}}
JSON
python3 - <<'PY'
import json, os
home=os.environ["ATM_HOME"]
path=os.path.join(home, ".atm", "daemon", "status.json")
with open(path, "r", encoding="utf-8") as f:
    obj=json.load(f)
obj["pid"]=os.getpid()
with open(path, "w", encoding="utf-8") as f:
    json.dump(obj, f)
open(os.path.join(home, "started-ok"), "w").write("ok")
PY
sleep 8
"#,
            env!("CARGO_PKG_VERSION")
        );
        fs::write(&script_path, script).unwrap();
        let mut perms = fs::metadata(&script_path).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&script_path, perms).unwrap();

        let old_home = std::env::var("ATM_HOME").ok();
        let old_bin = std::env::var("ATM_DAEMON_BIN").ok();
        let old_auto = std::env::var("ATM_DAEMON_AUTOSTART").ok();
        unsafe {
            std::env::set_var("ATM_HOME", &home);
            std::env::set_var("ATM_DAEMON_BIN", &script_path);
            std::env::set_var("ATM_DAEMON_AUTOSTART", "1");
        }

        ensure_daemon_running_unix().expect("must recover from dead stale pid metadata");
        let marker = home.join("started-ok");
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        while std::time::Instant::now() < deadline && !marker.exists() {
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        assert!(marker.exists(), "expected replacement daemon to start");

        if let Ok(pid_str) = std::fs::read_to_string(home.join(".atm/daemon/atm-daemon.pid"))
            && let Ok(pid) = pid_str.trim().parse::<i32>()
            && pid_alive(pid)
        {
            send_signal(pid, 15);
        }

        unsafe {
            match old_home {
                Some(v) => std::env::set_var("ATM_HOME", v),
                None => std::env::remove_var("ATM_HOME"),
            }
            match old_bin {
                Some(v) => std::env::set_var("ATM_DAEMON_BIN", v),
                None => std::env::remove_var("ATM_DAEMON_BIN"),
            }
            match old_auto {
                Some(v) => std::env::set_var("ATM_DAEMON_AUTOSTART", v),
                None => std::env::remove_var("ATM_DAEMON_AUTOSTART"),
            }
        }
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    #[ignore = "smoke coverage only; exercises real subprocess and socket timing"]
    fn test_ensure_daemon_running_restarts_identity_mismatch_daemon() {
        use std::fs;
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().to_path_buf();
        fs::create_dir_all(home.join(".atm/daemon")).unwrap();

        let stale_script = home.join("stale-daemon.sh");
        let stale = r#"#!/bin/sh
set -eu
home="${ATM_HOME:?}"
mkdir -p "$home/.atm/daemon"
pid=$$
echo "$pid" > "$home/.atm/daemon/atm-daemon.pid"
cat > "$home/.atm/daemon/status.json" <<'JSON'
{"timestamp":"2026-01-01T00:00:00Z","pid":0,"version":"0.0.1","uptime_secs":1,"plugins":[],"teams":[]}
JSON
python3 - <<'PY'
import json, os
home=os.environ["ATM_HOME"]
path=os.path.join(home, ".atm", "daemon", "status.json")
with open(path, "r", encoding="utf-8") as f:
    obj=json.load(f)
obj["pid"]=os.getpid()
with open(path, "w", encoding="utf-8") as f:
    json.dump(obj, f)
PY
exec python3 - "$home/.atm/daemon/atm-daemon.sock" <<'PY'
import os, signal, socket, sys, time
path=sys.argv[1]
try:
    os.unlink(path)
except FileNotFoundError:
    pass
srv=socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
srv.bind(path)
srv.listen(1)
def shutdown(*_):
    try:
        srv.close()
    finally:
        try:
            os.unlink(path)
        except FileNotFoundError:
            pass
    sys.exit(0)
signal.signal(signal.SIGTERM, shutdown)
signal.signal(signal.SIGINT, shutdown)
while True:
    time.sleep(1)
PY
"#;
        fs::write(&stale_script, stale).unwrap();
        let mut stale_perms = fs::metadata(&stale_script).unwrap().permissions();
        stale_perms.set_mode(0o755);
        fs::set_permissions(&stale_script, stale_perms).unwrap();

        let expected_script = home.join("expected-daemon.sh");
        let expected = format!(
            r#"#!/bin/sh
set -eu
home="${{ATM_HOME:?}}"
mkdir -p "$home/.atm/daemon"
pid=$$
echo "$pid" > "$home/.atm/daemon/atm-daemon.pid"
cat > "$home/.atm/daemon/status.json" <<'JSON'
{{"timestamp":"2026-01-01T00:00:00Z","pid":0,"version":"{}","uptime_secs":1,"plugins":[],"teams":[]}}
JSON
python3 - <<'PY'
import json, os
home=os.environ["ATM_HOME"]
path=os.path.join(home, ".atm", "daemon", "status.json")
with open(path, "r", encoding="utf-8") as f:
    obj=json.load(f)
obj["pid"]=os.getpid()
with open(path, "w", encoding="utf-8") as f:
    json.dump(obj, f)
open(os.path.join(home, "replacement-started"), "w").write("ok")
with open(os.path.join(home, "replacement-started"), "a", encoding="utf-8") as f:
    f.flush()
    os.fsync(f.fileno())
PY
sleep 8
"#,
            env!("CARGO_PKG_VERSION")
        );
        fs::write(&expected_script, expected).unwrap();
        let mut expected_perms = fs::metadata(&expected_script).unwrap().permissions();
        expected_perms.set_mode(0o755);
        fs::set_permissions(&expected_script, expected_perms).unwrap();

        let old_home = std::env::var("ATM_HOME").ok();
        let old_bin = std::env::var("ATM_DAEMON_BIN").ok();
        let old_auto = std::env::var("ATM_DAEMON_AUTOSTART").ok();
        unsafe {
            std::env::set_var("ATM_HOME", &home);
            std::env::set_var("ATM_DAEMON_AUTOSTART", "0");
        }
        let mut stale_child = std::process::Command::new(&stale_script)
            .env("ATM_HOME", &home)
            .spawn()
            .expect("spawn stale daemon");
        assert!(
            wait_for_daemon_runtime_ready(&home),
            "stale daemon must publish pid file and bind socket before mismatch check"
        );
        let stale_pid: u32 = std::fs::read_to_string(home.join(".atm/daemon/atm-daemon.pid"))
            .unwrap()
            .trim()
            .parse()
            .unwrap();
        let stale_metadata = DaemonLockMetadata {
            pid: stale_pid,
            executable_path: stale_script.to_string_lossy().to_string(),
            home_scope: std::fs::canonicalize(&home)
                .unwrap_or_else(|_| home.clone())
                .to_string_lossy()
                .to_string(),
            version: "0.0.1".to_string(),
            written_at: chrono::Utc::now().to_rfc3339(),
        };
        std::fs::write(
            home.join(".atm/daemon/daemon.lock.meta.json"),
            serde_json::to_string_pretty(&stale_metadata).unwrap(),
        )
        .unwrap();

        unsafe {
            std::env::set_var("ATM_DAEMON_BIN", &expected_script);
            std::env::set_var("ATM_DAEMON_AUTOSTART", "1");
        }
        ensure_daemon_running_unix().expect("mismatch daemon should be restarted");

        let stale_exit_deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        let mut stale_exited = false;
        while std::time::Instant::now() < stale_exit_deadline {
            if stale_child.try_wait().ok().flatten().is_some() {
                stale_exited = true;
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
        let new_pid = wait_for_daemon_version(&home, env!("CARGO_PKG_VERSION"))
            .expect("replacement daemon missing");
        if !stale_exited && stale_child.try_wait().ok().flatten().is_none() {
            let _ = stale_child.kill();
            let _ = stale_child.wait();
        }
        assert!(
            stale_exited,
            "stale daemon must exit during mismatch restart"
        );
        assert!(new_pid > 1, "replacement daemon pid must be valid");

        if pid_alive(new_pid) {
            send_signal(new_pid, 15);
        }

        unsafe {
            match old_home {
                Some(v) => std::env::set_var("ATM_HOME", v),
                None => std::env::remove_var("ATM_HOME"),
            }
            match old_bin {
                Some(v) => std::env::set_var("ATM_DAEMON_BIN", v),
                None => std::env::remove_var("ATM_DAEMON_BIN"),
            }
            match old_auto {
                Some(v) => std::env::set_var("ATM_DAEMON_AUTOSTART", v),
                None => std::env::remove_var("ATM_DAEMON_AUTOSTART"),
            }
        }
    }

    #[test]
    fn test_new_request_id_is_unique() {
        let id1 = new_request_id();
        // Tiny sleep to ensure different nanosecond timestamp
        std::thread::sleep(std::time::Duration::from_nanos(1000));
        let id2 = new_request_id();
        // Both should be non-empty; may or may not be equal depending on timing
        assert!(!id1.is_empty());
        assert!(!id2.is_empty());
    }

    #[test]
    fn test_daemon_socket_path_contains_expected_suffix() {
        let path = daemon_socket_path().unwrap();
        assert!(path.to_string_lossy().ends_with("atm-daemon.sock"));
        assert!(path.to_string_lossy().contains(".atm/daemon"));
    }

    #[test]
    fn test_daemon_pid_path_contains_expected_suffix() {
        let path = daemon_pid_path().unwrap();
        assert!(path.to_string_lossy().ends_with("atm-daemon.pid"));
        assert!(path.to_string_lossy().contains(".atm/daemon"));
    }

    #[test]
    #[serial]
    fn test_query_agent_state_no_daemon_returns_none() {
        with_autostart_disabled(|| {
            // Graceful fallback: no daemon → Ok(None)
            let result = query_agent_state("arch-ctm", "atm-dev");
            assert!(result.is_ok());
            // Result is None unless daemon happens to be running
        });
    }

    #[test]
    #[serial]
    fn test_query_team_member_states_offline_returns_none() {
        with_autostart_disabled(|| {
            let tmp = tempfile::tempdir().expect("tempdir");
            let old_home = std::env::var("ATM_HOME").ok();
            // SAFETY: serialized test env mutation.
            unsafe { std::env::set_var("ATM_HOME", tmp.path()) };

            let result = query_team_member_states("atm-dev");

            // SAFETY: serialized test env mutation cleanup.
            unsafe {
                match old_home {
                    Some(v) => std::env::set_var("ATM_HOME", v),
                    None => std::env::remove_var("ATM_HOME"),
                }
            }

            assert!(
                matches!(result, Ok(None)),
                "offline daemon must map to Ok(None), got: {result:?}"
            );
        });
    }

    #[cfg(unix)]
    #[test]
    #[serial]
    fn test_query_team_member_states_invalid_payload_returns_err() {
        use std::io::{BufRead, BufReader, Write};
        use std::os::unix::net::UnixListener;

        with_autostart_disabled(|| {
            let tmp = tempfile::tempdir().expect("tempdir");
            let daemon_dir = tmp.path().join(".atm/daemon");
            std::fs::create_dir_all(&daemon_dir).expect("create daemon dir");
            let socket_path = daemon_dir.join("atm-daemon.sock");

            let listener = UnixListener::bind(&socket_path).expect("bind socket");
            let handle = std::thread::spawn(move || {
                // Other concurrently running tests can occasionally hit this temporary
                // socket while ATM_HOME is overridden. Ignore non-target requests and
                // keep waiting until we receive the expected list-agents query.
                for _ in 0..32 {
                    let (mut stream, _) = listener.accept().expect("accept");
                    let mut request_line = String::new();
                    let mut reader = BufReader::new(stream.try_clone().expect("clone stream"));
                    reader.read_line(&mut request_line).expect("read request");

                    if request_line.contains("\"command\":\"list-agents\"") {
                        let response = SocketResponse {
                            version: PROTOCOL_VERSION,
                            request_id: "req-test".to_string(),
                            status: "ok".to_string(),
                            payload: Some(serde_json::json!({
                                "agent": "arch-ctm",
                                "state": "active"
                            })),
                            error: None,
                        };
                        let line = serde_json::to_string(&response).expect("serialize response");
                        stream.write_all(line.as_bytes()).expect("write response");
                        stream.write_all(b"\n").expect("write newline");
                        return;
                    }

                    let ignored = SocketResponse {
                        version: PROTOCOL_VERSION,
                        request_id: "req-ignored".to_string(),
                        status: "error".to_string(),
                        payload: None,
                        error: Some(SocketError {
                            code: "IGNORED_FOR_TEST".to_string(),
                            message: "ignored non-list-agents request".to_string(),
                        }),
                    };
                    let line = serde_json::to_string(&ignored).expect("serialize ignored");
                    stream.write_all(line.as_bytes()).expect("write ignored");
                    stream.write_all(b"\n").expect("write newline");
                }
                panic!("expected list-agents request within retry budget");
            });

            let old_home = std::env::var("ATM_HOME").ok();
            // SAFETY: serialized test env mutation.
            unsafe { std::env::set_var("ATM_HOME", tmp.path()) };

            let result = query_team_member_states("atm-dev");

            // SAFETY: serialized test env mutation cleanup.
            unsafe {
                match old_home {
                    Some(v) => std::env::set_var("ATM_HOME", v),
                    None => std::env::remove_var("ATM_HOME"),
                }
            }

            handle.join().expect("mock daemon thread");
            let err = result.expect_err("invalid payload must return Err");
            assert!(
                err.to_string()
                    .contains("invalid canonical member-state payload"),
                "unexpected error: {err}"
            );
        });
    }

    #[test]
    fn test_agent_pane_info_deserialization() {
        let json = r#"{"pane_id":"%42","log_path":"/home/user/.claude/logs/arch-ctm.log"}"#;
        let info: AgentPaneInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.pane_id, "%42");
        assert_eq!(info.log_path, "/home/user/.claude/logs/arch-ctm.log");
    }

    #[test]
    #[serial]
    fn test_query_agent_pane_no_daemon_returns_none() {
        with_autostart_disabled(|| {
            // Graceful fallback: no daemon → Ok(None)
            let result = query_agent_pane("arch-ctm");
            assert!(result.is_ok());
            // Result is None unless daemon happens to be running
        });
    }

    #[test]
    fn test_launch_config_serialization() {
        let mut env_vars = std::collections::HashMap::new();
        env_vars.insert("EXTRA_VAR".to_string(), "value".to_string());

        let config = LaunchConfig {
            agent: "arch-ctm".to_string(),
            team: "atm-dev".to_string(),
            command: "codex --yolo".to_string(),
            prompt: Some("Review the bridge module".to_string()),
            timeout_secs: 30,
            env_vars,
            runtime: Some("codex".to_string()),
            resume_session_id: None,
        };

        let json = serde_json::to_string(&config).unwrap();
        let decoded: LaunchConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(decoded.agent, "arch-ctm");
        assert_eq!(decoded.team, "atm-dev");
        assert_eq!(decoded.command, "codex --yolo");
        assert_eq!(decoded.prompt.as_deref(), Some("Review the bridge module"));
        assert_eq!(decoded.timeout_secs, 30);
        assert_eq!(decoded.runtime.as_deref(), Some("codex"));
        assert!(decoded.resume_session_id.is_none());
        assert_eq!(
            decoded.env_vars.get("EXTRA_VAR").map(String::as_str),
            Some("value")
        );
    }

    #[test]
    fn test_launch_config_no_prompt_serialization() {
        let config = LaunchConfig {
            agent: "worker-1".to_string(),
            team: "my-team".to_string(),
            command: "codex --yolo".to_string(),
            prompt: None,
            timeout_secs: 60,
            env_vars: std::collections::HashMap::new(),
            runtime: None,
            resume_session_id: Some("sess-123".to_string()),
        };

        let json = serde_json::to_string(&config).unwrap();
        let decoded: LaunchConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(decoded.agent, "worker-1");
        assert!(decoded.prompt.is_none());
        assert!(decoded.env_vars.is_empty());
        assert!(decoded.runtime.is_none());
        assert_eq!(decoded.resume_session_id.as_deref(), Some("sess-123"));
    }

    #[test]
    fn test_launch_result_serialization() {
        let result = LaunchResult {
            agent: "arch-ctm".to_string(),
            pane_id: "%42".to_string(),
            state: "launching".to_string(),
            warning: None,
        };

        let json = serde_json::to_string(&result).unwrap();
        let decoded: LaunchResult = serde_json::from_str(&json).unwrap();

        assert_eq!(decoded.agent, "arch-ctm");
        assert_eq!(decoded.pane_id, "%42");
        assert_eq!(decoded.state, "launching");
        assert!(decoded.warning.is_none());
    }

    #[test]
    fn test_launch_result_with_warning_serialization() {
        let result = LaunchResult {
            agent: "arch-ctm".to_string(),
            pane_id: "%7".to_string(),
            state: "launching".to_string(),
            warning: Some("Readiness timeout reached".to_string()),
        };

        let json = serde_json::to_string(&result).unwrap();
        let decoded: LaunchResult = serde_json::from_str(&json).unwrap();

        assert_eq!(
            decoded.warning.as_deref(),
            Some("Readiness timeout reached")
        );
    }

    #[test]
    fn test_session_query_result_serialization() {
        let result = SessionQueryResult {
            session_id: "abc123".to_string(),
            process_id: 12345,
            alive: true,
            last_seen_at: Some("2026-03-10T00:00:00Z".to_string()),
            runtime: None,
            runtime_session_id: None,
            pane_id: None,
            runtime_home: None,
        };
        let json = serde_json::to_string(&result).unwrap();
        let decoded: SessionQueryResult = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.session_id, "abc123");
        assert_eq!(decoded.process_id, 12345);
        assert!(decoded.alive);
    }

    #[test]
    fn test_session_query_result_dead() {
        let json = r#"{"session_id":"xyz789","process_id":99,"alive":false}"#;
        let result: SessionQueryResult = serde_json::from_str(json).unwrap();
        assert_eq!(result.session_id, "xyz789");
        assert_eq!(result.process_id, 99);
        assert!(!result.alive);
        assert!(result.last_seen_at.is_none());
        assert!(result.runtime.is_none());
        assert!(result.runtime_session_id.is_none());
    }

    #[test]
    #[serial]
    fn test_query_session_no_daemon_returns_none() {
        with_autostart_disabled(|| {
            // Graceful fallback: no daemon → Ok(None)
            let result = query_session("team-lead");
            assert!(result.is_ok());
            // None unless daemon happens to be running
        });
    }

    #[test]
    #[serial]
    fn test_launch_agent_no_daemon_returns_none() {
        with_autostart_disabled(|| {
            if daemon_is_running() {
                // Shared dev machines may have daemon active; this test validates
                // no-daemon behavior only.
                return;
            }
            let config = LaunchConfig {
                agent: "test-agent".to_string(),
                team: "test-team".to_string(),
                command: "codex --yolo".to_string(),
                prompt: None,
                timeout_secs: 5,
                env_vars: std::collections::HashMap::new(),
                runtime: Some("codex".to_string()),
                resume_session_id: None,
            };
            // Without a running daemon the call should gracefully return Ok(None).
            // On non-Unix platforms it always returns None.
            // On Unix with no daemon socket present it also returns None.
            let result = launch_agent(&config);
            // The result should be Ok (no I/O error on missing socket)
            assert!(result.is_ok());
            // Result is None unless daemon happens to be running and handling "launch"
            // (which it won't be in a unit test environment)
        });
    }

    #[test]
    #[serial]
    fn test_register_hint_no_daemon_is_silent_skip() {
        with_autostart_disabled(|| {
            if daemon_is_running() {
                return;
            }
            let outcome = register_hint(
                "atm-dev",
                "arch-ctm",
                "sess-arch-ctm-test-1234",
                1234,
                Some("codex"),
                Some("thread-id:arch-ctm-test-1234"),
                None,
                None,
            )
            .expect("register-hint must not error when daemon unavailable");
            assert_eq!(outcome, RegisterHintOutcome::DaemonUnavailable);
        });
    }

    #[test]
    fn test_agent_summary_serialization() {
        let summary = AgentSummary {
            agent: "arch-ctm".to_string(),
            state: "idle".to_string(),
        };
        let json = serde_json::to_string(&summary).unwrap();
        let decoded: AgentSummary = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.agent, "arch-ctm");
        assert_eq!(decoded.state, "idle");
    }

    #[test]
    fn test_canonical_member_state_serialization() {
        let state = CanonicalMemberState {
            agent: "arch-ctm".to_string(),
            state: "active".to_string(),
            activity: "busy".to_string(),
            session_id: Some("sess-123".to_string()),
            process_id: Some(4242),
            last_alive_at: Some("2026-03-08T00:00:00Z".to_string()),
            reason: "session active with live pid".to_string(),
            source: "session_registry".to_string(),
            in_config: true,
        };
        let json = serde_json::to_string(&state).unwrap();
        let decoded: CanonicalMemberState = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.agent, "arch-ctm");
        assert_eq!(decoded.state, "active");
        assert_eq!(decoded.activity, "busy");
        assert_eq!(decoded.session_id.as_deref(), Some("sess-123"));
        assert_eq!(decoded.process_id, Some(4242));
        assert_eq!(
            decoded.last_alive_at.as_deref(),
            Some("2026-03-08T00:00:00Z")
        );
        assert!(decoded.in_config);
    }

    #[test]
    fn test_canonical_status_activity_labels_and_liveness() {
        let active = CanonicalMemberState {
            agent: "arch-ctm".to_string(),
            state: "active".to_string(),
            activity: "busy".to_string(),
            session_id: None,
            process_id: None,
            last_alive_at: None,
            reason: String::new(),
            source: String::new(),
            in_config: true,
        };
        let idle = CanonicalMemberState {
            state: "idle".to_string(),
            activity: "idle".to_string(),
            ..active.clone()
        };
        let dead = CanonicalMemberState {
            state: "offline".to_string(),
            activity: "unknown".to_string(),
            ..active.clone()
        };

        assert_eq!(canonical_status_label(Some(&active)), "Active");
        assert_eq!(canonical_status_label(Some(&idle)), "Idle");
        assert_eq!(canonical_status_label(Some(&dead)), "Dead");
        assert_eq!(canonical_status_label(None), "Unknown");

        assert_eq!(canonical_activity_label(Some(&active)), "Busy");
        assert_eq!(canonical_activity_label(Some(&idle)), "Idle");
        assert_eq!(canonical_activity_label(Some(&dead)), "Unknown");
        assert_eq!(canonical_activity_label(None), "Unknown");

        assert_eq!(canonical_liveness_bool(Some(&active)), Some(true));
        assert_eq!(canonical_liveness_bool(Some(&idle)), Some(true));
        assert_eq!(canonical_liveness_bool(Some(&dead)), Some(false));
        assert_eq!(canonical_liveness_bool(None), None);
    }

    #[test]
    fn test_decode_canonical_member_states_payload_rejects_invalid_schema() {
        let invalid = serde_json::json!({
            "agent": "arch-ctm",
            "state": "active"
        });
        let err = decode_canonical_member_states_payload(invalid).unwrap_err();
        assert!(
            err.to_string()
                .contains("invalid canonical member-state payload")
        );
    }

    #[test]
    fn test_decode_canonical_member_states_payload_accepts_valid_schema() {
        let valid = serde_json::json!([
            {
                "agent": "arch-ctm",
                "state": "active",
                "activity": "busy",
                "session_id": "sess-1",
                "process_id": 1234,
                "reason": "session active",
                "source": "session_registry",
                "in_config": false
            }
        ]);
        let states = decode_canonical_member_states_payload(valid).expect("valid payload");
        assert_eq!(states.len(), 1);
        assert_eq!(states[0].agent, "arch-ctm");
        assert_eq!(states[0].state, "active");
        assert!(!states[0].in_config);
    }

    #[test]
    fn test_decode_canonical_member_state_defaults_in_config_true_when_missing() {
        let json = r#"{
            "agent":"arch-ctm",
            "state":"active",
            "activity":"busy",
            "reason":"session active",
            "source":"session_registry"
        }"#;
        let state: CanonicalMemberState = serde_json::from_str(json).expect("decode");
        assert!(state.in_config);
    }

    #[test]
    fn test_decode_register_hint_response_ok_registered() {
        let response = SocketResponse {
            version: PROTOCOL_VERSION,
            request_id: "req-1".to_string(),
            status: "ok".to_string(),
            payload: Some(serde_json::json!({ "processed": true })),
            error: None,
        };
        let outcome = decode_register_hint_response(response).expect("ok response");
        assert_eq!(outcome, RegisterHintOutcome::Registered);
    }

    #[test]
    fn test_decode_register_hint_response_unknown_command_maps_to_unsupported() {
        let response = SocketResponse {
            version: PROTOCOL_VERSION,
            request_id: "req-1".to_string(),
            status: "error".to_string(),
            payload: None,
            error: Some(SocketError {
                code: "UNKNOWN_COMMAND".to_string(),
                message: "Unknown command: 'register-hint'".to_string(),
            }),
        };
        let outcome = decode_register_hint_response(response).expect("unknown command handled");
        assert_eq!(outcome, RegisterHintOutcome::UnsupportedDaemon);
    }

    // Unix-only: test PID alive check for the current process
    #[cfg(unix)]
    #[test]
    fn test_pid_alive_current_process() {
        let pid = std::process::id() as i32;
        assert!(pid_alive(pid));
    }

    #[cfg(unix)]
    #[test]
    fn test_pid_alive_nonexistent_pid() {
        // Use a PID that is extremely unlikely to exist: i32::MAX.
        // On Linux and macOS the max PID is 4194304 or similar; i32::MAX exceeds
        // the kernel's PID range and kill() will return ESRCH (no such process).
        assert!(!pid_alive(i32::MAX));
    }

    /// When `ATM_DAEMON_BIN` is set to a nonexistent path, `ensure_daemon_running`
    /// must return `Err` (spawn fails) rather than silently succeeding.
    /// This confirms that the `ATM_DAEMON_BIN` env var is read by the public API.
    ///
    /// The test is skipped when a live daemon is already running to avoid
    /// interfering with the running process.
    ///
    /// `#[serial]` is required because the test mutates the process environment.
    #[test]
    #[serial]
    fn test_ensure_daemon_running_reads_atm_daemon_bin() {
        // Skip if a live daemon is already running.
        if daemon_is_running() {
            return;
        }
        unsafe {
            std::env::set_var("ATM_DAEMON_BIN", "/nonexistent-bin-for-atm-test");
        }
        let result = ensure_daemon_running();
        unsafe {
            std::env::remove_var("ATM_DAEMON_BIN");
        }
        // On non-Unix the function is a no-op and always returns Ok(()).
        #[cfg(unix)]
        assert!(
            result.is_err(),
            "spawn of nonexistent binary must return Err on Unix"
        );
        #[cfg(not(unix))]
        assert!(
            result.is_ok(),
            "ensure_daemon_running is a no-op on non-Unix"
        );
    }

    // ── LifecycleSource / LifecycleSourceKind ────────────────────────────────

    #[test]
    fn lifecycle_source_kind_serializes_snake_case() {
        assert_eq!(
            serde_json::to_string(&LifecycleSourceKind::ClaudeHook).unwrap(),
            "\"claude_hook\""
        );
        assert_eq!(
            serde_json::to_string(&LifecycleSourceKind::AtmMcp).unwrap(),
            "\"atm_mcp\""
        );
        assert_eq!(
            serde_json::to_string(&LifecycleSourceKind::AgentHook).unwrap(),
            "\"agent_hook\""
        );
        assert_eq!(
            serde_json::to_string(&LifecycleSourceKind::Unknown).unwrap(),
            "\"unknown\""
        );
    }

    #[test]
    fn lifecycle_source_kind_deserializes_snake_case() {
        let kind: LifecycleSourceKind = serde_json::from_str("\"claude_hook\"").unwrap();
        assert_eq!(kind, LifecycleSourceKind::ClaudeHook);

        let kind: LifecycleSourceKind = serde_json::from_str("\"atm_mcp\"").unwrap();
        assert_eq!(kind, LifecycleSourceKind::AtmMcp);

        let kind: LifecycleSourceKind = serde_json::from_str("\"agent_hook\"").unwrap();
        assert_eq!(kind, LifecycleSourceKind::AgentHook);

        let kind: LifecycleSourceKind = serde_json::from_str("\"unknown\"").unwrap();
        assert_eq!(kind, LifecycleSourceKind::Unknown);
    }

    #[test]
    fn lifecycle_source_round_trip() {
        let src = LifecycleSource::new(LifecycleSourceKind::AtmMcp);
        let json = serde_json::to_string(&src).unwrap();
        assert!(json.contains("\"atm_mcp\""), "serialized: {json}");
        let decoded: LifecycleSource = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded.kind, LifecycleSourceKind::AtmMcp);
    }

    #[test]
    fn hook_event_payload_without_source_is_backward_compatible() {
        // A payload without the "source" field must still parse as SocketRequest.
        let json = r#"{
            "version": 1,
            "request_id": "req-test",
            "command": "hook-event",
            "payload": {
                "event": "session_start",
                "agent": "team-lead",
                "team": "atm-dev",
                "session_id": "abc-123"
            }
        }"#;
        let req: SocketRequest = serde_json::from_str(json).unwrap();
        // The payload's "source" field is absent — no panic, no error.
        assert!(req.payload.get("source").is_none());
        assert_eq!(req.command, "hook-event");
    }

    #[test]
    fn hook_event_payload_with_atm_mcp_source_parses() {
        let json = r#"{
            "version": 1,
            "request_id": "req-mcp",
            "command": "hook-event",
            "payload": {
                "event": "session_start",
                "agent": "arch-ctm",
                "team": "atm-dev",
                "session_id": "codex:abc-123",
                "source": {"kind": "atm_mcp"}
            }
        }"#;
        let req: SocketRequest = serde_json::from_str(json).unwrap();
        let source: LifecycleSource =
            serde_json::from_value(req.payload["source"].clone()).unwrap();
        assert_eq!(source.kind, LifecycleSourceKind::AtmMcp);
    }

    #[test]
    fn test_send_control_no_daemon_returns_err() {
        if daemon_is_running() {
            // Shared dev machines may have daemon active; this test validates
            // no-daemon behavior only.
            return;
        }
        // Without a running daemon, send_control must return Err (not None or panic).
        use crate::control::{CONTROL_SCHEMA_VERSION, ControlAction, ControlRequest};

        let req = ControlRequest {
            v: CONTROL_SCHEMA_VERSION,
            request_id: "req-test-ctrl".to_string(),
            msg_type: "control.stdin.request".to_string(),
            signal: None,
            sent_at: "2026-02-21T00:00:00Z".to_string(),
            team: "atm-dev".to_string(),
            session_id: String::new(),
            agent_id: "arch-ctm".to_string(),
            sender: "tui".to_string(),
            action: ControlAction::Stdin,
            payload: Some("hello".to_string()),
            content_ref: None,
            elicitation_id: None,
            decision: None,
        };

        let result = send_control(&req);
        // With no daemon running the call should fail gracefully (not panic).
        // We only assert it returns an Err — the exact message is implementation detail.
        assert!(
            result.is_err(),
            "send_control should return Err when daemon is not running"
        );
    }

    // ── Windows-specific tests ───────────────────────────────────────────────
    //
    // These tests validate the Windows code paths for daemon auto-start readiness
    // and lock behavior. On Windows, all daemon socket communication is intentionally
    // unavailable (Unix domain sockets only), so the contract is that every public
    // function returns `Ok(None)` or `false` without panicking or returning an error.
    //
    // Requirement: requirements.md §T.1 cross-platform row — "Windows CI coverage
    // must validate spawn/readiness/lock behavior".

    /// On Windows, `query_daemon` must return `Ok(None)` for any request.
    ///
    /// The daemon uses Unix domain sockets which are unavailable on Windows.
    /// The graceful fallback ensures the CLI degrades silently rather than
    /// failing with a platform-specific error.
    #[cfg(windows)]
    #[test]
    #[serial]
    fn windows_query_daemon_returns_ok_none() {
        let req = SocketRequest {
            version: PROTOCOL_VERSION,
            request_id: "req-win-test".to_string(),
            command: "agent-state".to_string(),
            payload: serde_json::json!({ "agent": "arch-ctm", "team": "atm-dev" }),
        };
        let result = query_daemon(&req);
        assert!(
            result.is_ok(),
            "query_daemon must not return Err on Windows"
        );
        assert!(
            result.unwrap().is_none(),
            "query_daemon must return Ok(None) on Windows (no Unix socket available)"
        );
    }

    /// On Windows, `daemon_is_running` must return `false` without panicking.
    ///
    /// The PID-file check uses Unix `kill(pid, 0)` which is unavailable on Windows.
    /// The Windows branch always returns `false` — validated here so CI catches
    /// any accidental regression that re-introduces a Unix-only code path.
    #[cfg(windows)]
    #[test]
    fn windows_daemon_is_running_returns_false() {
        // No daemon can be running on Windows (no Unix socket / PID-kill support).
        assert!(
            !daemon_is_running(),
            "daemon_is_running must return false on Windows"
        );
    }

    /// On Windows, `subscribe_stream_events` must return `Ok(None)`.
    ///
    /// Stream subscriptions require a long-lived Unix domain socket connection.
    /// The Windows branch short-circuits to `Ok(None)` so callers can treat the
    /// absence of stream events as equivalent to a daemon that is not running.
    #[cfg(windows)]
    #[test]
    fn windows_subscribe_stream_events_returns_ok_none() {
        let result = subscribe_stream_events();
        assert!(
            result.is_ok(),
            "subscribe_stream_events must not return Err on Windows"
        );
        assert!(
            result.unwrap().is_none(),
            "subscribe_stream_events must return Ok(None) on Windows"
        );
    }

    /// On Windows, `query_agent_state` must return `Ok(None)`.
    ///
    /// Exercises the full call path (including payload serialisation) to confirm
    /// that the Windows `Ok(None)` short-circuit in `query_daemon` propagates
    /// correctly through the higher-level wrapper.
    #[cfg(windows)]
    #[test]
    #[serial]
    fn windows_query_agent_state_returns_ok_none() {
        let result = query_agent_state("arch-ctm", "atm-dev");
        assert!(
            result.is_ok(),
            "query_agent_state must not return Err on Windows"
        );
        assert!(
            result.unwrap().is_none(),
            "query_agent_state must return Ok(None) on Windows"
        );
    }

    /// On Windows, `query_session` must return `Ok(None)`.
    #[cfg(windows)]
    #[test]
    #[serial]
    fn windows_query_session_returns_ok_none() {
        let result = query_session("team-lead");
        assert!(
            result.is_ok(),
            "query_session must not return Err on Windows"
        );
        assert!(
            result.unwrap().is_none(),
            "query_session must return Ok(None) on Windows"
        );
    }

    /// On Windows, `launch_agent` must return `Ok(None)`.
    ///
    /// Confirms that the auto-start path (which requires Unix `fork`/`exec`
    /// semantics) never executes on Windows and the call degrades gracefully.
    #[cfg(windows)]
    #[test]
    #[serial]
    fn windows_launch_agent_returns_ok_none() {
        let config = LaunchConfig {
            agent: "test-agent".to_string(),
            team: "test-team".to_string(),
            command: "codex --yolo".to_string(),
            prompt: None,
            timeout_secs: 5,
            env_vars: std::collections::HashMap::new(),
            runtime: Some("codex".to_string()),
            resume_session_id: None,
        };
        let result = launch_agent(&config);
        assert!(
            result.is_ok(),
            "launch_agent must not return Err on Windows (no daemon socket)"
        );
        assert!(
            result.unwrap().is_none(),
            "launch_agent must return Ok(None) on Windows"
        );
    }

    /// On Windows, the startup lock (`acquire_lock`) must be acquirable and
    /// automatically released on drop.
    ///
    /// The `ensure_daemon_running_unix` function is gated `#[cfg(unix)]` and
    /// never runs on Windows, but the startup-lock path (`fs2::LockFileEx`) is
    /// the same cross-platform primitive used throughout atm-core.  This test
    /// confirms the Windows lock backend works correctly in the context of the
    /// daemon startup directory layout.
    #[cfg(windows)]
    #[test]
    fn windows_startup_lock_acquires_and_releases() {
        use crate::io::lock::acquire_lock;
        use std::fs;

        let tmp = tempfile::tempdir().unwrap();
        let lock_dir = tmp.path().join("config").join("atm");
        fs::create_dir_all(&lock_dir).unwrap();
        let lock_path = lock_dir.join("daemon-start.lock");

        // Acquire the lock — mirrors what ensure_daemon_running_unix does.
        let lock = acquire_lock(&lock_path, 3);
        assert!(
            lock.is_ok(),
            "startup lock must be acquirable on Windows: {:?}",
            lock.err()
        );

        // Explicit drop releases the lock (Windows holds handles; explicit drop
        // ensures the LockFileEx unlock fires before we try to re-acquire).
        drop(lock.unwrap());

        // Re-acquire to confirm the lock was actually released.
        let lock2 = acquire_lock(&lock_path, 1);
        assert!(
            lock2.is_ok(),
            "startup lock must be re-acquirable after release on Windows"
        );
    }

    /// On Windows, `daemon_socket_path` must produce a path ending with the
    /// expected suffix regardless of the underlying home-directory resolver.
    #[cfg(windows)]
    #[test]
    fn windows_daemon_socket_path_has_correct_suffix() {
        let path = daemon_socket_path().unwrap();
        let s = path.to_string_lossy();
        assert!(
            s.ends_with("atm-daemon.sock"),
            "daemon_socket_path must end with 'atm-daemon.sock' on Windows, got: {s}"
        );
        assert!(
            s.contains(".atm") && s.contains("daemon"),
            "daemon_socket_path must contain '.atm/daemon' on Windows, got: {s}"
        );
    }

    /// On Windows, `daemon_pid_path` must produce a path ending with the
    /// expected suffix.
    #[cfg(windows)]
    #[test]
    fn windows_daemon_pid_path_has_correct_suffix() {
        let path = daemon_pid_path().unwrap();
        let s = path.to_string_lossy();
        assert!(
            s.ends_with("atm-daemon.pid"),
            "daemon_pid_path must end with 'atm-daemon.pid' on Windows, got: {s}"
        );
        assert!(
            s.contains(".atm") && s.contains("daemon"),
            "daemon_pid_path must contain '.atm/daemon' on Windows, got: {s}"
        );
    }

    /// On Windows, `send_control` must return `Err` (not panic) when the daemon
    /// is not reachable, because `send_control` intentionally propagates absence
    /// as an error (unlike the `Ok(None)` contract of other public functions).
    #[cfg(windows)]
    #[test]
    fn windows_send_control_no_daemon_returns_err() {
        use crate::control::{CONTROL_SCHEMA_VERSION, ControlAction, ControlRequest};

        let req = ControlRequest {
            v: CONTROL_SCHEMA_VERSION,
            request_id: "req-win-ctrl".to_string(),
            msg_type: "control.stdin.request".to_string(),
            signal: None,
            sent_at: "2026-02-21T00:00:00Z".to_string(),
            team: "atm-dev".to_string(),
            session_id: String::new(),
            agent_id: "arch-ctm".to_string(),
            sender: "tui".to_string(),
            action: ControlAction::Stdin,
            payload: Some("hello".to_string()),
            content_ref: None,
            elicitation_id: None,
            decision: None,
        };

        let result = send_control(&req);
        assert!(
            result.is_err(),
            "send_control must return Err on Windows when daemon is not reachable"
        );
    }

    #[test]
    fn test_send_control_builds_correct_socket_request() {
        // Verify the SocketRequest built inside send_control has the right shape
        // by re-creating it manually and checking serialization.
        use crate::control::{CONTROL_SCHEMA_VERSION, ControlAction, ControlRequest};

        let req = ControlRequest {
            v: CONTROL_SCHEMA_VERSION,
            request_id: "req-ctrl-check".to_string(),
            msg_type: "control.interrupt.request".to_string(),
            signal: Some("interrupt".to_string()),
            sent_at: "2026-02-21T00:00:00Z".to_string(),
            team: "atm-dev".to_string(),
            session_id: String::new(),
            agent_id: "arch-ctm".to_string(),
            sender: "tui".to_string(),
            action: ControlAction::Interrupt,
            payload: None,
            content_ref: None,
            elicitation_id: None,
            decision: None,
        };

        // The socket-level request_id is an independent correlation ID generated
        // by send_control (e.g., "sock-<nanos>").  It must NOT be the same as
        // the control payload's stable idempotency key (`req.request_id`).
        let control_payload = serde_json::to_value(&req).expect("serialize ControlRequest");
        let socket_req = SocketRequest {
            version: PROTOCOL_VERSION,
            // Distinct from req.request_id — mirrors what send_control generates.
            request_id: "sock-test-123".to_string(),
            command: "control".to_string(),
            payload: control_payload,
        };

        // Sanity check: outer request_id is the socket-level ID, not the control ID.
        assert_ne!(
            socket_req.request_id, req.request_id,
            "socket-level request_id must differ from control payload request_id"
        );
        assert_eq!(socket_req.request_id, "sock-test-123");

        let json = serde_json::to_string(&socket_req).expect("serialize SocketRequest");

        // Outer envelope fields.
        assert!(
            json.contains("\"command\":\"control\""),
            "command field missing"
        );

        // The control payload's request_id must appear inside the serialized
        // payload body, not as the outer SocketRequest.request_id.
        assert!(
            json.contains("\"request_id\":\"req-ctrl-check\""),
            "control payload request_id must appear inside the payload body"
        );

        // The outer socket-level request_id is present.
        assert!(
            json.contains("\"request_id\":\"sock-test-123\""),
            "socket-level request_id must appear in the outer envelope"
        );

        // The type field in the control payload.
        assert!(
            json.contains("\"type\":\"control.interrupt.request\""),
            "msg_type field missing from control payload"
        );

        // The interrupt signal.
        assert!(json.contains("\"interrupt\""), "interrupt signal missing");
    }
}