triaged 0.2.0

Long-running daemon that owns Triage terminal session state and serves a built-in web client and WebSocket API for PIN-paired remote attach.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
#![cfg_attr(
    windows,
    allow(dead_code, clippy::needless_return, clippy::large_enum_variant)
)]
use std::collections::{HashMap, HashSet, VecDeque};
use std::ffi::{OsStr, OsString};
use std::fs;
use std::fs::{File, OpenOptions};
use std::io::{ErrorKind, Read, Seek, SeekFrom, Write};
#[cfg(unix)]
use std::os::unix::ffi::OsStringExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::RwLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{
    self, Receiver, RecvTimeoutError, Sender, SyncSender, TryRecvError, TrySendError,
};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, anyhow, bail, ensure};
use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system};
use serde::{Deserialize, Serialize};
use tattoy_wezterm_term::color::{ColorAttribute, ColorPalette, SrgbaTuple};
use tattoy_wezterm_term::{Intensity, Terminal, TerminalConfiguration, TerminalSize, Underline};
use triage_core::session::{
    AttachSessionRequest, AttachSessionResponse, ClientId, CompletedSession, InputLeaseRequest,
    InputLeaseState, LeaseChange, ResizeSessionRequest, RestoreSessionRequest, SessionApi,
    SessionContext, SessionContextRow, SessionEvent, SessionEventEnvelope, SessionEventReceiver,
    SessionId, SessionSize, SessionSnapshot, StartSessionRequest, StyledRow, StyledRowsRequest,
    StyledRowsResponse, StyledSpan, SubscribeSessionEventsRequest, TerminalColor, TerminalCursor,
    TerminalStyle, WriteInputRequest,
};
use triage_transport_ws::ServerMessage;
use unicode_width::UnicodeWidthStr;

use crate::summarizer::{SnippetResult, SummarizeJob, Summarizer, build_prompt_text};

const EVENT_SUBSCRIBER_BUFFER: usize = 64;
const EVENT_REPLAY_BUFFER: usize = 1024;
const MAX_OSC_BUFFER: usize = 4096;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionConfig {
    pub command: String,
    pub args: Vec<String>,
    pub cwd: Option<PathBuf>,
    pub size: SessionSize,
    pub log_path: PathBuf,
}

impl SessionConfig {
    pub fn new(command: impl Into<String>, log_path: impl Into<PathBuf>) -> Self {
        Self {
            command: command.into(),
            args: Vec::new(),
            cwd: None,
            size: SessionSize::default(),
            log_path: log_path.into(),
        }
    }

    fn validate(&self) -> Result<()> {
        ensure!(
            !self.command.trim().is_empty(),
            "session command must be set"
        );
        self.size.validate()
    }
}

#[derive(Debug)]
struct TriageTerminalConfig;

impl TerminalConfiguration for TriageTerminalConfig {
    fn color_palette(&self) -> ColorPalette {
        ColorPalette::default()
    }
}

pub struct PtySession {
    _master: Box<dyn MasterPty + Send>,
    child: Box<dyn Child + Send + Sync>,
    reader: Box<dyn Read + Send>,
    _writer: SharedPtyWriter,
    output: OutputState,
}

pub struct SessionActor {
    tx: Sender<ActorCommand>,
    worker: Option<JoinHandle<()>>,
    reader: Option<JoinHandle<()>>,
    /// Wall-clock of this session's most recent PTY output, as milliseconds since
    /// the Unix epoch, shared with the actor's [`ActorState`].
    ///
    /// Deliberately an atomic rather than actor state read over [`Self::tx`]: the
    /// rail orders every session by activity, so listing them would otherwise
    /// cost one actor round-trip per session on a path that runs at every client
    /// connect. This is a lock-free load instead, and it stays readable while the
    /// actor is busy serving a long output burst, exactly when a round-trip
    /// would be slowest. `Relaxed` throughout: the value is a display-ordering
    /// hint that races with output by nature, and it guards no other memory.
    last_activity_ms: Arc<AtomicU64>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionManagerConfig {
    pub log_dir: PathBuf,
}

impl SessionManagerConfig {
    pub fn new(log_dir: impl Into<PathBuf>) -> Self {
        Self {
            log_dir: log_dir.into(),
        }
    }

    fn manifest_path(&self) -> PathBuf {
        self.log_dir.join("sessions.json")
    }
}

/// Crockford Base32 alphabet (RFC 4648 variant): excludes I, L, O, U to reduce typos.
const CROCKFORD_BASE32_ALPHABET: &[u8] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
const PAIRING_CODE_LENGTH: usize = 8;
const PAIRING_DEVICE_CODE_TTL: Duration = Duration::from_secs(15 * 60);
const PAIRING_PIN_TTL: Duration = Duration::from_secs(5 * 60);
const MAX_PENDING_PAIRING_CHALLENGES: usize = 64;
const MAX_PAIRING_CLIENT_ID_LENGTH: usize = 128;

/// Normalize a user-typed pairing code per Crockford Base32 rules:
/// strip whitespace, uppercase, and map ambiguous characters (I/L → 1, O → 0).
fn normalize_pairing_code(input: &str) -> String {
    input
        .chars()
        .filter(|c| !c.is_whitespace())
        .map(|c| match c.to_ascii_uppercase() {
            'I' | 'L' => '1',
            'O' => '0',
            other => other,
        })
        .collect()
}

fn unix_timestamp_secs() -> Result<u64> {
    Ok(std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)?
        .as_secs())
}

/// Wall-clock milliseconds since the Unix epoch, for session activity stamps.
///
/// Infallible by design, unlike [`unix_timestamp_secs`]: this runs on the actor's
/// hot output path, where the only failure mode (a system clock set before
/// 1970) must not cost a session its activity stamp. Such a clock yields 0,
/// which the rail already treats as "activity unknown" and orders last.
fn now_unix_millis() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
        .unwrap_or(0)
}

fn random_pairing_code() -> String {
    use rand::Rng;

    let mut rng = rand::thread_rng();
    (0..PAIRING_CODE_LENGTH)
        .map(|_| {
            let idx = rng.gen_range(0..CROCKFORD_BASE32_ALPHABET.len());
            CROCKFORD_BASE32_ALPHABET[idx] as char
        })
        .collect()
}

fn unique_pairing_code(challenges: &HashMap<String, PendingPairingChallenge>) -> String {
    loop {
        let code = random_pairing_code();
        if !challenges.contains_key(&code) {
            return code;
        }
    }
}

fn unique_pairing_pin(challenges: &HashMap<String, PendingPairingChallenge>) -> String {
    loop {
        let code = random_pairing_code();
        let in_use = challenges
            .values()
            .filter_map(|challenge| challenge.pin.as_ref())
            .any(|pin| pin.code == code);
        if !in_use {
            return code;
        }
    }
}

fn prune_expired_pairing_challenges(
    challenges: &mut HashMap<String, PendingPairingChallenge>,
    now: Instant,
) {
    challenges.retain(|_, challenge| {
        if challenge.expires_at <= now {
            return false;
        }
        if challenge
            .pin
            .as_ref()
            .is_some_and(|pin| pin.expires_at <= now)
        {
            challenge.pin = None;
        }
        true
    });
}

fn evict_oldest_unapproved_pairing_challenge(
    challenges: &mut HashMap<String, PendingPairingChallenge>,
) -> bool {
    let device_code = challenges
        .iter()
        .filter(|(_, challenge)| challenge.pin.is_none())
        .min_by_key(|(_, challenge)| challenge.expires_at)
        .map(|(device_code, _)| device_code.clone());

    if let Some(device_code) = device_code {
        challenges.remove(&device_code);
        return true;
    }

    false
}

pub struct SessionManager {
    config: SessionManagerConfig,
    next_session: AtomicU64,
    sessions: Mutex<HashMap<SessionId, ManagedSession>>,
    pairing_challenges: Mutex<HashMap<String, PendingPairingChallenge>>,
    paired_devices: Mutex<HashMap<ClientId, String>>,
    require_pairing: bool,
    /// Latest generated snippet per session (in-memory only; not persisted).
    snippets: Mutex<HashMap<SessionId, SessionSnippet>>,
    /// The local-LLM summarizer worker. Disabled until `start_summarizer` runs.
    summarizer: Mutex<crate::summarizer::Summarizer>,
    /// Sender handed to session actors so they report output activity to the
    /// debounce loop. `None` until `start_summarizer` runs.
    dirty_tx: Mutex<Option<DirtySender>>,
    /// Per-connection push channels for connection-wide broadcasts (snippet and
    /// context updates). Senders are pruned when their client disconnects. Held
    /// behind an `Arc` so live session actors can broadcast context changes
    /// directly (see [`GlobalSenders`] and `ActorState::global_senders`) without
    /// routing through the manager.
    global_senders: GlobalSenders,
    /// Latest result of the background update check (Phase 1 of self-update).
    /// Read into every `Hello` handshake; a poll that flips it to
    /// `update_available` also pushes a connection-wide notice. Starts as the
    /// running version with no `latest` until the first poll completes.
    update_status: Arc<RwLock<crate::update::UpdateStatus>>,
    /// Sender handed to session actors so they report working-directory changes
    /// to the cwd-persistence thread, which records the live cwd into the
    /// on-disk manifest. Unlike [`Self::dirty_tx`] this is wired up
    /// unconditionally (`start_cwd_persistence`), independent of the summarizer,
    /// so a daemon kill can restore a session into the directory it was last in.
    /// `None` until `start_cwd_persistence` runs (e.g. in tests).
    cwd_update_tx: Mutex<Option<CwdUpdateSender>>,
    /// Set while this daemon is serving a handover. It enforces one handover at a
    /// time and, critically, blocks `start_session`: a session created after the
    /// outgoing daemon snapshotted its set would not be among the transferred
    /// descriptors and would be lost when that daemon detaches and exits. Set and
    /// cleared through [`SessionManager::begin_handover`].
    handover_in_flight: AtomicBool,
    /// Guards [`Self::start_activity_persistence`] so a second call cannot spawn a
    /// second flush thread, both racing to rewrite the same manifest.
    activity_persistence_started: AtomicBool,
}

/// Channel an actor uses to report a working-directory change to the manager's
/// cwd-persistence thread: `(session_id, new_cwd)`.
type CwdUpdateSender = std::sync::mpsc::Sender<(SessionId, PathBuf)>;

/// Shared list of per-connection global push channels. Cloned (cheaply, by
/// `Arc`) into managed session actors so they can broadcast context updates as a
/// session's working directory changes.
type GlobalSenders = Arc<Mutex<Vec<SyncSender<ServerMessage>>>>;

/// Broadcasts a message to every connected client, pruning dead channels. Shared
/// by [`SessionManager::broadcast_global`] and the live session actors (which
/// hold a clone of the same [`GlobalSenders`]).
///
/// Returns `true` if the message reached every live client, or `false` if at
/// least one client's channel was full and the message was dropped for it. For
/// snippet updates a dropped message is harmless (the next regeneration
/// resends), but context updates are only emitted on change, so the caller uses
/// this to schedule a resend (see [`ActorState::broadcast_context_update`]).
fn broadcast_to_global_senders(senders: &GlobalSenders, message: ServerMessage) -> bool {
    let Ok(mut senders) = senders.lock() else {
        // Can't reach any sender; nothing a resend could fix, so don't loop on it.
        return true;
    };
    let mut delivered_to_all = true;
    senders.retain(|sender| match sender.try_send(message.clone()) {
        Ok(()) => true,
        // Full: client is slow; keep it, but report the drop so the caller can
        // resend (context updates won't otherwise be re-emitted).
        Err(TrySendError::Full(_)) => {
            delivered_to_all = false;
            true
        }
        Err(TrySendError::Disconnected(_)) => false,
    });
    delivered_to_all
}

/// A session's most recent snippet plus the output sequence it was generated at,
/// used to drop out-of-order worker results.
#[derive(Debug, Clone)]
struct SessionSnippet {
    text: String,
    /// Longer-form summary for the hover popover / search. `None` until the
    /// detail pass produces something usable.
    detail: Option<String>,
    generated_at_output_seq: u64,
}

/// Bounded capacity for each connection's global-push channel. If a client
/// can't keep up, snippet updates are dropped (the next regeneration resends).
const GLOBAL_PUSH_CHANNEL_CAPACITY: usize = 256;

#[derive(Debug, Clone)]
pub struct PairingChallengeInfo {
    pub device_code: String,
    pub expires_at: u64,
}

#[derive(Debug, Clone)]
pub struct PairingPinInfo {
    pub pin: String,
    pub expires_at: u64,
    pub client_id: ClientId,
}

#[derive(Debug, Clone)]
struct PendingPairingChallenge {
    client_id: ClientId,
    expires_at: Instant,
    expires_at_unix: u64,
    pin: Option<PendingPairingPin>,
}

#[derive(Debug, Clone)]
struct PendingPairingPin {
    code: String,
    expires_at: Instant,
}

// The `Live` variant intentionally carries the live actor plus its launch
// metadata and last-known cwd for the session's whole lifetime; only a handful
// of these are ever held (one per session) and they coexist with `Historical`,
// so boxing fields to shrink the variant difference would add indirection for no
// real memory win.
#[allow(clippy::large_enum_variant)]
enum ManagedSession {
    Live {
        actor: SessionActor,
        lease: InputLeaseState,
        launch: PersistedSessionLaunch,
        /// The session's most recently observed working directory, kept fresh by
        /// the actor (via the cwd-update channel). Persisted into the manifest so
        /// a daemon kill restores the session here rather than at its launch dir.
        /// Seeded from the launch/restored cwd; `None` until first known.
        last_known_cwd: Option<PathBuf>,
    },
    Historical {
        session: Box<HistoricalSession>,
        lease: InputLeaseState,
    },
    Restoring {
        session: Box<HistoricalSession>,
        lease: InputLeaseState,
    },
}

struct HistoricalSession {
    persisted: PersistedSession,
    output: OutputState,
    size: SessionSize,
    current_working_directory: Option<PathBuf>,
    context: Option<SessionContext>,
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct SessionManifest {
    version: u32,
    sessions: Vec<PersistedSession>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct PersistedSession {
    id: SessionId,
    command: String,
    args: Vec<String>,
    cwd: Option<PathBuf>,
    size: SessionSize,
    log_path: PathBuf,
    exited: bool,
    /// The session's last observed live working directory, tracked while it ran
    /// and recorded here so a daemon kill restores it into that directory rather
    /// than its launch dir. `cwd` above is the *launch* directory and never
    /// changes; this follows the shell. Defaults to `None` for manifests written
    /// before this field existed.
    #[serde(default)]
    last_known_cwd: Option<PathBuf>,
    /// Wall-clock of the session's most recent output, as milliseconds since the
    /// Unix epoch, so a daemon restart restores each session's real recency for
    /// the client rail's activity ordering. 0 means "unknown": either a manifest
    /// written before this field existed, or a session that has never produced
    /// output, and the rail orders those last rather than treating them as
    /// epoch-old.
    ///
    /// For a live session this is refreshed from the actor on every manifest
    /// write (see [`ManagedSession::persisted`]) rather than being pushed on each
    /// output, which would rewrite the manifest continuously under a build.
    #[serde(default)]
    last_activity_ms: u64,
}

#[derive(Debug, Clone)]
struct PersistedSessionLaunch {
    command: String,
    args: Vec<String>,
    cwd: Option<PathBuf>,
    size: SessionSize,
    log_path: PathBuf,
}

impl From<&SessionConfig> for PersistedSessionLaunch {
    fn from(config: &SessionConfig) -> Self {
        Self {
            command: config.command.clone(),
            args: config.args.clone(),
            cwd: config.cwd.clone(),
            size: config.size.clone(),
            log_path: config.log_path.clone(),
        }
    }
}

impl PersistedSessionLaunch {
    fn into_persisted(self, id: SessionId, exited: bool) -> PersistedSession {
        PersistedSession {
            id,
            command: self.command,
            args: self.args,
            cwd: self.cwd,
            size: self.size,
            log_path: self.log_path,
            exited,
            last_known_cwd: None,
            // Filled in by `ManagedSession::persisted` for live sessions, which
            // is the only caller with access to the actor's activity stamp.
            last_activity_ms: 0,
        }
    }
}

impl SessionManager {
    pub fn new(config: SessionManagerConfig) -> Self {
        let sessions = restore_sessions(&config).unwrap_or_else(|error| {
            tracing::warn!(error = ?error, "failed to restore persisted sessions");
            HashMap::new()
        });
        let next_session = next_session_sequence(sessions.keys());
        let paired_devices = load_paired_devices(&config.log_dir);
        let require_pairing = if let Ok(path) = triage_core::config::Config::default_path() {
            if path.exists() {
                triage_core::config::Config::load_from_path(&path)
                    .map(|c| c.remote.require_pairing)
                    .unwrap_or(true)
            } else {
                true
            }
        } else {
            true
        };
        Self {
            config,
            next_session: AtomicU64::new(next_session),
            sessions: Mutex::new(sessions),
            pairing_challenges: Mutex::new(HashMap::new()),
            paired_devices: Mutex::new(paired_devices),
            require_pairing,
            snippets: Mutex::new(HashMap::new()),
            summarizer: Mutex::new(Summarizer::disabled()),
            dirty_tx: Mutex::new(None),
            global_senders: Arc::new(Mutex::new(Vec::new())),
            update_status: Arc::new(RwLock::new(crate::update::UpdateStatus::current())),
            cwd_update_tx: Mutex::new(None),
            handover_in_flight: AtomicBool::new(false),
            activity_persistence_started: AtomicBool::new(false),
        }
    }

    /// Claim the handover slot for the caller. Returns `None` when a handover is
    /// already in flight, so the caller can refuse a concurrent one. While the
    /// returned guard lives, [`SessionApi::start_session`] is refused. Cleared on
    /// drop — a handover that fails before committing leaves the daemon able to
    /// serve a later one and to start sessions again.
    pub fn begin_handover(&self) -> Option<HandoverGuard<'_>> {
        self.handover_in_flight
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
            .ok()
            .map(|_| HandoverGuard { manager: self })
    }

    fn allocate_session_id(&self) -> Result<SessionId> {
        let sequence = self.next_session.fetch_add(1, Ordering::Relaxed);
        SessionId::new(format!("session-{sequence}"))
    }

    /// Clones the dirty-activity sender handed to new session actors. `None`
    /// until the summarizer is started (or if it is disabled).
    fn dirty_tx(&self) -> Option<DirtySender> {
        self.dirty_tx.lock().ok().and_then(|guard| guard.clone())
    }

    /// Clones the cwd-update sender handed to new session actors. `None` until
    /// `start_cwd_persistence` runs (e.g. in tests that never start it).
    fn cwd_update_tx(&self) -> Option<CwdUpdateSender> {
        self.cwd_update_tx
            .lock()
            .ok()
            .and_then(|guard| guard.clone())
    }

    /// Spawns the cwd-persistence thread: it records each live session's
    /// working directory into the on-disk manifest as it changes, so a daemon
    /// kill (which also kills the child shells) can restore a session into the
    /// directory it was last in rather than the launch dir / `~`. Wired up
    /// unconditionally at startup, independent of the summarizer.
    ///
    /// Updates are coalesced over `CWD_PERSIST_SETTLE` so a burst of `cd`s
    /// collapses into a single manifest rewrite rather than one per directory —
    /// mirroring the summarizer's `run_debounce_loop`. Idempotent: a second call
    /// is a no-op (it does not spawn a second thread or swap the sender), so live
    /// actors that captured the original sender keep reporting to the one loop.
    pub fn start_cwd_persistence(self: &Arc<Self>) {
        let rx = {
            let Ok(mut guard) = self.cwd_update_tx.lock() else {
                return;
            };
            if guard.is_some() {
                return; // already started
            }
            let (tx, rx) = mpsc::channel::<(SessionId, PathBuf)>();
            *guard = Some(tx);
            rx
        };
        let weak = Arc::downgrade(self);
        if let Err(error) = thread::Builder::new()
            .name("triage-cwd-persistence".into())
            .spawn(move || run_cwd_persistence_loop(weak, rx))
        {
            tracing::error!(%error, "failed to spawn cwd-persistence thread");
            // Roll back so a retry can spawn the thread rather than seeing a
            // sender with no loop draining it.
            if let Ok(mut guard) = self.cwd_update_tx.lock() {
                *guard = None;
            }
        }
    }

    /// Starts the periodic activity-stamp flush (see
    /// `run_activity_persistence_loop`) so the client rail's activity ordering
    /// survives an ungraceful daemon kill. Wired up unconditionally at startup,
    /// independent of the summarizer. Idempotent: a second call is a no-op.
    pub fn start_activity_persistence(self: &Arc<Self>) {
        if self
            .activity_persistence_started
            .swap(true, Ordering::AcqRel)
        {
            return; // already started
        }
        let weak = Arc::downgrade(self);
        if let Err(error) = thread::Builder::new()
            .name("triage-activity-persistence".into())
            .spawn(move || run_activity_persistence_loop(weak))
        {
            tracing::error!(%error, "failed to spawn activity-persistence thread");
            // Roll back so a retry can spawn the thread.
            self.activity_persistence_started
                .store(false, Ordering::Release);
        }
    }

    /// Applies a coalesced batch of working-directory updates and persists the
    /// manifest at most once. No-op unless at least one live session's cwd
    /// actually changed. Holds the global `sessions` lock across the manifest
    /// write (like the lifecycle persisters); the debounce keeps this to roughly
    /// one write per [`CWD_PERSIST_SETTLE`] even under a `cd` storm.
    fn flush_cwd_updates(&self, updates: HashMap<SessionId, PathBuf>) {
        if updates.is_empty() {
            return;
        }
        let Ok(mut sessions) = self.sessions() else {
            return;
        };
        let mut changed = false;
        for (session_id, cwd) in updates {
            if let Some(ManagedSession::Live { last_known_cwd, .. }) = sessions.get_mut(&session_id)
                && last_known_cwd.as_deref() != Some(cwd.as_path())
            {
                *last_known_cwd = Some(cwd);
                changed = true;
            }
        }
        if !changed {
            return;
        }
        if let Err(error) = self.persist_manifest(&sessions) {
            tracing::warn!(error = ?error, "failed to persist live cwd updates");
        }
    }

    /// Cheap visible-rows snapshot for the summarizer. Clones the live actor's
    /// command channel under a brief lock, then does the round-trip OFF-LOCK so
    /// it never holds the global `sessions` mutex during actor I/O (which would
    /// starve interactive session operations). Returns `None` for
    /// non-live/missing sessions.
    fn summary_rows(&self, session_id: &SessionId) -> Option<SummaryRowsResponse> {
        let cmd_tx = {
            let sessions = self.sessions().ok()?;
            match sessions.get(session_id) {
                Some(ManagedSession::Live { actor, .. }) => actor.tx.clone(),
                _ => return None,
            }
        };
        request_summary_rows(&cmd_tx).ok()
    }

    /// Current snippet (one-liner, detail) for a session, if one has been
    /// generated. Returns `(None, None)` when no snippet exists.
    fn snippet_for(&self, session_id: &SessionId) -> (Option<String>, Option<String>) {
        let Ok(snippets) = self.snippets.lock() else {
            return (None, None);
        };
        match snippets.get(session_id) {
            Some(snippet) => (Some(snippet.text.clone()), snippet.detail.clone()),
            None => (None, None),
        }
    }

    /// Overlays the cached snippet onto a snapshot before it is returned to a
    /// client. The actor builds snapshots without snippet (it has no cache).
    fn overlay_snippet(
        &self,
        mut snapshot: SessionSnapshot,
        session_id: &SessionId,
    ) -> SessionSnapshot {
        let (snippet, detail) = self.snippet_for(session_id);
        snapshot.snippet = snippet;
        snapshot.snippet_detail = detail;
        snapshot
    }

    /// Registers a connection-wide push channel. The returned receiver is
    /// drained by the WebSocket connection alongside its subscription events.
    pub fn register_global_receiver(&self) -> Receiver<ServerMessage> {
        let (tx, rx) = mpsc::sync_channel(GLOBAL_PUSH_CHANNEL_CAPACITY);
        if let Ok(mut senders) = self.global_senders.lock() {
            senders.push(tx);
        }
        rx
    }

    /// Broadcasts a message to every connected client, pruning dead channels.
    fn broadcast_global(&self, message: ServerMessage) {
        // Snippet broadcasts tolerate a dropped send (the next regeneration
        // resends), so the delivery result is intentionally ignored here.
        let _ = broadcast_to_global_senders(&self.global_senders, message);
    }

    /// Snapshot of the latest update check, embedded into the `Hello` handshake
    /// so every client learns the server version and whether a newer release
    /// exists. Falls back to the running version if the lock is poisoned.
    pub fn update_status(&self) -> crate::update::UpdateStatus {
        self.update_status
            .read()
            .map(|status| status.clone())
            .unwrap_or_else(|_| crate::update::UpdateStatus::current())
    }

    /// Overwrite the stored update status. Test-only: the poller is the sole
    /// production writer, but tests need to seed a known "update available"
    /// state without a network round-trip.
    #[cfg(test)]
    pub(crate) fn set_update_status_for_test(&self, status: crate::update::UpdateStatus) {
        *self.update_status.write().expect("update status lock") = status;
    }

    /// Starts the background update poller (Phase 1 of self-update). No-op when
    /// `[update] check` is false. When a poll first observes a newer release,
    /// the result is stored (for future handshakes) and pushed to every
    /// connected client as a connection-wide notice. Safe to call once at
    /// startup.
    pub fn start_update_poller(self: &Arc<Self>, config: triage_core::config::UpdateConfig) {
        let status = Arc::clone(&self.update_status);
        let weak = Arc::downgrade(self);
        crate::update::spawn_poller(config, status, move |new_status| {
            if let Some(manager) = weak.upgrade() {
                manager.broadcast_update_available(new_status);
            }
        });
    }

    /// Pushes an "update available" notice to every connected client. Only
    /// called on the transition into the available state, so a single dropped
    /// send is acceptable — the value also rides the next `Hello` handshake.
    fn broadcast_update_available(&self, status: &crate::update::UpdateStatus) {
        if let Some(latest) = &status.latest {
            self.broadcast_global(ServerMessage::UpdateAvailable {
                current_version: status.current.clone(),
                latest_version: latest.clone(),
            });
        }
    }

    /// Clones the shared global-sender list handed to live session actors so they
    /// can broadcast context updates as their working directory changes.
    fn global_senders(&self) -> GlobalSenders {
        Arc::clone(&self.global_senders)
    }

    /// Records a freshly generated snippet (newest `output_seq` wins) and pushes
    /// the update to all connected clients. Called on the summarizer worker thread.
    fn apply_snippet(&self, result: SnippetResult) {
        {
            let Ok(mut snippets) = self.snippets.lock() else {
                return;
            };
            match snippets.get(&result.session_id) {
                Some(existing)
                    if existing.generated_at_output_seq > result.generated_at_output_seq => {}
                _ => {
                    snippets.insert(
                        result.session_id.clone(),
                        SessionSnippet {
                            text: result.text.clone(),
                            detail: result.detail.clone(),
                            generated_at_output_seq: result.generated_at_output_seq,
                        },
                    );
                }
            }
        }
        tracing::debug!(
            session_id = %result.session_id,
            output_seq = result.generated_at_output_seq,
            text = %result.text,
            "cached + broadcasting session snippet"
        );
        self.broadcast_global(ServerMessage::SessionSnippetUpdated {
            session_id: result.session_id,
            snippet: result.text,
            detail: result.detail,
            output_seq: result.generated_at_output_seq,
        });
    }

    /// Drops a session's cached snippet (on shutdown/removal).
    fn forget_snippet(&self, session_id: &SessionId) {
        if let Ok(mut snippets) = self.snippets.lock() {
            snippets.remove(session_id);
        }
    }

    /// Starts the local-LLM summarizer: loads the model lazily on a worker
    /// thread, wires session activity into a debounce loop, and pushes generated
    /// snippets to clients. No-op when disabled. Safe to call once at startup.
    pub fn start_summarizer(self: &Arc<Self>, config: triage_core::config::SummarizerConfig) {
        if !config.enabled {
            return;
        }
        let cache_dir = config
            .cache_dir
            .clone()
            .map(PathBuf::from)
            .unwrap_or_else(default_model_cache_dir);
        let worker_config = crate::summarizer::SummarizerConfig {
            bundle_id: config.bundle_id.clone(),
            quant: config.quant.clone(),
            context_size: config.context_size,
            max_tokens: config.max_tokens,
            detail_max_tokens: config.detail_max_tokens,
            cache_dir,
            queue_depth: 8,
        };

        let on_result = {
            let weak = Arc::downgrade(self);
            move |result: SnippetResult| {
                if let Some(manager) = weak.upgrade() {
                    manager.apply_snippet(result);
                }
            }
        };
        let summarizer = Summarizer::spawn(worker_config, on_result);
        if !summarizer.is_enabled() {
            return;
        }

        let (dirty_tx, dirty_rx) = mpsc::channel::<DirtyTick>();
        if let Ok(mut guard) = self.dirty_tx.lock() {
            *guard = Some(dirty_tx);
        }
        if let Ok(mut guard) = self.summarizer.lock() {
            *guard = summarizer.clone();
        }

        let weak = Arc::downgrade(self);
        let settle = Duration::from_millis(config.settle_ms);
        let min_regen = Duration::from_millis(config.min_regen_ms);
        let loop_summarizer = summarizer.clone();
        if let Err(error) = thread::Builder::new()
            .name("triage-summarizer-debounce".into())
            .spawn(move || {
                run_debounce_loop(weak, loop_summarizer, dirty_rx, settle, min_regen);
            })
        {
            tracing::error!(%error, "failed to spawn summarizer debounce thread");
            return;
        }

        // Seed any sessions that already exist at this point. On a fresh start
        // there are none; on handover, adoption runs *after* this, so callers
        // must also invoke `seed_session_snippets` post-adoption.
        self.seed_initial_summaries(&summarizer);
    }

    /// Re-runs the initial seed against the current live sessions. Call this
    /// after handover adoption so adopted (possibly idle) sessions get a snippet
    /// without waiting for new output. No-op when the summarizer is disabled.
    pub fn seed_session_snippets(&self) {
        let summarizer = match self.summarizer.lock() {
            Ok(guard) => guard.clone(),
            Err(_) => return,
        };
        if summarizer.is_enabled() {
            self.seed_initial_summaries(&summarizer);
        }
    }

    /// Enqueues a one-shot summary for every currently-live session.
    fn seed_initial_summaries(&self, summarizer: &Summarizer) {
        let session_ids = match self.list_sessions() {
            Ok(ids) => ids,
            Err(_) => return,
        };
        let total = session_ids.len();
        let mut enqueued = 0usize;
        let mut skipped_blank = 0usize;
        for session_id in session_ids {
            if let Some((rows, output_seq, context)) = self.summary_rows(&session_id) {
                if let Some(prompt_text) = build_prompt_text(&rows) {
                    if summarizer.try_enqueue(SummarizeJob {
                        session_id,
                        prompt_text,
                        output_seq,
                        context,
                    }) {
                        enqueued += 1;
                    }
                } else {
                    skipped_blank += 1;
                }
            }
        }
        tracing::debug!(total, enqueued, skipped_blank, "seeded session snippets");
    }

    fn log_path(&self, session_id: &SessionId) -> PathBuf {
        self.config.log_dir.join(format!("{session_id}.log"))
    }

    /// Reclaims session logs that nothing refers to any more.
    ///
    /// Deliberately *not* run from `restore_sessions`. At manifest-load time the
    /// picture is incomplete: sessions adopted across a handover join the map
    /// afterwards, so a live-but-idle session's log — one untouched for longer
    /// than the retention window, which a shell sitting at a prompt manages
    /// easily — could be deleted moments before its session was adopted. The
    /// daemon calls this once startup has settled instead.
    ///
    /// A log is referenced if *either* a session in the map points at it or the
    /// on-disk manifest does. The union matters in both directions: the map
    /// misses sessions whose `HistoricalSession::restore` failed (warn-skipped,
    /// but still listed in the manifest and still recoverable), and the manifest
    /// misses anything adopted since it was last written.
    pub fn purge_orphaned_logs(&self) {
        self.purge_orphaned_logs_with_retention(ORPHANED_LOG_RETENTION);
    }

    /// [`Self::purge_orphaned_logs`] with an explicit grace period, so tests can
    /// drive the real union without backdating file mtimes.
    fn purge_orphaned_logs_with_retention(&self, retention: std::time::Duration) {
        let Ok(sessions) = self.sessions() else {
            tracing::warn!("session lock poisoned; skipping orphaned log purge");
            return;
        };
        let mut referenced: HashSet<PathBuf> = sessions
            .values()
            .map(|session| match session {
                ManagedSession::Live { launch, .. } => launch.log_path.clone(),
                ManagedSession::Historical { session, .. }
                | ManagedSession::Restoring { session, .. } => session.persisted.log_path.clone(),
            })
            .collect();
        drop(sessions);

        let manifest_path = self.config.manifest_path();
        if manifest_path.exists() {
            let manifest = fs::read(&manifest_path)
                .context("reading session manifest")
                .and_then(|bytes| {
                    serde_json::from_slice::<SessionManifest>(&bytes)
                        .context("decoding session manifest")
                });
            match manifest {
                Ok(manifest) => {
                    referenced.extend(manifest.sessions.into_iter().map(|s| s.log_path));
                }
                Err(error) => {
                    // Without the manifest half of the union, a failed-restore
                    // session's log looks orphaned. Skip rather than guess.
                    tracing::warn!(
                        manifest_path = %manifest_path.display(),
                        ?error,
                        "could not read session manifest; skipping orphaned log purge"
                    );
                    return;
                }
            }
        }

        purge_orphaned_session_logs(&self.config.log_dir, &referenced, retention);
    }

    fn sessions(&self) -> Result<std::sync::MutexGuard<'_, HashMap<SessionId, ManagedSession>>> {
        self.sessions
            .lock()
            .map_err(|_| anyhow!("session manager lock poisoned"))
    }

    fn pairing_challenges(
        &self,
    ) -> Result<std::sync::MutexGuard<'_, HashMap<String, PendingPairingChallenge>>> {
        self.pairing_challenges
            .lock()
            .map_err(|_| anyhow!("pairing challenges lock poisoned"))
    }

    fn paired_devices(&self) -> Result<std::sync::MutexGuard<'_, HashMap<ClientId, String>>> {
        self.paired_devices
            .lock()
            .map_err(|_| anyhow!("paired devices lock poisoned"))
    }

    fn persist_manifest(&self, sessions: &HashMap<SessionId, ManagedSession>) -> Result<()> {
        fs::create_dir_all(&self.config.log_dir).with_context(|| {
            format!("creating session log dir {}", self.config.log_dir.display())
        })?;
        let mut persisted_sessions = sessions
            .iter()
            .map(|(session_id, session)| session.persisted(session_id.clone()))
            .collect::<Vec<_>>();
        persisted_sessions.sort_by(|left, right| left.id.as_str().cmp(right.id.as_str()));
        let manifest = SessionManifest {
            version: 1,
            sessions: persisted_sessions,
        };
        let manifest_path = self.config.manifest_path();
        let temp_path = manifest_path.with_extension("json.tmp");
        let json = serde_json::to_vec_pretty(&manifest).context("encoding session manifest")?;
        fs::write(&temp_path, json)
            .with_context(|| format!("writing session manifest {}", temp_path.display()))?;
        replace_manifest(&temp_path, &manifest_path)?;
        Ok(())
    }

    fn rollback_restoring_session(&self, session_id: SessionId) -> Result<()> {
        let mut sessions = self.sessions()?;
        let session = sessions
            .remove(&session_id)
            .with_context(|| format!("session {session_id} not found"))?;
        let ManagedSession::Restoring { session, lease } = session else {
            sessions.insert(session_id.clone(), session);
            bail!("session {session_id} is not being restored");
        };
        sessions.insert(session_id, ManagedSession::Historical { session, lease });
        Ok(())
    }

    /// Converts a `Live` session whose child process has already exited into a
    /// `Historical` session in place, so it can be restored. Nothing else moves
    /// a dead `Live` session to `Historical` (that only happens on a daemon
    /// restart via the manifest), so without this a session that dies while live
    /// — notably one adopted across a handover — can never be re-spawned.
    ///
    /// Returns `Ok(())` when the session is left unchanged (still running, not
    /// `Live`, or not a restorable shell) or successfully demoted; returns `Err`
    /// only when the session is a confirmed-exited restorable `Live` whose log
    /// could not be rebuilt, so the caller can report the real cause instead of
    /// a misleading "already live".
    fn demote_dead_live_session(&self, session_id: &SessionId) -> Result<()> {
        // Phase 1 (brief lock): grab the actor command channel + launch of a
        // `Live` session, without doing the actor round-trip under the lock.
        let (cmd_tx, launch, last_known_cwd, last_activity_ms) = {
            let sessions = self.sessions()?;
            let Some(ManagedSession::Live {
                actor,
                launch,
                last_known_cwd,
                ..
            }) = sessions.get(session_id)
            else {
                return Ok(());
            };
            (
                actor.tx.clone(),
                launch.clone(),
                last_known_cwd.clone(),
                actor.last_activity_ms(),
            )
        };

        // Off-lock: only a cleanly-exited actor is a demote candidate. A snapshot
        // *error* means the worker thread is gone, so we cannot confirm the child
        // died — leave it rather than risk reaping a still-running child and
        // spawning a duplicate shell.
        if !matches!(request_snapshot(&cmd_tx), Ok(snapshot) if snapshot.exited) {
            return Ok(());
        }

        // Only restorable shells can be re-spawned; don't reap a non-restorable
        // session's actor and downgrade it for a restore that would bail anyway.
        let mut persisted = launch.into_persisted(session_id.clone(), true);
        // Preserve the live-tracked cwd across the demotion: `into_persisted`
        // only carries the launch dir, so without this an exit-then-restore would
        // overwrite the persisted cwd with `None` and re-spawn at the launch dir.
        persisted.last_known_cwd = last_known_cwd;
        // Carry the activity stamp across the demotion for the same reason as the
        // cwd: `into_persisted` builds from the launch config and zeroes it, so a
        // session that exits would be written to the manifest as "activity
        // unknown" and sort to the bottom of the rail despite having been busy
        // moments earlier.
        persisted.last_activity_ms = last_activity_ms;
        if !is_restorable_shell_launch(&persisted) {
            return Ok(());
        }

        // Off-lock: rebuild the historical view, which reads and replays the
        // session log — too slow to do while holding the global sessions lock.
        let historical = HistoricalSession::restore(persisted)
            .with_context(|| format!("rebuilding exited session {session_id} for restore"))?;

        // Phase 3 (brief lock): swap only if it is still a `Live` entry — a
        // concurrent restore may already have replaced it. A confirmed-exited
        // process cannot revive, so no second round-trip is needed here.
        let mut sessions = self.sessions()?;
        if !matches!(sessions.get(session_id), Some(ManagedSession::Live { .. })) {
            return Ok(());
        }
        if let Some(ManagedSession::Live { actor, lease, .. }) = sessions.remove(session_id) {
            if let Err(error) = actor.shutdown() {
                tracing::warn!(
                    session_id = %session_id,
                    ?error,
                    "failed to reap exited actor while demoting to historical"
                );
            }
            // The `Live` -> `Historical` transition is otherwise invisible: it
            // happens lazily on a restore request, so without this the map can
            // change shape with nothing in the log to explain it.
            tracing::info!(session_id = %session_id, "demoting exited live session for restore");

            sessions.insert(
                session_id.clone(),
                ManagedSession::Historical {
                    session: Box::new(historical),
                    lease,
                },
            );
            // Keep the on-disk manifest consistent with the in-memory swap, as
            // every other map-mutating path does.
            self.persist_manifest(&sessions)
                .with_context(|| format!("persisting manifest after demoting {session_id}"))?;
        }
        Ok(())
    }

    pub fn request_pairing_challenge(&self, client_id: &ClientId) -> Result<PairingChallengeInfo> {
        ensure!(
            client_id.as_str().len() <= MAX_PAIRING_CLIENT_ID_LENGTH,
            "pairing client id is too long"
        );

        let now = Instant::now();
        let now_unix = unix_timestamp_secs()?;
        let mut challenges = self.pairing_challenges()?;
        prune_expired_pairing_challenges(&mut challenges, now);

        if let Some((device_code, challenge)) = challenges
            .iter()
            .find(|(_, challenge)| &challenge.client_id == client_id)
        {
            return Ok(PairingChallengeInfo {
                device_code: device_code.clone(),
                expires_at: challenge.expires_at_unix,
            });
        }

        while challenges.len() >= MAX_PENDING_PAIRING_CHALLENGES {
            if !evict_oldest_unapproved_pairing_challenge(&mut challenges) {
                bail!("too many pending pairing challenges");
            }
        }

        let device_code = unique_pairing_code(&challenges);
        let expires_at_unix = now_unix + PAIRING_DEVICE_CODE_TTL.as_secs();
        challenges.insert(
            device_code.clone(),
            PendingPairingChallenge {
                client_id: client_id.clone(),
                expires_at: now + PAIRING_DEVICE_CODE_TTL,
                expires_at_unix,
                pin: None,
            },
        );

        tracing::info!(client_id = %client_id, "issued pairing device code");

        Ok(PairingChallengeInfo {
            device_code,
            expires_at: expires_at_unix,
        })
    }

    pub fn approve_pairing_device_code(&self, device_code: &str) -> Result<PairingPinInfo> {
        let normalized = normalize_pairing_code(device_code);
        let now = Instant::now();
        let now_unix = unix_timestamp_secs()?;
        let mut challenges = self.pairing_challenges()?;
        prune_expired_pairing_challenges(&mut challenges, now);

        let (pin_code, challenge_expires_at, challenge_expires_at_unix) = {
            let challenge = challenges
                .get(&normalized)
                .with_context(|| "invalid or expired pairing device code")?;

            if challenge.expires_at <= now {
                bail!("pairing device code has expired");
            }

            let pin_code = match &challenge.pin {
                Some(pin) if pin.expires_at > now => Some(pin.code.clone()),
                _ => None,
            };

            (pin_code, challenge.expires_at, challenge.expires_at_unix)
        };

        let pin_code = pin_code.unwrap_or_else(|| unique_pairing_pin(&challenges));
        let pin_expires_at = std::cmp::min(now + PAIRING_PIN_TTL, challenge_expires_at);
        let pin_expires_at_unix = std::cmp::min(
            now_unix + PAIRING_PIN_TTL.as_secs(),
            challenge_expires_at_unix,
        );
        let challenge = challenges
            .get_mut(&normalized)
            .with_context(|| "invalid or expired pairing device code")?;
        challenge.pin = Some(PendingPairingPin {
            code: pin_code.clone(),
            expires_at: pin_expires_at,
        });

        tracing::info!(client_id = %challenge.client_id, "issued pairing PIN for device code");

        Ok(PairingPinInfo {
            pin: pin_code,
            expires_at: pin_expires_at_unix,
            client_id: challenge.client_id.clone(),
        })
    }

    #[cfg(unix)]
    pub fn serialize_active_sessions(
        &self,
    ) -> Result<(
        crate::handover::HandoverState,
        Vec<std::os::unix::io::RawFd>,
    )> {
        let sessions = self.sessions()?;
        let mut handover_sessions = Vec::new();
        let mut fds = Vec::new();

        for (id, managed) in sessions.iter() {
            if let ManagedSession::Live {
                actor,
                lease: _,
                launch,
                // The adopted process stays alive across a handover, so the new
                // daemon reads its live cwd directly (see `adopted_session_cwd`);
                // no need to carry `last_known_cwd` through the handover state.
                last_known_cwd: _,
            } = managed
            {
                let (tx, rx) = mpsc::channel();
                if let Err(err) = actor
                    .tx
                    .send(ActorCommand::ExtractHandoverState { response: tx })
                {
                    tracing::warn!(session_id = %id, ?err, "Failed to send extract command to actor");
                    continue;
                }

                let ext = match rx.recv() {
                    Ok(Ok(ext)) => ext,
                    Ok(Err(err)) => {
                        tracing::warn!(session_id = %id, ?err, "Actor failed to extract handover state");
                        continue;
                    }
                    Err(err) => {
                        // Aborting the whole handover here is deliberate: a
                        // half-transferred set would silently drop the sessions we
                        // skipped. But the daemon survives this abort and can serve
                        // a later attempt, so the masters already duplicated for
                        // this attempt must be closed rather than left to
                        // accumulate across retries.
                        for fd in fds.drain(..) {
                            // Safety: each fd is a `dup` produced for this transfer
                            // and owned solely by this vector; nothing has been sent
                            // to a peer yet.
                            unsafe { libc::close(fd) };
                        }
                        return Err(err).context("waiting for extract response");
                    }
                };

                fds.push(ext.fd);

                handover_sessions.push(crate::handover::HandoverSession {
                    id: id.clone(),
                    command: launch.command.clone(),
                    args: launch.args.clone(),
                    cwd: launch.cwd.clone(),
                    size: launch.size.clone(),
                    log_path: launch.log_path.clone(),
                    output_seq: ext.output_seq,
                    bytes_logged: ext.bytes_logged,
                    pid: ext.pid,
                    last_activity_ms: actor.last_activity_ms(),
                });
            }
        }

        let state = crate::handover::HandoverState {
            sessions: handover_sessions,
            has_tcp_listener: false,
            // handle_handover_server sets this true once it takes over the wire
            // protocol; the manager itself makes no protocol promise.
            sends_teardown_commit: false,
        };

        Ok((state, fds))
    }

    /// Detaches every live session from this daemon for a process handover:
    /// removes them from the map and disarms their actors (no shutdown signal, no
    /// `child.kill()`) so the shared child processes survive into the successor
    /// daemon, which already holds their master fds.
    ///
    /// What becomes of each actor's threads afterwards is stated once, here,
    /// because it is easy to get wrong in the reassuring direction. Detaching
    /// gives up the right to *join* them; it is not what keeps them running, and
    /// neither is simply "alive until `process::exit`". They end in a chain:
    ///
    /// 1. `SessionActor::detach` takes the actor by value, dropping the stored
    ///    `Sender<ActorCommand>`. That is not necessarily the last one: three call
    ///    sites clone it and use the clone off-lock for a round-trip the actor
    ///    itself has to serve, so a clone in flight keeps the channel connected
    ///    for however long the actor takes to answer — which is not bounded by
    ///    anything this call controls. Once none is left, the worker's next poll of
    ///    `command_rx` (a `try_recv`, or the `recv_timeout` it switches to after
    ///    the child exits) sees the channel disconnected and returns. That drops `ActorState`, and with it this
    ///    process's PTY master. Nothing kills or reaps the child, which is the
    ///    point of the detach — but see the caveat below before reading that as
    ///    "the child is untouched".
    /// 2. That return also drops the output receiver, so the reader ends at its
    ///    next send. It reads through its own `dup`, so closing the master above
    ///    does not disturb it — which is exactly why it can still take a chunk
    ///    nobody receives: the one it was already parked in `send` with, or the
    ///    one it reads first. Only if that read reports EOF or an error does it
    ///    end having consumed nothing.
    ///
    /// Nothing sequences that chain against this call and nothing bounds it: the
    /// worker may be mid-iteration or waiting out a 20ms `output_rx` timeout, and
    /// a reader whose child is quiet is blocked in `read` indefinitely.
    /// `process::exit` routinely arrives before either step and reaps what is
    /// left, `dup`ed fds included. So the loop does not *depend* on the exit to
    /// end, but nothing guarantees it ended before one: assume this daemon can
    /// still take a destructive read from the successor at any point up to that
    /// exit, which is what [`crate::handover::HANDOVER_TEARDOWN_TIMEOUT`] is sized
    /// around.
    ///
    /// The caveat on step 1, stated carefully because it is a loaded gun that has
    /// so far refused to fire: for a session *this* daemon spawned, `ActorState`
    /// holds the last reference to portable-pty's master writer, and
    /// `UnixMasterWriter::Drop` writes `\n` plus `VEOF` to the tty. Written to a
    /// shell's tty that sequence submits any partially typed line and then ends
    /// the shell on the resulting empty one, which would destroy the session the
    /// handover exists to preserve.
    ///
    /// An attempt to reproduce that end to end did *not* kill the child: after a
    /// detach it stayed running, and injecting the same two bytes by hand at that
    /// moment did not end it either, though injecting them mid-session does. So
    /// the mechanism is real and the consequence is not demonstrated, and the
    /// reason is not understood. It is written down because the analysis that gets
    /// you to "the child is untouched" — nothing kills it, nothing reaps it — does
    /// not account for the writer at all, and that gap is worth more than the
    /// reassurance. Do not read step 1 as proof the child survives.
    ///
    /// Closing a live session's master here is safe;
    /// [`crate::handover::AdoptedMasterPty`] documents why.
    #[cfg(unix)]
    pub fn detach_all_live_sessions(&self) {
        if let Ok(mut sessions) = self.sessions() {
            for (_, managed) in sessions.drain() {
                if let ManagedSession::Live { actor, .. } = managed {
                    actor.detach();
                }
            }
        }
    }

    #[cfg(unix)]
    pub fn adopt_sessions(
        &self,
        state: crate::handover::HandoverState,
        fds: Vec<std::os::unix::io::RawFd>,
    ) -> Result<()> {
        let mut sessions = self.sessions()?;
        let mut pending = UnadoptedFds::new(fds);

        for h_sess in state.sessions {
            let Some(fd) = pending.take_next() else {
                bail!("No inherited FDs left for session {}", h_sess.id);
            };

            let runtime = spawn_adopted_pty_runtime(&h_sess, fd)?;

            let launch = PersistedSessionLaunch {
                command: h_sess.command.clone(),
                args: h_sess.args.clone(),
                cwd: h_sess.cwd.clone(),
                size: h_sess.size.clone(),
                log_path: h_sess.log_path.clone(),
            };

            let event_session_id = Some(h_sess.id.clone());
            let dirty_tx = self.dirty_tx();
            let cwd_update_tx = self.cwd_update_tx();
            let global_senders = Some(self.global_senders());

            let PtyRuntime {
                master,
                child,
                reader,
                writer,
                output,
                size,
                log_path,
                current_working_directory,
            } = runtime;

            let initial_working_directory = current_working_directory
                .or_else(|| h_sess.cwd.clone())
                .or_else(|| std::env::current_dir().ok());
            let initial_context = resolve_session_context(initial_working_directory.as_ref());
            let last_known_cwd = initial_working_directory.clone();

            let (command_tx, command_rx) = mpsc::channel();
            let (output_tx, output_rx) = mpsc::sync_channel(64);
            // Carry the outgoing daemon's stamp through the swap. A zero means
            // that daemon predates the field; fall back to "now" so the session
            // sorts as recent rather than as epoch-old, which would bury a
            // genuinely busy session at the bottom of the rail.
            let adopted_activity_ms = if h_sess.last_activity_ms == 0 {
                now_unix_millis()
            } else {
                h_sess.last_activity_ms
            };
            let last_activity_ms = Arc::new(AtomicU64::new(adopted_activity_ms));
            let actor_last_activity_ms = Arc::clone(&last_activity_ms);

            let reader = thread::Builder::new()
                .name("session-actor-reader".into())
                .spawn(move || read_pty_output(reader, output_tx))
                .context("spawning session actor reader thread")?;

            let worker = thread::Builder::new()
                .name("session-actor-worker".into())
                .spawn(move || {
                    let state = ActorState {
                        master,
                        child,
                        writer,
                        output,
                        size,
                        log_path,
                        exited: false,
                        output_closed: false,
                        exit_broadcasted: false,
                        current_working_directory: initial_working_directory,
                        context: initial_context,
                        event_session_id,
                        dirty_tx,
                        last_activity_ms: actor_last_activity_ms,
                        cwd_update_tx,
                        global_senders,
                        context_resend_pending: false,
                        shell_reports_cwd: false,
                        // Throttle the cwd poll from spawn so the idle refresh
                        // doesn't fire before the session has settled (and races
                        // the initial snapshot); the first poll runs one interval
                        // in. Output-driven polling is gated by the same field.
                        last_cwd_poll: Some(Instant::now()),
                        subscribers: Vec::new(),
                        event_log: VecDeque::new(),
                        next_event_seq: 1,
                    };
                    run_actor(state, command_rx, output_rx);
                })
                // If this spawn fails the closure is dropped, which drops `master`
                // (closing the adopted fd — see AdoptedMasterPty's Drop) and
                // `output_rx`. The reader thread started just above outlives that
                // by design: it is blocked in `read`, and only notices on its next
                // send, which fails against the dropped receiver and ends it. So an
                // idle session leaves one thread and its dup'd fd parked until the
                // child next writes. Bounded and self-clearing, but not immediate —
                // making it deterministic means teaching the actor to tear down a
                // half-built session, which is tracked as a follow-up.
                .context("spawning session actor worker thread")?;

            let actor = SessionActor {
                tx: command_tx,
                worker: Some(worker),
                reader: Some(reader),
                last_activity_ms,
            };

            sessions.insert(
                h_sess.id.clone(),
                ManagedSession::Live {
                    actor,
                    lease: InputLeaseState::default(),
                    launch,
                    last_known_cwd,
                },
            );

            // Per session, so a shell that later turns out to be dead can be
            // identified from the log rather than inferred from a total.
            tracing::info!(
                session_id = %h_sess.id,
                pid = h_sess.pid,
                command = %h_sess.command,
                "adopted inherited live session"
            );
        }

        self.persist_manifest(&sessions)?;
        Ok(())
    }
}

/// Owns the inherited descriptors that have not been handed out yet, and closes
/// whatever it still holds when adoption ends.
///
/// Ownership is strictly one-at-a-time and moves at [`Self::take_next`]: before
/// it the guard owns the descriptor, after it the `AdoptedMasterPty` does. The
/// guard therefore never holds one a session might also be holding, which is
/// what makes closing its remainder in `Drop` sound.
///
/// A `RawFd` is a bare integer with no ownership, so nothing closes one on the
/// way out of [`SessionManager::adopt_sessions`]. That was harmless while a
/// failed adoption propagated into a `process::exit` and the OS reclaimed every
/// descriptor. Now that a partial adoption is logged and the daemon keeps
/// running, a descriptor that never reached a session would stay open for the
/// life of the process — the tail left when adoption gives up partway, and any
/// surplus the handover state does not account for.
#[cfg(unix)]
struct UnadoptedFds {
    fds: std::collections::VecDeque<std::os::unix::io::RawFd>,
}

#[cfg(unix)]
impl UnadoptedFds {
    fn new(fds: Vec<std::os::unix::io::RawFd>) -> Self {
        Self { fds: fds.into() }
    }

    /// Hand the next descriptor to the session about to adopt it.
    ///
    /// Ownership transfers here, to the `AdoptedMasterPty` that
    /// `spawn_adopted_pty_runtime` wraps it in as its very first act. That type
    /// closes on drop, so every early return after the wrap — a rotated log, a
    /// thread spawn hitting EAGAIN — still closes it, as does the actor loop
    /// returning later (see [`crate::handover::AdoptedMasterPty`]; a session merely
    /// *ending* does not). Holding it in the guard past this point instead would
    /// put it under two owners at once and close it twice on the failure path.
    fn take_next(&mut self) -> Option<std::os::unix::io::RawFd> {
        self.fds.pop_front()
    }
}

#[cfg(unix)]
impl Drop for UnadoptedFds {
    fn drop(&mut self) {
        for fd in self.fds.drain(..) {
            // SAFETY: these are the descriptors `take_next` never handed out — a
            // surplus the handover state does not account for, or the tail left
            // when adoption gave up partway. Ownership of everything else moved to
            // its `AdoptedMasterPty`, so this cannot close a descriptor another
            // owner still holds.
            unsafe {
                libc::close(fd);
            }
        }
    }
}

#[cfg(unix)]
fn spawn_adopted_pty_runtime(
    h_sess: &crate::handover::HandoverSession,
    fd: std::os::unix::io::RawFd,
) -> Result<PtyRuntime> {
    use crate::handover::{AdoptedChild, AdoptedMasterPty};

    // SAFETY: `UnadoptedFds::take_next` gave up its claim on this descriptor so
    // the master can own it; nothing else holds or will close it.
    let master = Box::new(unsafe { AdoptedMasterPty::from_raw_fd(fd) });
    let child = Box::new(AdoptedChild { pid: h_sess.pid });

    let reader = master.try_clone_reader().context("cloning PTY reader")?;
    let writer = shared_pty_writer(master.take_writer().context("taking PTY writer")?);

    let terminal = terminal_with_writer(&h_sess.size, writer.clone());
    let log = OpenOptions::new()
        .create(true)
        .read(true)
        .append(true)
        .open(&h_sess.log_path)
        .with_context(|| format!("opening session log {}", h_sess.log_path.display()))?;

    let mut output = OutputState {
        log: log.try_clone().context("cloning restored session log")?,
        log_path: h_sess.log_path.clone(),
        trim_disabled: false,
        max_log_bytes: MAX_SESSION_LOG_BYTES,
        retain_log_bytes: SESSION_LOG_RETAIN_BYTES,
        terminal,
        cwd_sequence_buffer: Vec::new(),
        bytes_logged: 0,
        output_seq: 0,
        log_cache: None,
    };

    let (replay_len, replay) = read_replay_tail(&h_sess.log_path)?;
    let replayed_working_directory = if replay_len == 0 {
        None
    } else {
        output.replay_tail(replay_len, &replay)?
    };
    let current_working_directory = adopted_session_cwd(
        h_sess.pid,
        pty_foreground_pgid(fd),
        replayed_working_directory,
        h_sess.cwd.clone(),
    );

    Ok(PtyRuntime {
        master,
        child,
        reader,
        writer,
        output,
        size: h_sess.size.clone(),
        log_path: h_sess.log_path.clone(),
        current_working_directory,
    })
}

impl ManagedSession {
    fn persisted(&self, session_id: SessionId) -> PersistedSession {
        match self {
            Self::Live {
                actor,
                launch,
                last_known_cwd,
                ..
            } => {
                let mut persisted = launch.clone().into_persisted(session_id, false);
                persisted.last_known_cwd = last_known_cwd.clone();
                // Read through to the actor so every manifest write carries the
                // current activity stamp; this is what makes the periodic flush
                // in `run_activity_persistence_loop` a plain re-persist rather
                // than a separate write path.
                persisted.last_activity_ms = actor.last_activity_ms();
                persisted
            }
            Self::Historical { session, .. } => session.persisted.clone(),
            Self::Restoring { session, .. } => session.persisted.clone(),
        }
    }
}

impl Default for SessionManager {
    fn default() -> Self {
        Self::new(SessionManagerConfig::new(default_log_dir()))
    }
}

/// Held for the duration of a handover this daemon serves; clears the manager's
/// handover-in-flight flag on drop. See [`SessionManager::begin_handover`].
pub struct HandoverGuard<'a> {
    manager: &'a SessionManager,
}

impl Drop for HandoverGuard<'_> {
    fn drop(&mut self) {
        self.manager
            .handover_in_flight
            .store(false, Ordering::Release);
    }
}

impl SessionApi for SessionManager {
    fn list_sessions(&self) -> Result<Vec<SessionId>> {
        let sessions = self.sessions()?;
        let mut ids: Vec<SessionId> = sessions.keys().cloned().collect();
        // `sessions` is a `HashMap`, whose iteration order is arbitrary *and*
        // reseeded per process, so returning its key order unsorted gave clients
        // a different session order on every daemon restart. Sort by creation
        // sequence to give the rail a stable floor to fall back on whenever
        // activity ordering can't decide (equal or unknown stamps).
        ids.sort_by(|left, right| session_sort_key(left).cmp(&session_sort_key(right)));
        Ok(ids)
    }

    fn start_session(&self, request: StartSessionRequest) -> Result<SessionId> {
        // Refuse while a handover is in flight: the outgoing daemon has already
        // snapshotted the session set it is transferring, so a session started
        // now would not be among the handed-off descriptors and would be lost
        // when that daemon detaches and exits. The window is brief (a swap), and
        // failing loudly is far better than silently dropping the session.
        //
        // This early check is only a courtesy so we don't fork a PTY we are about
        // to throw away; it is NOT the one that makes this safe. The authoritative
        // re-check happens below under the `sessions` lock — see there.
        if self.handover_in_flight.load(Ordering::Acquire) {
            bail!("a handover is in progress; try again once the daemon swap completes");
        }
        request.validate()?;
        fs::create_dir_all(&self.config.log_dir).with_context(|| {
            format!("creating session log dir {}", self.config.log_dir.display())
        })?;

        let session_id = self.allocate_session_id()?;
        let log_path = self.log_path(&session_id);
        let config = SessionConfig {
            command: request.command,
            args: request.args,
            cwd: request.cwd,
            size: request.size,
            log_path,
        };
        let launch = PersistedSessionLaunch::from(&config);
        let last_known_cwd = launch.cwd.clone();
        let actor = SessionActor::spawn_managed(
            config,
            session_id.clone(),
            self.dirty_tx(),
            self.cwd_update_tx(),
            Some(self.global_senders()),
        )?;

        let mut sessions = self.sessions()?;

        // Authoritative handover gate. The check at the top of this function ran
        // before `spawn_managed` forked the PTY — tens of milliseconds ago — so a
        // handover that began in the meantime would have snapshotted the session
        // set without this session, and `detach_all_live_sessions` would then drop
        // it on the floor when the outgoing daemon exits. Re-checking here closes
        // that window, because `serialize_active_sessions` holds this same lock
        // for the whole of its snapshot: either we insert before it starts (and
        // are transferred), or we observe the flag it set and refuse.
        //
        // The forked child is killed by dropping `actor` on this path, which is
        // correct — it never became a session anyone can reach.
        if self.handover_in_flight.load(Ordering::Acquire) {
            drop(sessions);
            bail!("a handover is in progress; try again once the daemon swap completes");
        }

        sessions.insert(
            session_id.clone(),
            ManagedSession::Live {
                actor,
                lease: InputLeaseState::default(),
                launch,
                last_known_cwd,
            },
        );
        if let Err(error) = self.persist_manifest(&sessions) {
            let inserted = sessions.remove(&session_id);
            drop(sessions);
            if let Some(ManagedSession::Live { actor, .. }) = inserted
                && let Err(shutdown_error) = actor.shutdown()
            {
                tracing::warn!(
                    error = ?shutdown_error,
                    "failed to shut down session after manifest persistence failure"
                );
            }
            return Err(error);
        }
        Ok(session_id)
    }

    fn attach_session(&self, request: AttachSessionRequest) -> Result<AttachSessionResponse> {
        let mut sessions = self.sessions()?;
        let session = sessions
            .get_mut(&request.session_id)
            .with_context(|| format!("session {} not found", request.session_id))?;

        match session {
            ManagedSession::Live { actor, lease, .. } => {
                if let Some(kind) = request.mode.controller_kind() {
                    let change = lease.acquire(request.client_id, kind);
                    actor.broadcast_event(SessionEvent::LeaseChanged {
                        session_id: request.session_id.clone(),
                        change,
                    })?;
                }

                let snapshot = actor.snapshot()?;
                let lease = lease.clone();
                Ok(AttachSessionResponse {
                    snapshot: self.overlay_snippet(snapshot, &request.session_id),
                    lease,
                })
            }
            ManagedSession::Historical { session, lease } => {
                let snapshot = session.snapshot_with_history();
                let lease = lease.clone();
                Ok(AttachSessionResponse {
                    snapshot: self.overlay_snippet(snapshot, &request.session_id),
                    lease,
                })
            }
            ManagedSession::Restoring { .. } => {
                bail!("session {} is being restored", request.session_id)
            }
        }
    }

    fn subscribe_session_events(&self, session_id: SessionId) -> Result<SessionEventReceiver> {
        self.subscribe_session_events_from(SubscribeSessionEventsRequest {
            session_id,
            after_event_seq: None,
        })
    }

    fn subscribe_session_events_from(
        &self,
        request: SubscribeSessionEventsRequest,
    ) -> Result<SessionEventReceiver> {
        let sessions = self.sessions()?;
        let session = sessions
            .get(&request.session_id)
            .with_context(|| format!("session {} not found", request.session_id))?;
        match session {
            ManagedSession::Live { actor, .. } => actor.subscribe_events(request.after_event_seq),
            ManagedSession::Historical { .. } => Ok(closed_session_event_receiver()),
            ManagedSession::Restoring { .. } => {
                bail!("session {} is being restored", request.session_id)
            }
        }
    }

    fn acquire_input_lease(&self, request: InputLeaseRequest) -> Result<LeaseChange> {
        let mut sessions = self.sessions()?;
        let session = sessions
            .get_mut(&request.session_id)
            .with_context(|| format!("session {} not found", request.session_id))?;
        match session {
            ManagedSession::Live { actor, lease, .. } => {
                let change = lease.acquire(request.client_id, request.kind);
                actor.broadcast_event(SessionEvent::LeaseChanged {
                    session_id: request.session_id,
                    change: change.clone(),
                })?;
                Ok(change)
            }
            ManagedSession::Historical { .. } => {
                bail!("restored historical sessions cannot acquire input leases")
            }
            ManagedSession::Restoring { .. } => {
                bail!("session {} is being restored", request.session_id)
            }
        }
    }

    fn release_input_lease(
        &self,
        session_id: SessionId,
        client_id: ClientId,
    ) -> Result<LeaseChange> {
        let mut sessions = self.sessions()?;
        let session = sessions
            .get_mut(&session_id)
            .with_context(|| format!("session {session_id} not found"))?;
        match session {
            ManagedSession::Live { actor, lease, .. } => {
                let change = lease
                    .release(&client_id)
                    .with_context(|| format!("client {client_id} does not hold input lease"))?;
                actor.broadcast_event(SessionEvent::LeaseChanged {
                    session_id,
                    change: change.clone(),
                })?;
                Ok(change)
            }
            ManagedSession::Historical { .. } => {
                bail!("restored historical sessions cannot hold input leases")
            }
            ManagedSession::Restoring { .. } => {
                bail!("session {session_id} is being restored")
            }
        }
    }

    fn write_input(&self, request: WriteInputRequest) -> Result<()> {
        let sessions = self.sessions()?;
        let session = sessions
            .get(&request.session_id)
            .with_context(|| format!("session {} not found", request.session_id))?;
        let ManagedSession::Live { actor, lease, .. } = session else {
            match session {
                ManagedSession::Historical { .. } => {
                    bail!("restored historical sessions cannot accept input")
                }
                ManagedSession::Restoring { .. } => {
                    bail!("session {} is being restored", request.session_id)
                }
                ManagedSession::Live { .. } => unreachable!(),
            }
        };
        let holder = lease
            .holder
            .as_ref()
            .with_context(|| format!("session {} has no input lease holder", request.session_id))?;
        ensure!(
            holder.client_id == request.client_id,
            "client {} does not hold input lease for session {}",
            request.client_id,
            request.session_id
        );
        actor.write_input(request.bytes)
    }

    fn resize_session(&self, request: ResizeSessionRequest) -> Result<SessionSnapshot> {
        let sessions = self.sessions()?;
        let session = sessions
            .get(&request.session_id)
            .with_context(|| format!("session {} not found", request.session_id))?;
        let snapshot = match session {
            ManagedSession::Live { actor, .. } => actor.resize(request.size)?,
            ManagedSession::Historical { .. } => {
                bail!("restored historical sessions cannot be resized")
            }
            ManagedSession::Restoring { .. } => {
                bail!("session {} is being restored", request.session_id)
            }
        };
        Ok(self.overlay_snippet(snapshot, &request.session_id))
    }

    fn restore_session(&self, request: RestoreSessionRequest) -> Result<SessionSnapshot> {
        request.size.validate()?;
        // A session whose child process dies while `Live` is never demoted to
        // `Historical` on its own, so the block below would reject it as "already
        // live" and it would stay stuck/uninputtable until a daemon restart —
        // e.g. sessions adopted across a handover whose process later exits.
        // Demote a dead `Live` session here so the normal restore path re-spawns
        // it; surfaces a real error if its log can't be rebuilt.
        self.demote_dead_live_session(&request.session_id)?;
        let (persisted, current_working_directory) = {
            let mut sessions = self.sessions()?;
            let existing = sessions
                .remove(&request.session_id)
                .with_context(|| format!("session {} not found", request.session_id))?;
            let ManagedSession::Historical { session, lease } = existing else {
                sessions.insert(request.session_id.clone(), existing);
                bail!(
                    "session {} is already live or restoring",
                    request.session_id
                );
            };
            if !is_restorable_shell_launch(&session.persisted) {
                sessions.insert(
                    request.session_id.clone(),
                    ManagedSession::Historical { session, lease },
                );
                bail!(
                    "session {} was not launched as a restorable shell",
                    request.session_id
                );
            }
            let persisted = session.persisted.clone();
            let current_working_directory = session.current_working_directory.clone();
            sessions.insert(
                request.session_id.clone(),
                ManagedSession::Restoring { session, lease },
            );
            (persisted, current_working_directory)
        };

        let cwd = restorable_cwd(current_working_directory, persisted.cwd.clone());
        let config = SessionConfig {
            command: persisted.command.clone(),
            args: persisted.args.clone(),
            cwd,
            size: request.size,
            log_path: persisted.log_path.clone(),
        };
        let launch = PersistedSessionLaunch::from(&config);
        let last_known_cwd = launch.cwd.clone();
        // The manifest's stamp, handed to the spawn rather than stored after it:
        // restarting the daemon must not re-stamp every restored session with the
        // restart instant, which would collapse the rail's activity order into
        // one tie, the same corruption that ruled out log-file mtimes. A 0 means
        // the manifest predates the field, so the spawn-time default stands.
        let restored_activity_ms =
            (persisted.last_activity_ms != 0).then_some(persisted.last_activity_ms);
        let actor = match SessionActor::spawn_restored(
            config,
            request.session_id.clone(),
            restored_activity_ms,
            self.dirty_tx(),
            self.cwd_update_tx(),
            Some(self.global_senders()),
        ) {
            Ok(actor) => actor,
            Err(error) => {
                self.rollback_restoring_session(request.session_id)?;
                return Err(error);
            }
        };
        let snapshot = match actor.snapshot() {
            Ok(snapshot) => snapshot,
            Err(error) => {
                self.rollback_restoring_session(request.session_id.clone())?;
                actor.shutdown()?;
                return Err(error);
            }
        };

        let mut sessions = self.sessions()?;

        // Same authoritative handover gate as `start_session`: this also inserts a
        // Live session, so a swap that snapshotted before we got here would leave
        // this one out of the transferred descriptors and `detach_all_live_sessions`
        // would drop it. Checked under the `sessions` lock that
        // `serialize_active_sessions` holds across its whole snapshot, so we either
        // land before it starts or observe the flag it set.
        if self.handover_in_flight.load(Ordering::Acquire) {
            drop(sessions);
            // Roll back to Historical before bailing, exactly as the spawn- and
            // snapshot-failure paths above do. Without this the entry stays
            // `Restoring` forever: `restore_session` would reject it as "already
            // live or restoring" and snapshotting bails on `Restoring`, so if the
            // handover then aborts — which it can, leaving this daemon serving —
            // the session is unusable until a restart, and the "try again once the
            // swap completes" this returns could never come true.
            self.rollback_restoring_session(request.session_id.clone())?;
            actor.shutdown()?;
            bail!("a handover is in progress; try again once the daemon swap completes");
        }

        let existing = sessions
            .remove(&request.session_id)
            .with_context(|| format!("session {} not found", request.session_id))?;
        let ManagedSession::Restoring { session, lease } = existing else {
            sessions.insert(request.session_id.clone(), existing);
            drop(sessions);
            actor.shutdown()?;
            bail!("session {} is no longer being restored", request.session_id);
        };
        sessions.insert(
            request.session_id.clone(),
            ManagedSession::Live {
                actor,
                lease: InputLeaseState::default(),
                launch,
                last_known_cwd,
            },
        );
        if let Err(error) = self.persist_manifest(&sessions) {
            let inserted = sessions.remove(&request.session_id);
            sessions.insert(
                request.session_id,
                ManagedSession::Historical { session, lease },
            );
            drop(sessions);
            if let Some(ManagedSession::Live { actor, .. }) = inserted
                && let Err(shutdown_error) = actor.shutdown()
            {
                tracing::warn!(
                    error = ?shutdown_error,
                    "failed to shut down restored session after manifest persistence failure"
                );
            }
            return Err(error);
        }
        drop(sessions);

        Ok(self.overlay_snippet(snapshot, &request.session_id))
    }

    fn snapshot_session(&self, session_id: SessionId) -> Result<SessionSnapshot> {
        let sessions = self.sessions()?;
        let session = sessions
            .get(&session_id)
            .with_context(|| format!("session {session_id} not found"))?;
        let snapshot = match session {
            ManagedSession::Live { actor, .. } => actor.snapshot()?,
            ManagedSession::Historical { session, .. } => session.snapshot_with_history(),
            ManagedSession::Restoring { .. } => bail!("session {session_id} is being restored"),
        };
        Ok(self.overlay_snippet(snapshot, &session_id))
    }

    fn styled_rows(&self, request: StyledRowsRequest) -> Result<StyledRowsResponse> {
        let sessions = self.sessions()?;
        let session = sessions
            .get(&request.session_id)
            .with_context(|| format!("session {} not found", request.session_id))?;
        match session {
            ManagedSession::Live { actor, .. } => actor.styled_rows(request.start, request.end),
            ManagedSession::Historical { session, .. } => {
                session.styled_rows(request.start, request.end)
            }
            ManagedSession::Restoring { .. } => {
                bail!("session {} is being restored", request.session_id)
            }
        }
    }

    fn shutdown_session(&self, session_id: SessionId) -> Result<CompletedSession> {
        let session = {
            let mut sessions = self.sessions()?;
            let session = sessions
                .remove(&session_id)
                .with_context(|| format!("session {session_id} not found"))?;
            if let Err(error) = self.persist_manifest(&sessions) {
                sessions.insert(session_id, session);
                return Err(error);
            }
            session
        };
        self.forget_snippet(&session_id);
        // Each session's own recorded path, never a re-derived name: a session
        // adopted across a handover carries the log path from the handover
        // payload, which need not match `log_dir/{id}.log`. Deleting a derived
        // path would unlink nothing and leak the real log — the very leak this
        // fixes.
        //
        // `Restoring` is deliberately absent. `restore_session` inserts that
        // state, releases the sessions lock, and only then spawns the actor that
        // opens the log, so a shutdown landing in that window would delete a log
        // an in-flight spawn is about to write to. Leaving it is the safe side of
        // the trade: the startup purge reclaims it later.
        let log_path = match &session {
            ManagedSession::Live { launch, .. } => Some(launch.log_path.clone()),
            ManagedSession::Historical { session, .. } => Some(session.persisted.log_path.clone()),
            ManagedSession::Restoring { .. } => None,
        };
        let completed = match session {
            ManagedSession::Live { actor, .. } => actor.shutdown(),
            ManagedSession::Historical { session, .. } => Ok(session.completed_session()),
            ManagedSession::Restoring { session, .. } => Ok(session.completed_session()),
        };
        // Only after the actor has shut down, so nothing is still writing to it.
        // A session removed from the manifest can never be restored, so its log
        // is unreachable from here on and would otherwise leak forever.
        if let Some(log_path) = log_path {
            remove_session_log(&session_id, &log_path);
        }
        completed
    }

    #[allow(clippy::type_complexity)]
    fn list_session_snippets(&self) -> Result<Vec<(SessionId, Option<String>, Option<String>)>> {
        let session_ids = self.list_sessions()?;
        let snippets = self
            .snippets
            .lock()
            .map_err(|_| anyhow!("snippet cache lock poisoned"))?;
        Ok(session_ids
            .into_iter()
            .map(|session_id| {
                let (snippet, detail) = match snippets.get(&session_id) {
                    Some(s) => (Some(s.text.clone()), s.detail.clone()),
                    None => (None, None),
                };
                (session_id, snippet, detail)
            })
            .collect())
    }

    /// Every session's rail metadata (git context plus last-output time), for
    /// the `list_session_contexts` control request. Reads the already-resolved
    /// per-session context — it never re-runs git (`resolve_session_context`):
    /// live sessions return the actor's cached `SessionContext` via a brief
    /// off-lock round-trip (mirroring `summary_rows`), and historical /
    /// restoring sessions read their stored context directly. Sessions with no
    /// resolved context (e.g. a cwd outside any repository) carry `None`.
    ///
    /// Rows come back in the same creation order as [`Self::list_sessions`], so a
    /// client that builds its list from this response inherits a deterministic
    /// order even when every session's activity is unknown.
    fn list_session_contexts(&self) -> Result<Vec<SessionContextRow>> {
        // Capture each session's context source under a brief lock: a cloned
        // actor channel for live sessions (read OFF-LOCK so the round-trip never
        // holds the global `sessions` mutex during actor I/O) or the
        // already-stored context for historical / restoring ones.
        enum ContextSource {
            Ready(Option<SessionContext>),
            Live(Sender<ActorCommand>),
        }
        let mut sources: Vec<(SessionId, ContextSource, u64)> = {
            let sessions = self.sessions()?;
            sessions
                .iter()
                .map(|(session_id, managed)| {
                    let (source, last_activity_ms) = match managed {
                        ManagedSession::Live { actor, .. } => (
                            ContextSource::Live(actor.tx.clone()),
                            actor.last_activity_ms(),
                        ),
                        ManagedSession::Historical { session, .. }
                        | ManagedSession::Restoring { session, .. } => (
                            ContextSource::Ready(session.context.clone()),
                            session.persisted.last_activity_ms,
                        ),
                    };
                    (session_id.clone(), source, last_activity_ms)
                })
                .collect()
        };
        // Same `HashMap`-iteration hazard as `list_sessions`: sort so a client
        // building its list from this response gets a stable fallback order.
        sources.sort_by(|left, right| session_sort_key(&left.0).cmp(&session_sort_key(&right.0)));
        Ok(sources
            .into_iter()
            .map(|(session_id, source, last_activity_ms)| {
                let context = match source {
                    ContextSource::Ready(context) => context,
                    // A live actor mid-shutdown simply yields no context rather
                    // than failing the whole batch.
                    ContextSource::Live(tx) => request_session_context(&tx).ok().flatten(),
                };
                SessionContextRow {
                    session_id,
                    context,
                    last_activity_ms,
                }
            })
            .collect())
    }

    fn server_update_info(&self) -> triage_core::session::ServerUpdateInfo {
        let status = self.update_status();
        triage_core::session::ServerUpdateInfo {
            server_version: status.current,
            update_available: status.update_available,
            latest_version: status.latest,
        }
    }
}

impl PtySession {
    pub fn spawn(config: SessionConfig) -> Result<Self> {
        let runtime = spawn_pty_runtime(config, LogInitialization::Truncate)?;

        Ok(Self {
            _master: runtime.master,
            child: runtime.child,
            reader: runtime.reader,
            _writer: runtime.writer,
            output: runtime.output,
        })
    }

    pub fn drain_until_exit(mut self) -> Result<CompletedSession> {
        let mut chunk = [0; 8192];

        loop {
            match self.reader.read(&mut chunk) {
                Ok(0) => break,
                Ok(read_len) => {
                    self.output.ingest(&chunk[..read_len])?;
                }
                Err(error) if error.kind() == ErrorKind::Interrupted => continue,
                Err(error)
                    if matches!(
                        error.kind(),
                        ErrorKind::BrokenPipe
                            | ErrorKind::ConnectionReset
                            | ErrorKind::UnexpectedEof
                    ) =>
                {
                    break;
                }
                Err(error) if is_closed_pty_error(&error) => break,
                Err(error) => return Err(error).context("reading PTY output"),
            }
        }

        self.child.wait().context("waiting for PTY child")?;
        self.output.log.flush().context("flushing session log")?;

        Ok(CompletedSession {
            output_seq: self.output.output_seq,
            bytes_logged: self.output.bytes_logged,
            visible_rows: visible_rows(&self.output.terminal),
        })
    }
}

pub fn default_log_dir() -> PathBuf {
    default_log_dir_from_env(
        std::env::var_os("XDG_STATE_HOME"),
        std::env::var_os("HOME"),
        std::env::var_os("USERPROFILE"),
    )
}

fn default_log_dir_from_env(
    xdg_state_home: Option<OsString>,
    home: Option<OsString>,
    userprofile: Option<OsString>,
) -> PathBuf {
    xdg_state_home
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            let home = home
                .or(userprofile)
                .map(PathBuf::from)
                .unwrap_or_else(std::env::temp_dir);
            home.join(".local/state")
        })
        .join("triage/sessions")
}

/// Default cache directory for downloaded summarizer model files. Mirrors
/// [`default_log_dir`] but rooted at the XDG *cache* dir (`~/.cache`), since
/// models are re-downloadable caches, not persistent application state.
pub fn default_model_cache_dir() -> PathBuf {
    let cache_root = std::env::var_os("XDG_CACHE_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| {
            let home = std::env::var_os("HOME")
                .or_else(|| std::env::var_os("USERPROFILE"))
                .map(PathBuf::from)
                .unwrap_or_else(std::env::temp_dir);
            home.join(".cache")
        });
    cache_root.join("triage/models")
}

/// State the debounce loop tracks per session between ticks.
struct PendingDirty {
    last_output_seq: u64,
    last_tick_at: Instant,
}

/// Coalescing window for [`SessionManager::flush_cwd_updates`]: working-directory
/// changes that land within this window of the first pending change are written
/// to the manifest in a single rewrite, bounding both disk churn and how long
/// the `sessions` lock is held for cwd persistence under a `cd` storm.
const CWD_PERSIST_SETTLE: Duration = Duration::from_millis(500);

/// How often [`run_activity_persistence_loop`] checks whether any live session's
/// activity stamp has advanced past what the manifest holds.
///
/// Far coarser than [`CWD_PERSIST_SETTLE`] because the two persist very different
/// event rates: a `cd` is occasional and its value is needed exactly, whereas
/// output is continuous and its stamp is only ever a display-ordering hint. The
/// cost of losing up to this much recency to an ungraceful kill is that a session
/// sorts as slightly staler than it was (invisible at rail granularity), while
/// persisting per output would rewrite the manifest continuously under a build.
const ACTIVITY_PERSIST_INTERVAL: Duration = Duration::from_secs(60);

/// Whether any live session's stamp differs from what the last write persisted.
///
/// Only additions and advances count: a session that has *disappeared* since the
/// last tick is deliberately not a reason to write, because the paths that
/// remove a session (shutdown, demotion) persist the manifest themselves. Firing
/// here as well would make every shutdown cost two writes.
fn activity_advanced(
    persisted: &HashMap<SessionId, u64>,
    current: &HashMap<SessionId, u64>,
) -> bool {
    current
        .iter()
        .any(|(session_id, millis)| persisted.get(session_id) != Some(millis))
}

/// Periodically re-persists the manifest when a live session's activity stamp has
/// advanced, so recency survives an ungraceful daemon kill.
///
/// Needed because the manifest is otherwise only rewritten on structural events
/// (start, exit, `cd`). A session that produces output without ever changing
/// directory (a long build, a running agent) would persist no activity at all
/// between those events, which is precisely the session the rail most needs to
/// order correctly.
///
/// Runs on its own thread; exits when the manager is dropped.
fn run_activity_persistence_loop(manager: std::sync::Weak<SessionManager>) {
    // Mirrors what the last write put in the manifest, so a quiet daemon settles
    // into doing no disk I/O: with every session idle the stamps stop advancing
    // and the comparison below keeps failing. Starting empty rather than seeded
    // from the manifest means the first tick after startup always writes once:
    // every live session reads as newly advanced. That is a fair price for not
    // parsing the manifest again here.
    let mut persisted: HashMap<SessionId, u64> = HashMap::new();
    loop {
        thread::sleep(ACTIVITY_PERSIST_INTERVAL);
        let Some(manager) = manager.upgrade() else {
            return;
        };
        let Ok(sessions) = manager.sessions() else {
            return; // lock poisoned; the manager is unusable
        };
        let current: HashMap<SessionId, u64> = sessions
            .iter()
            .filter_map(|(session_id, managed)| match managed {
                ManagedSession::Live { actor, .. } => {
                    Some((session_id.clone(), actor.last_activity_ms()))
                }
                // Historical and restoring sessions produce no output, so their
                // stamps are already whatever the manifest holds.
                _ => None,
            })
            .collect();
        if !activity_advanced(&persisted, &current) {
            continue;
        }
        if let Err(error) = manager.persist_manifest(&sessions) {
            tracing::warn!(error = ?error, "failed to persist session activity");
            // Leave `persisted` untouched so the next tick retries rather than
            // treating the failed write as if it had landed.
            continue;
        }
        // Replacing rather than merging also drops shut-down sessions, so this
        // map tracks the live set instead of growing for the daemon's lifetime.
        persisted = current;
    }
}

/// Drains the cwd-update channel, coalescing a burst of changes within one
/// [`CWD_PERSIST_SETTLE`] window into a single [`SessionManager::flush_cwd_updates`]
/// call. Runs on its own thread; exits when the manager is dropped or every
/// sender (the manager's plus all live actors' clones) has been dropped.
fn run_cwd_persistence_loop(
    manager: std::sync::Weak<SessionManager>,
    rx: Receiver<(SessionId, PathBuf)>,
) {
    loop {
        // Block for the first change of a batch.
        let mut pending: HashMap<SessionId, PathBuf> = HashMap::new();
        match rx.recv() {
            Ok((session_id, cwd)) => {
                pending.insert(session_id, cwd);
            }
            Err(_) => return, // all senders dropped
        }
        // Coalesce everything that arrives within one settle window of the first
        // change, then flush once. The window is measured from the first change
        // (not reset per message), so a sustained storm still flushes every
        // `CWD_PERSIST_SETTLE` rather than starving.
        let deadline = Instant::now() + CWD_PERSIST_SETTLE;
        loop {
            let now = Instant::now();
            if now >= deadline {
                break;
            }
            match rx.recv_timeout(deadline - now) {
                Ok((session_id, cwd)) => {
                    pending.insert(session_id, cwd);
                }
                Err(RecvTimeoutError::Timeout) => break,
                Err(RecvTimeoutError::Disconnected) => {
                    if let Some(manager) = manager.upgrade() {
                        manager.flush_cwd_updates(pending);
                    }
                    return;
                }
            }
        }
        let Some(manager) = manager.upgrade() else {
            return;
        };
        manager.flush_cwd_updates(pending);
    }
}

/// Debounce loop: receives [`DirtyTick`]s from session actors and, once a
/// session's output has been quiet for `settle`, enqueues a summarization job —
/// subject to a per-session rate limit and content-change checks. Runs on its
/// own thread; exits when the manager is dropped or the dirty channel closes.
fn run_debounce_loop(
    manager: std::sync::Weak<SessionManager>,
    summarizer: Summarizer,
    dirty_rx: Receiver<DirtyTick>,
    settle: Duration,
    min_regen: Duration,
) {
    let mut pending: HashMap<SessionId, PendingDirty> = HashMap::new();
    let mut last_enqueue: HashMap<SessionId, Instant> = HashMap::new();
    let mut last_summarized_seq: HashMap<SessionId, u64> = HashMap::new();
    let mut last_prompt_hash: HashMap<SessionId, u64> = HashMap::new();

    loop {
        // Block up to `settle` for the next tick so we re-evaluate readiness
        // even when no new output arrives.
        match dirty_rx.recv_timeout(settle) {
            Ok(tick) => record_tick(&mut pending, tick),
            Err(RecvTimeoutError::Timeout) => {}
            Err(RecvTimeoutError::Disconnected) => break,
        }
        // Coalesce any other immediately-available ticks.
        while let Ok(tick) = dirty_rx.try_recv() {
            record_tick(&mut pending, tick);
        }

        let Some(manager) = manager.upgrade() else {
            break;
        };
        let now = Instant::now();

        let ready: Vec<SessionId> = pending
            .iter()
            .filter(|(_, pd)| now.duration_since(pd.last_tick_at) >= settle)
            .map(|(session_id, _)| session_id.clone())
            .collect();

        for session_id in ready {
            let pd = pending
                .remove(&session_id)
                .expect("ready ids come from pending");

            // Already summarized this exact output position.
            if last_summarized_seq.get(&session_id) == Some(&pd.last_output_seq) {
                continue;
            }
            // Per-session rate limit; keep it pending to retry after the window.
            if let Some(last) = last_enqueue.get(&session_id)
                && now.duration_since(*last) < min_regen
            {
                pending.insert(session_id, pd);
                continue;
            }

            // Off-lock cheap snapshot: never holds the global sessions mutex
            // during the actor round-trip, so it can't starve interactive ops.
            let Some((rows, _output_seq, context)) = manager.summary_rows(&session_id) else {
                // Session likely gone; drop tracking state for it.
                last_enqueue.remove(&session_id);
                last_summarized_seq.remove(&session_id);
                last_prompt_hash.remove(&session_id);
                continue;
            };
            let Some(prompt_text) = build_prompt_text(&rows) else {
                continue;
            };

            let hash = hash_prompt(&prompt_text);
            // Screen text unchanged since last summary (e.g. spinner repaint).
            if last_prompt_hash.get(&session_id) == Some(&hash) {
                last_summarized_seq.insert(session_id, pd.last_output_seq);
                continue;
            }

            if summarizer.try_enqueue(SummarizeJob {
                session_id: session_id.clone(),
                prompt_text,
                output_seq: pd.last_output_seq,
                context,
            }) {
                last_enqueue.insert(session_id.clone(), now);
                last_prompt_hash.insert(session_id.clone(), hash);
                last_summarized_seq.insert(session_id, pd.last_output_seq);
            }
        }
    }
}

fn record_tick(pending: &mut HashMap<SessionId, PendingDirty>, tick: DirtyTick) {
    let entry = pending.entry(tick.session_id).or_insert(PendingDirty {
        last_output_seq: tick.output_seq,
        last_tick_at: Instant::now(),
    });
    entry.last_output_seq = tick.output_seq;
    entry.last_tick_at = Instant::now();
}

fn hash_prompt(text: &str) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    text.hash(&mut hasher);
    hasher.finish()
}

fn load_paired_devices(log_dir: &Path) -> HashMap<ClientId, String> {
    let path = log_dir.join("paired_devices.json");
    if !path.exists() {
        return HashMap::new();
    }

    let content = match fs::read_to_string(&path) {
        Ok(content) => content,
        Err(error) => {
            tracing::warn!(error = ?error, "failed to read paired_devices.json");
            return HashMap::new();
        }
    };

    match serde_json::from_str::<HashMap<String, String>>(&content) {
        Ok(raw_map) => {
            let mut map = HashMap::new();
            for (k, v) in raw_map {
                if let Ok(client_id) = ClientId::new(k) {
                    map.insert(client_id, v);
                }
            }
            map
        }
        Err(error) => {
            tracing::warn!(error = ?error, "failed to parse paired_devices.json");
            HashMap::new()
        }
    }
}

fn save_paired_devices(log_dir: &Path, devices: &HashMap<ClientId, String>) -> Result<()> {
    let path = log_dir.join("paired_devices.json");
    let mut raw_map = HashMap::new();
    for (k, v) in devices {
        raw_map.insert(k.to_string(), v.clone());
    }
    let json = serde_json::to_vec_pretty(&raw_map)?;
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    fs::write(&path, json)?;
    Ok(())
}

fn restore_sessions(config: &SessionManagerConfig) -> Result<HashMap<SessionId, ManagedSession>> {
    let manifest_path = config.manifest_path();
    if !manifest_path.exists() {
        return Ok(HashMap::new());
    }

    let manifest: SessionManifest = serde_json::from_slice(
        &fs::read(&manifest_path)
            .with_context(|| format!("reading session manifest {}", manifest_path.display()))?,
    )
    .with_context(|| format!("decoding session manifest {}", manifest_path.display()))?;
    ensure!(
        manifest.version == 1,
        "unsupported session manifest version {}",
        manifest.version
    );

    let mut sessions = HashMap::new();
    for persisted in manifest.sessions {
        match HistoricalSession::restore(persisted) {
            Ok(session) => {
                sessions.insert(
                    session.persisted.id.clone(),
                    ManagedSession::Historical {
                        session: Box::new(session),
                        lease: InputLeaseState::default(),
                    },
                );
            }
            Err(error) => {
                tracing::warn!(error = ?error, "skipping persisted session");
            }
        }
    }
    Ok(sessions)
}

/// Deletes the output log of a session that has just been removed from the
/// manifest. Best-effort: a failure leaks one log file, which must not turn a
/// successful shutdown into an error.
///
/// The path comes from the manifest or a handover payload, so it is *data*, not
/// something this process derived. Before unlinking, require it to be named
/// `{session_id}.log`: a corrupted manifest — or a future bug recording the
/// wrong path — would otherwise make this delete an arbitrary file. Leaking a
/// stray log is recoverable; deleting the wrong file is not.
///
/// Only the basename is constrained, not the directory, so this narrows the hole
/// rather than closing it. That is deliberate: a session adopted from a
/// predecessor with a different `log_dir` carries that directory in its path,
/// and rejecting it would leak exactly the logs this is meant to reclaim. The
/// basename is the part that never legitimately varies.
fn remove_session_log(session_id: &SessionId, log_path: &Path) {
    let expected = format!("{session_id}.log");
    if log_path.file_name().and_then(|name| name.to_str()) != Some(expected.as_str()) {
        tracing::warn!(
            session_id = %session_id,
            log_path = %log_path.display(),
            "refusing to remove a session log whose name does not match the session; \
             leaving it in place"
        );
        return;
    }
    match fs::remove_file(log_path) {
        Ok(()) => tracing::info!(
            session_id = %session_id,
            log_path = %log_path.display(),
            "removed session log for shut-down session"
        ),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => tracing::warn!(
            session_id = %session_id,
            log_path = %log_path.display(),
            ?error,
            "failed to remove session log for shut-down session"
        ),
    }
}

/// Grace period before an unreferenced session log is deleted.
///
/// Reference checking is the real safety property — [`SessionManager::purge_orphaned_logs`]
/// runs only once every session this daemon owns is in the map, and unions that
/// with the manifest. This age check is a second, weaker line: it bounds the
/// damage if that picture is ever wrong (a manifest written mid-change, a
/// session created by a path not yet considered). It is emphatically *not* a
/// guarantee on its own — an idle shell can sit at a prompt for weeks without
/// writing a byte — so it is applied in addition to reference checking, never
/// instead of it.
const ORPHANED_LOG_RETENTION: std::time::Duration =
    std::time::Duration::from_secs(7 * 24 * 60 * 60);

/// Deletes session logs in `log_dir` that are absent from `referenced` and have
/// not been written to for `retention`.
///
/// Before session shutdown learned to delete its own log, every shut-down
/// session leaked one; this reclaims that backlog and anything a failed deletion
/// leaves behind. Best-effort throughout — this runs on the startup path and
/// must never prevent the daemon from coming up.
///
/// Matching is by *file name*, not by full path. A manifest records the absolute
/// `log_path` a session was created with and keeps it for the session's whole
/// life, while the scanned paths are rebuilt from the current `log_dir`; the two
/// can spell the same location differently (a symlinked `$HOME`, macOS's
/// `/var` → `/private/var`, a re-pointed `XDG_STATE_HOME`). Comparing whole
/// paths would then match nothing and classify *every* referenced log as an
/// orphan — and since historical sessions are exactly the ones untouched for
/// weeks, the age guard would not save them.
fn purge_orphaned_session_logs(
    log_dir: &Path,
    referenced: &HashSet<PathBuf>,
    retention: std::time::Duration,
) {
    let referenced_names: HashSet<&std::ffi::OsStr> = referenced
        .iter()
        .filter_map(|path| path.file_name())
        .collect();

    let entries = match fs::read_dir(log_dir) {
        Ok(entries) => entries,
        Err(error) => {
            tracing::warn!(
                log_dir = %log_dir.display(),
                ?error,
                "failed to scan session log directory; skipping orphan purge"
            );
            return;
        }
    };

    let now = std::time::SystemTime::now();
    let (mut removed, mut reclaimed) = (0_u64, 0_u64);
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|ext| ext.to_str()) != Some("log") {
            continue;
        }
        if path
            .file_name()
            .is_some_and(|name| referenced_names.contains(name))
        {
            continue;
        }
        let Ok(metadata) = entry.metadata() else {
            continue;
        };
        if !metadata.is_file() {
            continue;
        }
        let stale = metadata
            .modified()
            .ok()
            .and_then(|modified| now.duration_since(modified).ok())
            .is_some_and(|age| age >= retention);
        if !stale {
            continue;
        }
        match fs::remove_file(&path) {
            Ok(()) => {
                removed += 1;
                reclaimed += metadata.len();
            }
            Err(error) => tracing::warn!(
                log_path = %path.display(),
                ?error,
                "failed to remove orphaned session log"
            ),
        }
    }

    if removed > 0 {
        tracing::info!(
            removed_logs = removed,
            reclaimed_bytes = reclaimed,
            "purged orphaned session logs"
        );
    }
}

/// Total order over session ids: generated `session-N` ids first, by ascending
/// sequence, then any custom ids lexicographically.
///
/// Sorting the raw string would order `session-10` before `session-2`, putting
/// the rail's fallback order in an obviously wrong sequence once a daemon passes
/// its tenth session. Splitting on the parsed sequence keeps generated ids in
/// creation order while still giving custom ids (which carry no sequence) a
/// stable, deterministic place.
fn session_sort_key(session_id: &SessionId) -> (u8, u64, &str) {
    match generated_session_sequence(session_id) {
        Some(sequence) => (0, sequence, session_id.as_str()),
        None => (1, 0, session_id.as_str()),
    }
}

/// The `N` of a generated `session-N` id, or `None` for a custom one.
///
/// The single place that knows the generated-id format, so changing the scheme
/// cannot leave the ordering and the allocator reading it differently.
fn generated_session_sequence(session_id: &SessionId) -> Option<u64> {
    session_id
        .as_str()
        .strip_prefix("session-")?
        .parse::<u64>()
        .ok()
}

fn next_session_sequence<'a>(sessions: impl Iterator<Item = &'a SessionId>) -> u64 {
    sessions
        .filter_map(generated_session_sequence)
        .max()
        .map_or(1, |sequence| sequence.saturating_add(1))
}

fn is_restorable_shell_launch(persisted: &PersistedSession) -> bool {
    let Some(command_name) = Path::new(&persisted.command)
        .file_name()
        .and_then(|name| name.to_str())
    else {
        return false;
    };
    let command_name = command_name.to_ascii_lowercase();
    if !matches!(
        command_name.as_str(),
        "sh" | "bash" | "zsh" | "fish" | "cmd.exe" | "powershell.exe" | "pwsh"
    ) {
        return false;
    }

    persisted.args.is_empty()
        || matches!(persisted.args.as_slice(), [flag] if flag == "-l")
        || is_triage_default_shell_wrapper(&persisted.args)
}

fn is_triage_default_shell_wrapper(args: &[String]) -> bool {
    matches!(args, [flag, script]
        if matches!(flag.as_str(), "-lc" | "-c")
            && script.contains("exec \"${SHELL:-/bin/sh}\""))
}

fn restorable_cwd(
    current_working_directory: Option<PathBuf>,
    launch_cwd: Option<PathBuf>,
) -> Option<PathBuf> {
    [current_working_directory, launch_cwd]
        .into_iter()
        .flatten()
        .find(|path| path.is_dir())
}

/// Read the foreground process group id of a PTY from its master fd. Returns
/// the pgid (which equals the group leader's pid) when the terminal reports a
/// foreground group, else `None`. Shared by the live actor
/// ([`ActorState::foreground_pgid`]) and handover adoption.
#[cfg(unix)]
fn pty_foreground_pgid(fd: std::os::unix::io::RawFd) -> Option<u32> {
    // SAFETY: the caller passes a live PTY master fd.
    let pgid = unsafe { libc::tcgetpgrp(fd) };
    (pgid > 0).then_some(pgid as u32)
}

/// Resolve the working directory for a session adopted across a handover.
///
/// The adopted process is still alive, so its real cwd is read straight from the
/// kernel and preferred above everything else. `foreground_pgid` is the PTY's
/// foreground process group leader — the same source the live actor polls — so a
/// `cd` made in a nested shell or agent is recovered immediately; it falls back
/// to `pid` (the direct PTY child) when the foreground group is unreadable. This
/// kernel read is the only source that reflects a `cd` in a shell that never
/// emits OSC 7 (zsh, fish, …): `replayed_working_directory` comes from replaying
/// OSC 7 reports in the session log, and `launch_cwd` is the *original* launch
/// directory. Without it, a handover-restored non-OSC-7 session comes back
/// pinned to its launch directory — so the side rail shows the launch branch
/// (typically the repo's default branch) until it next emits output. Falls back
/// to the replayed cwd, then the launch cwd, if the process has since exited or
/// its cwd is unreadable.
fn adopted_session_cwd(
    pid: u32,
    foreground_pgid: Option<u32>,
    replayed_working_directory: Option<PathBuf>,
    launch_cwd: Option<PathBuf>,
) -> Option<PathBuf> {
    let live = foreground_pgid
        .and_then(child_cwd)
        .or_else(|| child_cwd(pid));
    restorable_cwd(live.or(replayed_working_directory), launch_cwd)
}

fn replace_manifest(temp_path: &Path, manifest_path: &Path) -> Result<()> {
    #[cfg(windows)]
    {
        return replace_manifest_with_backup(temp_path, manifest_path);
    }

    #[cfg(not(windows))]
    fs::rename(temp_path, manifest_path).with_context(|| {
        format!(
            "moving session manifest {} to {}",
            temp_path.display(),
            manifest_path.display()
        )
    })
}

#[cfg(any(windows, test))]
fn replace_manifest_with_backup(temp_path: &Path, manifest_path: &Path) -> Result<()> {
    if !manifest_path.exists() {
        return fs::rename(temp_path, manifest_path).with_context(|| {
            format!(
                "moving session manifest {} to {}",
                temp_path.display(),
                manifest_path.display()
            )
        });
    }

    let backup_path = manifest_path.with_extension("json.bak");
    remove_path_if_exists(&backup_path).with_context(|| {
        format!(
            "removing stale session manifest backup {}",
            backup_path.display()
        )
    })?;
    fs::rename(manifest_path, &backup_path).with_context(|| {
        format!(
            "backing up session manifest {} to {}",
            manifest_path.display(),
            backup_path.display()
        )
    })?;

    match fs::rename(temp_path, manifest_path) {
        Ok(()) => {
            remove_path_if_exists(&backup_path).with_context(|| {
                format!("removing session manifest backup {}", backup_path.display())
            })?;
            Ok(())
        }
        Err(error) => {
            if let Err(restore_error) = fs::rename(&backup_path, manifest_path) {
                tracing::error!(
                    error = ?restore_error,
                    "failed to restore previous session manifest after replacement failure"
                );
            }
            Err(error).with_context(|| {
                format!(
                    "moving session manifest {} to {}",
                    temp_path.display(),
                    manifest_path.display()
                )
            })
        }
    }
}

#[cfg(any(windows, test))]
fn remove_path_if_exists(path: &Path) -> Result<()> {
    match fs::metadata(path) {
        Ok(metadata) if metadata.is_dir() => fs::remove_dir_all(path)
            .with_context(|| format!("removing directory {}", path.display())),
        Ok(_) => fs::remove_file(path).with_context(|| format!("removing file {}", path.display())),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error).with_context(|| format!("reading metadata {}", path.display())),
    }
}

fn closed_session_event_receiver() -> SessionEventReceiver {
    let (_tx, rx) = mpsc::channel();
    rx
}

impl HistoricalSession {
    fn restore(persisted: PersistedSession) -> Result<Self> {
        let size = persisted.size.clone();
        let mut output = output_state_for_log(&persisted.log_path, persisted.size.clone())?;
        let (log_len, log) = read_replay_tail(&persisted.log_path)?;
        // Always replay to rebuild the terminal screen; its OSC 7 cwd result is a
        // by-product used as one cwd candidate below. Guarded on the reported
        // length rather than on the tail being empty: those agree today, but the
        // length is what `bytes_logged` must end up holding.
        let replayed_cwd = if log_len == 0 {
            None
        } else {
            output.replay_tail(log_len, &log)?
        };
        // Deliberately no trim here. Restore runs during a handover *before* the
        // adoption byte, while the outgoing daemon is still fully serving and
        // writing these same logs (see the comment above `SessionManager::default`
        // in `main.rs`), so truncating one would corrupt a live writer's file:
        // a `write(true)` handle would resume at its pre-truncation offset and
        // punch a sparse hole, and an `append(true)` one would leave the other
        // daemon's `bytes_logged` past EOF. A log that is already oversized is
        // trimmed once its session next ingests output.
        // Choose the cwd by precedence, validating each so a removed worktree
        // falls through to the next candidate (rather than surfacing a dead path
        // / losing git context in the side rail for a never-restored session):
        //   1. last_known_cwd — the foreground-process-group cwd tracked while
        //      live. The most authoritative source: it reflects a `cd` made in a
        //      nested shell or agent, and is the only one for shells that never
        //      emit OSC 7 (zsh, fish), where the replay recovers nothing.
        //   2. replayed OSC 7 cwd — the *login shell's* last reported dir (bash).
        //      A fallback for older manifests with no last_known_cwd. It is NOT
        //      preferred over last_known_cwd: being the login shell's, it can lag
        //      behind work done in a nested subshell (the exact bug this fixes).
        //   3. launch dir — last resort.
        // The live-restore path applies the same `is_dir` filter via
        // `restorable_cwd`.
        let current_working_directory = [
            persisted.last_known_cwd.clone(),
            replayed_cwd,
            persisted.cwd.clone(),
        ]
        .into_iter()
        .flatten()
        .find(|path| path.is_dir());
        let context = resolve_session_context(current_working_directory.as_ref());
        Ok(Self {
            persisted,
            output,
            size,
            current_working_directory,
            context,
        })
    }

    fn snapshot(&self) -> SessionSnapshot {
        snapshot_from_output(
            &self.output,
            &self.size,
            self.current_working_directory.clone(),
            self.context.clone(),
            true,
        )
    }

    /// As [`Self::snapshot`], but carrying the raw output-history tail for
    /// client-side re-emulation. Historical sessions are only ever read on the
    /// attach/snapshot paths, so this is always history-bearing.
    fn snapshot_with_history(&self) -> SessionSnapshot {
        overlay_raw_output_history(
            self.snapshot(),
            &self.persisted.log_path,
            self.output.bytes_logged,
        )
    }

    fn styled_rows(&self, start: usize, end: usize) -> Result<StyledRowsResponse> {
        ensure!(start <= end, "styled row start must be before end");
        let row_count = self.output.terminal.screen().scrollback_rows();
        ensure!(
            end <= row_count,
            "styled row range {start}..{end} exceeds retained row count {row_count}"
        );
        Ok(StyledRowsResponse {
            output_seq: self.output.output_seq,
            start,
            rows: styled_visible_rows_for_range(&self.output.terminal, start, end),
        })
    }

    fn completed_session(&self) -> CompletedSession {
        CompletedSession {
            output_seq: self.output.output_seq,
            bytes_logged: self.output.bytes_logged,
            visible_rows: visible_rows(&self.output.terminal),
        }
    }
}

impl SessionActor {
    pub fn spawn(config: SessionConfig) -> Result<Self> {
        Self::spawn_with_events(
            config,
            None,
            None,
            None,
            None,
            None,
            LogInitialization::Truncate,
        )
    }

    fn spawn_managed(
        config: SessionConfig,
        session_id: SessionId,
        dirty_tx: Option<DirtySender>,
        cwd_update_tx: Option<CwdUpdateSender>,
        global_senders: Option<GlobalSenders>,
    ) -> Result<Self> {
        Self::spawn_with_events(
            config,
            Some(session_id),
            None,
            dirty_tx,
            cwd_update_tx,
            global_senders,
            LogInitialization::Truncate,
        )
    }

    /// `initial_activity_ms` is the manifest's stamp for this session, or None
    /// when it predates the field. Passed in rather than stored afterwards
    /// because the reader thread starts inside this call: a restored interactive
    /// shell prints its prompt within milliseconds, and a seed applied after the
    /// fact loses that race and re-stamps the session to "now", which is the
    /// collapse the seed exists to prevent.
    fn spawn_restored(
        config: SessionConfig,
        session_id: SessionId,
        initial_activity_ms: Option<u64>,
        dirty_tx: Option<DirtySender>,
        cwd_update_tx: Option<CwdUpdateSender>,
        global_senders: Option<GlobalSenders>,
    ) -> Result<Self> {
        Self::spawn_with_events(
            config,
            Some(session_id),
            initial_activity_ms,
            dirty_tx,
            cwd_update_tx,
            global_senders,
            LogInitialization::ReplayExisting,
        )
    }

    fn spawn_with_events(
        config: SessionConfig,
        event_session_id: Option<SessionId>,
        initial_activity_ms: Option<u64>,
        dirty_tx: Option<DirtySender>,
        cwd_update_tx: Option<CwdUpdateSender>,
        global_senders: Option<GlobalSenders>,
        log_initialization: LogInitialization,
    ) -> Result<Self> {
        let initial_working_directory = config.cwd.clone().or_else(|| std::env::current_dir().ok());
        let runtime = spawn_pty_runtime(config, log_initialization)?;
        let PtyRuntime {
            master,
            child,
            reader,
            writer,
            output,
            size,
            log_path,
            current_working_directory,
        } = runtime;
        let initial_working_directory = current_working_directory.or(initial_working_directory);
        let initial_context = resolve_session_context(initial_working_directory.as_ref());

        let (command_tx, command_rx) = mpsc::channel();
        let (output_tx, output_rx) = mpsc::sync_channel(64);
        // Seed at spawn so a session that has produced no output yet still sorts
        // by when it appeared rather than falling into the unknown-activity
        // bucket. A restored session supplies its manifest stamp here instead, so
        // the atomic is already correct before the reader thread below can take
        // its first output and overwrite it.
        let last_activity_ms = Arc::new(AtomicU64::new(
            initial_activity_ms.unwrap_or_else(now_unix_millis),
        ));
        let actor_last_activity_ms = Arc::clone(&last_activity_ms);
        let reader = thread::Builder::new()
            .name("session-actor-reader".into())
            .spawn(move || read_pty_output(reader, output_tx))
            .context("spawning session actor reader thread")?;
        let worker = thread::Builder::new()
            .name("session-actor-worker".into())
            .spawn(move || {
                let state = ActorState {
                    master,
                    child,
                    writer,
                    output,
                    size,
                    log_path,
                    exited: false,
                    output_closed: false,
                    exit_broadcasted: false,
                    current_working_directory: initial_working_directory,
                    context: initial_context,
                    event_session_id,
                    dirty_tx,
                    last_activity_ms: actor_last_activity_ms,
                    cwd_update_tx,
                    global_senders,
                    context_resend_pending: false,
                    shell_reports_cwd: false,
                    // Throttle the cwd poll from spawn so the idle refresh doesn't
                    // fire before the session has settled (and races the initial
                    // snapshot); the first poll runs one interval in.
                    last_cwd_poll: Some(Instant::now()),
                    subscribers: Vec::new(),
                    event_log: VecDeque::new(),
                    next_event_seq: 1,
                };
                run_actor(state, command_rx, output_rx);
            })
            .context("spawning session actor worker thread")?;

        Ok(Self {
            tx: command_tx,
            worker: Some(worker),
            reader: Some(reader),
            last_activity_ms,
        })
    }

    /// Milliseconds since the Unix epoch of this session's most recent output.
    fn last_activity_ms(&self) -> u64 {
        self.last_activity_ms.load(Ordering::Relaxed)
    }

    pub fn subscribe_events(&self, after_event_seq: Option<u64>) -> Result<SessionEventReceiver> {
        let (tx, rx) = mpsc::channel();
        self.tx
            .send(ActorCommand::SubscribeEvents {
                after_event_seq,
                response: tx,
            })
            .context("sending session event subscription command")?;
        recv_actor_result(rx, "subscribing to session events")
    }

    #[cfg(test)]
    fn subscriber_count(&self) -> Result<usize> {
        let (tx, rx) = mpsc::channel();
        self.tx
            .send(ActorCommand::SubscriberCount { response: tx })
            .context("sending session subscriber count command")?;
        recv_actor_result(rx, "counting session event subscribers")
    }

    pub fn broadcast_event(&self, event: SessionEvent) -> Result<()> {
        let (tx, rx) = mpsc::channel();
        self.tx
            .send(ActorCommand::BroadcastEvent {
                event: Box::new(event),
                response: tx,
            })
            .context("sending session event broadcast command")?;
        recv_actor_result(rx, "broadcasting session event")
    }

    pub fn write_input(&self, bytes: impl Into<Vec<u8>>) -> Result<()> {
        let (tx, rx) = mpsc::channel();
        self.tx
            .send(ActorCommand::WriteInput {
                bytes: bytes.into(),
                response: tx,
            })
            .context("sending session input command")?;
        recv_actor_result(rx, "writing session input")
    }

    pub fn resize(&self, size: SessionSize) -> Result<SessionSnapshot> {
        let (tx, rx) = mpsc::channel();
        self.tx
            .send(ActorCommand::Resize { size, response: tx })
            .context("sending session resize command")?;
        recv_actor_result(rx, "resizing session")
    }

    pub fn snapshot(&self) -> Result<SessionSnapshot> {
        let (tx, rx) = mpsc::channel();
        self.tx
            .send(ActorCommand::Snapshot { response: tx })
            .context("sending session snapshot command")?;
        recv_actor_result(rx, "reading session snapshot")
    }

    pub fn styled_rows(&self, start: usize, end: usize) -> Result<StyledRowsResponse> {
        let (tx, rx) = mpsc::channel();
        self.tx
            .send(ActorCommand::StyledRows {
                start,
                end,
                response: tx,
            })
            .context("sending session styled row command")?;
        recv_actor_result(rx, "reading session styled rows")
    }

    pub fn shutdown(mut self) -> Result<CompletedSession> {
        let (tx, rx) = mpsc::channel();
        let result = self
            .tx
            .send(ActorCommand::Shutdown { response: tx })
            .context("sending session shutdown command")
            .and_then(|_| recv_actor_result(rx, "shutting down session"));
        self.join_threads();
        result
    }

    fn join_threads(&mut self) {
        if let Some(worker) = self.worker.take() {
            join_thread_with_timeout(worker, "session actor worker");
        }
        if let Some(reader) = self.reader.take() {
            join_thread_with_timeout(reader, "session actor reader");
        }
    }

    /// Disarms the actor for a process handover: drops the worker/reader join
    /// handles WITHOUT signalling shutdown, so nothing kills the live PTY child.
    /// Killing it here (as [`Self::shutdown`] and [`Drop`] do) is exactly what
    /// tears every session down across a handover; the successor daemon already
    /// owns the session through the transferred master fd.
    ///
    /// Taking `self` by value is load-bearing, not incidental: it is what stops a
    /// future caller keeping a detached actor — and so its `Sender` — alive, which
    /// would leave the worker loop nothing to end on. Clearing the handles only
    /// gives up the right to join. The sole caller,
    /// `SessionManager::detach_all_live_sessions`, documents what both threads do
    /// from here and why the PTY master closing is safe.
    fn detach(mut self) {
        self.worker = None;
        self.reader = None;
        // `self` drops here; the `Drop` impl is a no-op once `worker` is `None`.
    }
}

impl Drop for SessionActor {
    fn drop(&mut self) {
        if self.worker.is_none() {
            return;
        }

        let (tx, rx) = mpsc::channel();
        if self
            .tx
            .send(ActorCommand::Shutdown { response: tx })
            .is_err()
        {
            tracing::warn!("session actor stopped before drop shutdown signal");
        }
        drop(rx);
    }
}

/// Notification that a session produced output, sent from the actor's output
/// hot path to the summarizer's debounce loop. Deliberately tiny: one
/// non-blocking `Sender::send` per output chunk, no lock and no I/O.
#[derive(Debug, Clone)]
pub(crate) struct DirtyTick {
    pub session_id: SessionId,
    pub output_seq: u64,
}

pub(crate) type DirtySender = std::sync::mpsc::Sender<DirtyTick>;

struct ActorState {
    master: Box<dyn MasterPty + Send>,
    child: Box<dyn Child + Send + Sync>,
    writer: SharedPtyWriter,
    output: OutputState,
    size: SessionSize,
    log_path: PathBuf,
    exited: bool,
    output_closed: bool,
    exit_broadcasted: bool,
    current_working_directory: Option<PathBuf>,
    context: Option<SessionContext>,
    event_session_id: Option<SessionId>,
    /// When set, the actor reports output activity here so the summarizer can
    /// (re)generate this session's snippet once its output settles.
    dirty_tx: Option<DirtySender>,
    /// Shared with [`SessionActor::last_activity_ms`]; stamped on every output
    /// ingest. Distinct from [`Self::dirty_tx`], which is `None` whenever the
    /// summarizer is disabled; activity ordering must not depend on that.
    last_activity_ms: Arc<AtomicU64>,
    /// When set (managed sessions), the actor reports working-directory changes
    /// here so the manager records the live cwd into the on-disk manifest,
    /// letting a daemon kill restore the session where it left off. `None` for
    /// unmanaged/test actors. Sent only on an actual change.
    cwd_update_tx: Option<CwdUpdateSender>,
    /// When set (managed sessions), the actor broadcasts a
    /// [`ServerMessage::SessionContextUpdated`] here whenever its working
    /// directory / git context changes, keeping every client's side rail fresh
    /// without re-attaching. `None` for unmanaged/test actors.
    global_senders: Option<GlobalSenders>,
    /// Set when the last [`ServerMessage::SessionContextUpdated`] broadcast was
    /// dropped for at least one full client channel. Because context updates are
    /// only emitted on change, the actor re-attempts the broadcast (with the
    /// current context) on the next output event until it is delivered.
    context_resend_pending: bool,
    /// Set once the session has reported its cwd via OSC 7 at least once, i.e.
    /// its shell honors the injected `PROMPT_COMMAND` hook (bash). When true, we
    /// trust OSC 7 and skip the OS-level cwd polling entirely; when it stays
    /// false (zsh, fish, ...), the fallback poll keeps the cwd fresh.
    shell_reports_cwd: bool,
    /// Timestamp of the last OS-level working-directory poll, used to throttle
    /// the fallback so git context is not re-resolved on every output chunk for
    /// shells that never emit OSC 7.
    last_cwd_poll: Option<Instant>,
    subscribers: Vec<EventSubscriber>,
    event_log: VecDeque<SessionEventEnvelope>,
    next_event_seq: u64,
}

struct EventSubscriber {
    tx: SyncSender<SessionEventEnvelope>,
    next_event_seq: u64,
}

struct PtyRuntime {
    master: Box<dyn MasterPty + Send>,
    child: Box<dyn Child + Send + Sync>,
    reader: Box<dyn Read + Send>,
    writer: SharedPtyWriter,
    output: OutputState,
    size: SessionSize,
    log_path: PathBuf,
    current_working_directory: Option<PathBuf>,
}

struct OutputState {
    log: File,
    /// Path of `log`, retained so the log can be trimmed once it outgrows
    /// [`MAX_SESSION_LOG_BYTES`]. Trimming rewrites the file through a separate
    /// non-append handle, which has to be opened by path.
    log_path: PathBuf,
    /// Set after a trim fails, to stop retrying it on every subsequent write.
    trim_disabled: bool,
    /// Size at which the log is trimmed, and the size it is trimmed back to.
    /// Fields rather than direct uses of [`MAX_SESSION_LOG_BYTES`] /
    /// [`SESSION_LOG_RETAIN_BYTES`] so tests can drive the real trim path
    /// without writing megabytes.
    max_log_bytes: u64,
    retain_log_bytes: u64,
    terminal: Terminal,
    cwd_sequence_buffer: Vec<u8>,
    bytes_logged: u64,
    output_seq: u64,
    log_cache: Option<Vec<u8>>,
}

/// Visible rows + output sequence + git context, returned by the actor's
/// cheap `SummaryRows` snapshot for the summarizer.
type SummaryRowsResponse = (Vec<String>, u64, Option<SessionContext>);

enum ActorMessage {
    Output(Vec<u8>),
    OutputClosed(Result<()>),
}

enum ActorCommand {
    WriteInput {
        bytes: Vec<u8>,
        response: Sender<ActorResult<()>>,
    },
    Resize {
        size: SessionSize,
        response: Sender<ActorResult<SessionSnapshot>>,
    },
    Snapshot {
        response: Sender<ActorResult<SessionSnapshot>>,
    },
    /// Cheap visible-rows-only snapshot for the summarizer: no styled rows and
    /// no raw-output-history disk read, so it never blocks on I/O. Returns a
    /// `(rows, output_seq, context)` tuple: the plain visible rows, the current
    /// output sequence, and the optional `SessionContext`
    /// (repository/worktree root + branch) used to localize the summary.
    SummaryRows {
        response: Sender<ActorResult<SummaryRowsResponse>>,
    },
    /// Cheap read of the session's already-resolved git context
    /// (repository/worktree root + branch): the actor just clones its cached
    /// `SessionContext`, so this never renders rows or re-runs git. Backs the
    /// `list_session_contexts` control request.
    Context {
        response: Sender<ActorResult<Option<SessionContext>>>,
    },
    StyledRows {
        start: usize,
        end: usize,
        response: Sender<ActorResult<StyledRowsResponse>>,
    },
    SubscribeEvents {
        after_event_seq: Option<u64>,
        response: Sender<ActorResult<SessionEventReceiver>>,
    },
    #[cfg(test)]
    SubscriberCount {
        response: Sender<ActorResult<usize>>,
    },
    BroadcastEvent {
        event: Box<SessionEvent>,
        response: Sender<ActorResult<()>>,
    },
    Shutdown {
        response: Sender<ActorResult<CompletedSession>>,
    },
    #[cfg(unix)]
    ExtractHandoverState {
        response: Sender<ActorResult<ExtractedHandover>>,
    },
}

#[cfg(unix)]
#[derive(Debug)]
pub struct ExtractedHandover {
    pub fd: std::os::unix::io::RawFd,
    pub pid: u32,
    pub output_seq: u64,
    pub bytes_logged: u64,
}

type ActorResult<T> = Result<T>;
type SharedPtyWriter = Arc<Mutex<Box<dyn Write + Send>>>;

fn run_actor(
    mut state: ActorState,
    command_rx: Receiver<ActorCommand>,
    output_rx: Receiver<ActorMessage>,
) {
    loop {
        if state.output_closed {
            match command_rx.recv_timeout(Duration::from_millis(20)) {
                Ok(command) => {
                    if state.handle_command(command, &command_rx, &output_rx) {
                        break;
                    }
                }
                Err(RecvTimeoutError::Timeout) => {
                    state.reap_child();
                    state.broadcast_exit();
                    state.flush_subscribers();
                }
                Err(RecvTimeoutError::Disconnected) => break,
            }
            continue;
        }

        match command_rx.try_recv() {
            Ok(command) => {
                if state.handle_command(command, &command_rx, &output_rx) {
                    break;
                }
                continue;
            }
            Err(TryRecvError::Disconnected) => break,
            Err(TryRecvError::Empty) => {}
        }

        match output_rx.recv_timeout(Duration::from_millis(20)) {
            Ok(message) => state.handle_output(message),
            Err(RecvTimeoutError::Timeout) => {
                state.refresh_idle_cwd();
                state.flush_subscribers();
            }
            Err(RecvTimeoutError::Disconnected) => {
                state.output_closed = true;
                state.mark_exited();
                state.broadcast_exit();
                state.flush_subscribers();
            }
        }
    }
}

impl ActorState {
    #[cfg(unix)]
    fn extract_handover_state(&mut self) -> Result<ExtractedHandover> {
        let fd = self
            .master
            .as_raw_fd()
            .ok_or_else(|| anyhow!("MasterPty has no raw fd"))?;

        let dup_fd = unsafe { libc::dup(fd) };
        if dup_fd < 0 {
            bail!(
                "failed to dup PTY master: {}",
                std::io::Error::last_os_error()
            );
        }

        let pid = self
            .child
            .process_id()
            .ok_or_else(|| anyhow!("Child process has no process ID"))?;

        Ok(ExtractedHandover {
            fd: dup_fd,
            pid,
            output_seq: self.output.output_seq,
            bytes_logged: self.output.bytes_logged,
        })
    }

    /// Pushes the current working directory + git context to every connected
    /// client so their side rails update live (e.g. when the shell `cd`s into or
    /// out of a repo). No-op for unmanaged actors or before a session id is
    /// assigned. `current_working_directory` is sent whenever known — even
    /// outside a repo — with the git fields left `None`, so the rail can fall
    /// back to showing the cwd.
    fn broadcast_context_update(&mut self) {
        let (Some(session_id), Some(global_senders)) =
            (self.event_session_id.clone(), self.global_senders.clone())
        else {
            return;
        };
        let to_string = |path: &Path| path.to_string_lossy().into_owned();
        let current_working_directory = self.current_working_directory.as_deref().map(to_string);
        let (repository_root, worktree_root, branch) = match &self.context {
            Some(context) => (
                context.repository_root.as_deref().map(to_string),
                context.worktree_root.as_deref().map(to_string),
                context.branch_name().map(str::to_string),
            ),
            None => (None, None, None),
        };
        let delivered = broadcast_to_global_senders(
            &global_senders,
            ServerMessage::SessionContextUpdated {
                session_id,
                current_working_directory,
                repository_root,
                worktree_root,
                branch,
            },
        );
        // If a client's channel was full the update was dropped for it; since
        // context updates are only emitted on change, remember to resend the
        // current context on the next output event until it lands.
        self.context_resend_pending = !delivered;
    }

    /// Update the tracked working directory and git context, broadcasting the
    /// change to clients. Re-resolves git context on every call so a branch
    /// switch within the same directory is still caught; only broadcasts when
    /// the cwd or resolved context actually changed (or a prior broadcast was
    /// dropped for a then-full client channel and still needs to land).
    fn apply_cwd(&mut self, cwd: PathBuf) {
        let new_context = resolve_session_context(Some(&cwd));
        let context_changed = self.context != new_context;
        let cwd_changed = self.current_working_directory.as_deref() != Some(cwd.as_path());
        self.context = new_context;
        self.current_working_directory = Some(cwd);
        if context_changed || cwd_changed || self.context_resend_pending {
            self.broadcast_context_update();
        }
        // Persist only on an actual directory change — the manifest tracks the
        // path, not the git branch, so a same-dir branch switch needn't re-write.
        if cwd_changed {
            self.report_cwd_change();
        }
    }

    /// Notify the manager that this session's working directory changed so it
    /// records the new cwd into the on-disk manifest. No-op for unmanaged actors
    /// or before a session id is assigned. A full/closed channel is tolerable —
    /// the next change retries, and a daemon-kill restore copes with a slightly
    /// stale cwd by falling back to the launch dir.
    fn report_cwd_change(&self) {
        let (Some(session_id), Some(cwd_update_tx), Some(cwd)) = (
            self.event_session_id.clone(),
            self.cwd_update_tx.as_ref(),
            self.current_working_directory.clone(),
        ) else {
            return;
        };
        let _ = cwd_update_tx.send((session_id, cwd));
    }

    /// Read the working directory of the process actually using the terminal
    /// from the OS, used for shells that do not emit OSC 7. Throttled to
    /// [`CWD_POLL_INTERVAL`] so the underlying `git` invocations in
    /// [`Self::apply_cwd`] are not run on every output chunk while an agent
    /// repaints its TUI.
    fn poll_child_cwd(&mut self) -> Option<PathBuf> {
        let now = Instant::now();
        if let Some(last) = self.last_cwd_poll
            && now.duration_since(last) < CWD_POLL_INTERVAL
        {
            return None;
        }
        self.last_cwd_poll = Some(now);
        // Prefer the foreground process group leader's cwd (what the user is
        // interacting with). If that pid is unreadable — e.g. a pipeline whose
        // group leader has exited while later stages run on, so the pgid no
        // longer names a live process — fall back to the direct PTY child so the
        // tracked cwd doesn't silently freeze.
        if let Some(pgid) = self.foreground_pgid()
            && let Some(cwd) = child_cwd(pgid)
        {
            return Some(cwd);
        }
        child_cwd(self.child.process_id()?)
    }

    /// While idle (no output to drive [`Self::handle_output`]), keep the tracked
    /// cwd fresh for shells that never emit OSC 7, so the side rail follows a
    /// `cd` made in a nested shell or agent even when the session is quiet.
    /// Throttled by [`Self::poll_child_cwd`]; skipped once the shell has proven
    /// it emits OSC 7 (we then trust OSC 7) or after the child has exited.
    fn refresh_idle_cwd(&mut self) {
        if self.shell_reports_cwd || self.exited {
            return;
        }
        if let Some(cwd) = self.poll_child_cwd() {
            self.apply_polled_cwd(cwd);
        }
    }

    /// Apply a cwd discovered by the *idle* poll, but skip the work in
    /// [`Self::apply_cwd`] — notably the three `git` invocations in
    /// [`resolve_session_context`] — when the directory is unchanged. A
    /// stationary idle non-OSC-7 session would otherwise re-resolve git context
    /// every [`CWD_POLL_INTERVAL`] forever for no result. Same-directory branch
    /// switches are instead caught on the output-driven path (which calls
    /// [`Self::apply_cwd`] directly, since a `git switch`/`checkout` produces
    /// output) and on the next actual cwd change.
    fn apply_polled_cwd(&mut self, cwd: PathBuf) {
        if self.current_working_directory.as_deref() != Some(cwd.as_path()) {
            self.apply_cwd(cwd);
        }
    }

    /// The PTY's foreground process group id (which equals the group leader's
    /// pid) — the shell or program the user is actively interacting with, so a
    /// `cd` made in a nested shell or agent is tracked, not just the login shell
    /// that triage spawned (which sits in the launch dir). `None` when the fd is
    /// unavailable or the terminal reports no foreground group; callers fall back
    /// to the direct PTY child. Note the returned id is only resolvable while the
    /// group leader is alive — [`Self::poll_child_cwd`] handles the dead-leader
    /// case.
    fn foreground_pgid(&self) -> Option<u32> {
        #[cfg(unix)]
        if let Some(fd) = self.master.as_raw_fd() {
            return pty_foreground_pgid(fd);
        }
        None
    }

    fn handle_output(&mut self, message: ActorMessage) {
        match message {
            ActorMessage::Output(bytes) => match self.output.ingest(&bytes) {
                Ok(current_working_directory) => {
                    // Stamped for *any* output, before the branches below: this
                    // is the definition of session activity the rail orders by,
                    // and it must not depend on the session having an event id
                    // or on the summarizer being wired up.
                    self.last_activity_ms
                        .store(now_unix_millis(), Ordering::Relaxed);
                    match current_working_directory {
                        // bash reports its cwd via OSC 7 (the injected
                        // PROMPT_COMMAND hook), so apply it directly. Mark the
                        // shell as OSC 7-capable so we stop OS-polling for it.
                        Some(reported) => {
                            self.shell_reports_cwd = true;
                            self.apply_cwd(reported);
                        }
                        // zsh, fish, and other shells ignore PROMPT_COMMAND and
                        // never emit OSC 7, so the cwd would otherwise stay stuck
                        // at the daemon's startup directory. Until a session has
                        // proven it emits OSC 7, fall back to reading the PTY
                        // child's cwd from the kernel (throttled). Once OSC 7 has
                        // been seen we trust it and skip polling, so OSC 7-capable
                        // shells don't re-resolve git context during long output.
                        None if !self.shell_reports_cwd => {
                            // Output-driven: re-resolve unconditionally (throttled
                            // by poll_child_cwd) so a same-directory branch switch
                            // — `git switch`/`checkout`, which produces output but
                            // no cwd change — still refreshes the side rail. The
                            // unconditional-resolve cost is bounded here because it
                            // only fires while the shell is actually producing
                            // output; the idle path is the one that dedups.
                            if let Some(cwd) = self.poll_child_cwd() {
                                self.apply_cwd(cwd);
                            }
                        }
                        None => {}
                    }
                    if let Some(session_id) = self.event_session_id.clone() {
                        // Non-blocking nudge to the summarizer; a full or dropped
                        // channel is fine — the debounce loop re-checks on settle.
                        if let Some(dirty_tx) = &self.dirty_tx {
                            let _ = dirty_tx.send(DirtyTick {
                                session_id: session_id.clone(),
                                output_seq: self.output.output_seq,
                            });
                        }
                        self.broadcast(SessionEvent::Output {
                            session_id,
                            output_seq: self.output.output_seq,
                            bytes,
                        });
                    }
                }
                Err(error) => tracing::warn!(error = ?error, "failed to ingest PTY output"),
            },
            ActorMessage::OutputClosed(result) => {
                if let Err(error) = result {
                    tracing::warn!(error = ?error, "PTY output reader closed with error");
                }
                self.output_closed = true;
                self.mark_exited();
                self.broadcast_exit();
            }
        }
    }

    fn handle_command(
        &mut self,
        command: ActorCommand,
        command_rx: &Receiver<ActorCommand>,
        output_rx: &Receiver<ActorMessage>,
    ) -> bool {
        match command {
            ActorCommand::WriteInput { bytes, response } => {
                let _ = response.send(self.write_input(&bytes));
                false
            }
            ActorCommand::Resize { size, response } => {
                let _ = response.send(self.resize(size));
                false
            }
            ActorCommand::Snapshot { response } => {
                let _ = response.send(Ok(self.snapshot_with_history()));
                false
            }
            ActorCommand::SummaryRows { response } => {
                let rows = visible_rows(&self.output.terminal);
                let _ = response.send(Ok((rows, self.output.output_seq, self.context.clone())));
                false
            }
            ActorCommand::Context { response } => {
                let _ = response.send(Ok(self.context.clone()));
                false
            }
            ActorCommand::StyledRows {
                start,
                end,
                response,
            } => {
                let _ = response.send(self.styled_rows(start, end));
                false
            }
            ActorCommand::SubscribeEvents {
                after_event_seq,
                response,
            } => {
                let _ = response.send(self.subscribe_events(after_event_seq));
                false
            }
            #[cfg(test)]
            ActorCommand::SubscriberCount { response } => {
                self.flush_subscribers();
                let _ = response.send(Ok(self.subscribers.len()));
                false
            }
            ActorCommand::BroadcastEvent { event, response } => {
                self.broadcast(*event);
                let _ = response.send(Ok(()));
                false
            }
            ActorCommand::Shutdown { response } => {
                let _ = response.send(self.shutdown(command_rx, output_rx));
                true
            }
            #[cfg(unix)]
            ActorCommand::ExtractHandoverState { response } => {
                let _ = response.send(self.extract_handover_state());
                false
            }
        }
    }

    fn write_input(&mut self, bytes: &[u8]) -> Result<()> {
        ensure!(!self.exited, "session has already exited");
        let mut writer = self
            .writer
            .lock()
            .map_err(|_| anyhow!("PTY writer lock poisoned"))?;
        writer.write_all(bytes).context("writing input to PTY")?;
        writer.flush().context("flushing PTY input")?;
        Ok(())
    }

    fn resize(&mut self, size: SessionSize) -> Result<SessionSnapshot> {
        size.validate()?;
        self.master
            .resize(pty_size(&size))
            .context("resizing PTY")?;
        self.output.reflow_from_log(&size, self.writer.clone())?;
        self.size = size;
        let snapshot = self.snapshot();
        if let Some(session_id) = self.event_session_id.clone() {
            self.broadcast(SessionEvent::Snapshot {
                session_id,
                snapshot: snapshot.clone(),
            });
        }
        Ok(snapshot)
    }

    fn snapshot(&self) -> SessionSnapshot {
        snapshot_from_output(
            &self.output,
            &self.size,
            self.current_working_directory.clone(),
            self.context.clone(),
            self.exited,
        )
    }

    /// A snapshot carrying the raw output-history tail for client-side
    /// re-emulation (attach / resync / explicit snapshot). Resize broadcasts use
    /// the plain [`Self::snapshot`] so they never carry history.
    fn snapshot_with_history(&self) -> SessionSnapshot {
        overlay_raw_output_history(self.snapshot(), &self.log_path, self.output.bytes_logged)
    }

    fn styled_rows(&self, start: usize, end: usize) -> Result<StyledRowsResponse> {
        ensure!(start <= end, "styled row start must be before end");
        let row_count = self.output.terminal.screen().scrollback_rows();
        ensure!(
            end <= row_count,
            "styled row range {start}..{end} exceeds retained row count {row_count}"
        );
        Ok(StyledRowsResponse {
            output_seq: self.output.output_seq,
            start,
            rows: styled_visible_rows_for_range(&self.output.terminal, start, end),
        })
    }

    fn shutdown(
        &mut self,
        command_rx: &Receiver<ActorCommand>,
        output_rx: &Receiver<ActorMessage>,
    ) -> Result<CompletedSession> {
        if !self.exited {
            self.reap_child();
            if !self.exited {
                // Logged here rather than at the exit broadcast: killing the
                // child closes the PTY, and the resulting EOF usually broadcasts
                // the exit from `drain_shutdown_output` before this function
                // reaches its own broadcast, which therefore cannot report the
                // cause. Correlate with `session child is gone` by session_id.
                if let Some(session_id) = self.event_session_id.as_ref() {
                    tracing::info!(session_id = %session_id, "killing session child");
                }
                self.child.kill().context("terminating PTY child")?;
                self.exited = true;
            }
        }
        self.drain_shutdown_output(command_rx, output_rx);
        self.reap_child();
        self.output.log.flush().context("flushing session log")?;

        let completed = self.completed_session();
        self.broadcast_completed(completed.clone());

        Ok(completed)
    }

    fn subscribe_events(&mut self, after_event_seq: Option<u64>) -> Result<SessionEventReceiver> {
        ensure!(
            self.event_session_id.is_some(),
            "session actor was not configured for event fan-out"
        );
        let (tx, rx) = mpsc::sync_channel(EVENT_SUBSCRIBER_BUFFER);
        let next_event_seq = after_event_seq
            .map(|event_seq| event_seq.saturating_add(1))
            .unwrap_or(self.next_event_seq);
        self.subscribers
            .push(EventSubscriber { tx, next_event_seq });
        self.flush_subscribers();
        Ok(rx)
    }

    fn broadcast(&mut self, event: SessionEvent) {
        self.record_event(event);
        self.flush_subscribers();
    }

    fn record_event(&mut self, event: SessionEvent) {
        let envelope = SessionEventEnvelope {
            event_seq: self.next_event_seq,
            event,
        };
        self.next_event_seq += 1;
        self.event_log.push_back(envelope);
        while self.event_log.len() > EVENT_REPLAY_BUFFER {
            self.event_log.pop_front();
        }
    }

    fn flush_subscribers(&mut self) {
        let mut retained = Vec::with_capacity(self.subscribers.len());
        let mut subscribers = std::mem::take(&mut self.subscribers);

        for mut subscriber in subscribers.drain(..) {
            if self.flush_subscriber(&mut subscriber) {
                retained.push(subscriber);
            }
        }

        self.subscribers = retained;
    }

    fn flush_subscriber(&self, subscriber: &mut EventSubscriber) -> bool {
        loop {
            if subscriber.next_event_seq >= self.next_event_seq {
                return true;
            }

            let Some(oldest_event_seq) = self.event_log.front().map(|event| event.event_seq) else {
                return true;
            };

            if subscriber.next_event_seq < oldest_event_seq {
                let resync = self.resync_envelope();
                return match subscriber.tx.try_send(resync) {
                    Ok(()) => {
                        subscriber.next_event_seq = self.next_event_seq;
                        true
                    }
                    Err(TrySendError::Full(_)) => true,
                    Err(TrySendError::Disconnected(_)) => false,
                };
            }

            let event_index = (subscriber.next_event_seq - oldest_event_seq) as usize;
            let Some(envelope) = self.event_log.get(event_index).cloned() else {
                return true;
            };

            match subscriber.tx.try_send(envelope) {
                Ok(()) => subscriber.next_event_seq += 1,
                Err(TrySendError::Full(_)) => return true,
                Err(TrySendError::Disconnected(_)) => return false,
            }
        }
    }

    fn resync_envelope(&self) -> SessionEventEnvelope {
        let latest_event_seq = self.next_event_seq.saturating_sub(1);
        let session_id = self
            .event_session_id
            .clone()
            .expect("event fan-out requires session id");
        SessionEventEnvelope {
            event_seq: latest_event_seq,
            event: SessionEvent::ResyncRequired {
                session_id,
                latest_event_seq,
                snapshot: self.snapshot_with_history(),
            },
        }
    }

    fn broadcast_exit(&mut self) {
        if !self.exited || self.exit_broadcasted {
            return;
        }

        self.broadcast_completed(self.completed_session());
    }

    fn broadcast_completed(&mut self, completed: CompletedSession) {
        if self.exit_broadcasted {
            return;
        }

        if let Some(session_id) = self.event_session_id.clone() {
            tracing::info!(session_id = %session_id, "session child is gone");
            self.broadcast(SessionEvent::Exited {
                session_id,
                completed,
            });
        }
        self.exit_broadcasted = true;
    }

    fn completed_session(&self) -> CompletedSession {
        CompletedSession {
            output_seq: self.output.output_seq,
            bytes_logged: self.output.bytes_logged,
            visible_rows: visible_rows(&self.output.terminal),
        }
    }

    fn mark_exited(&mut self) {
        if self.exited {
            return;
        }

        self.reap_child();
    }

    fn reap_child(&mut self) {
        match self.child.try_wait() {
            Ok(Some(_)) => self.exited = true,
            Ok(None) => {}
            Err(error) => tracing::warn!(error = ?error, "failed polling PTY child"),
        }
    }

    fn drain_shutdown_output(
        &mut self,
        command_rx: &Receiver<ActorCommand>,
        output_rx: &Receiver<ActorMessage>,
    ) {
        let deadline = Instant::now() + Duration::from_secs(2);

        loop {
            while let Ok(command) = command_rx.try_recv() {
                reject_command_during_shutdown(command);
            }

            if self.output_closed {
                break;
            }

            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                tracing::warn!("timed out draining PTY output during shutdown");
                break;
            }

            match output_rx.recv_timeout(remaining) {
                Ok(ActorMessage::Output(bytes)) => {
                    match self.output.ingest(&bytes) {
                        Ok(current_working_directory) => {
                            if let Some(current_working_directory) = current_working_directory {
                                self.context =
                                    resolve_session_context(Some(&current_working_directory));
                                self.current_working_directory = Some(current_working_directory);
                            }
                        }
                        Err(error) => {
                            tracing::warn!(error = ?error, "failed to ingest PTY output during shutdown");
                            continue;
                        }
                    }
                    if let Some(session_id) = self.event_session_id.clone() {
                        self.broadcast(SessionEvent::Output {
                            session_id,
                            output_seq: self.output.output_seq,
                            bytes,
                        });
                    }
                }
                Ok(ActorMessage::OutputClosed(result)) => {
                    if let Err(error) = result {
                        tracing::warn!(error = ?error, "PTY output reader closed with error");
                    }
                    self.output_closed = true;
                    self.exited = true;
                    self.broadcast_exit();
                    break;
                }
                Err(RecvTimeoutError::Timeout) => break,
                Err(RecvTimeoutError::Disconnected) => {
                    self.output_closed = true;
                    self.broadcast_exit();
                    break;
                }
            }
        }
    }
}

fn translate_newlines(bytes: &[u8]) -> std::borrow::Cow<'_, [u8]> {
    let mut last = 0;
    let mut needs_translation = false;
    let mut bare_lf_count = 0;
    for &byte in bytes {
        if byte == b'\n' && last != b'\r' {
            needs_translation = true;
            bare_lf_count += 1;
        }
        last = byte;
    }

    if !needs_translation {
        return std::borrow::Cow::Borrowed(bytes);
    }

    let mut result = Vec::with_capacity(bytes.len() + bare_lf_count);
    last = 0;
    for &byte in bytes {
        if byte == b'\n' && last != b'\r' {
            result.push(b'\r');
        }
        result.push(byte);
        last = byte;
    }
    std::borrow::Cow::Owned(result)
}

impl OutputState {
    fn ingest(&mut self, bytes: &[u8]) -> Result<Option<PathBuf>> {
        self.log
            .write_all(bytes)
            .context("writing PTY output log")?;
        self.bytes_logged += bytes.len() as u64;
        self.output_seq += 1;
        self.trim_log_if_oversized();
        if let Some(cache) = &mut self.log_cache {
            if cache.len() + bytes.len() <= 1024 * 1024 {
                cache.extend_from_slice(bytes);
            } else {
                self.log_cache = None;
            }
        }
        let current_working_directory = self.extract_current_working_directory(bytes);
        let translated = translate_newlines(bytes);
        self.terminal.advance_bytes(&translated);
        Ok(current_working_directory)
    }

    /// Trims the log back to [`SESSION_LOG_RETAIN_BYTES`] once it grows past
    /// [`MAX_SESSION_LOG_BYTES`], rebasing `bytes_logged` onto the new length.
    ///
    /// Best-effort: a failure here means the log keeps growing, which is worth a
    /// warning but must not take the session down mid-output.
    fn trim_log_if_oversized(&mut self) {
        if self.trim_disabled || self.bytes_logged <= self.max_log_bytes {
            return;
        }
        let len = match trim_session_log(&self.log_path, self.retain_log_bytes) {
            Ok(len) => len,
            Err(error) => {
                // Give up permanently for this session rather than retrying.
                // `bytes_logged` stays above `max`, so an unconditional retry
                // would re-attempt a multi-megabyte read/write on *every*
                // subsequent chunk of PTY output — turning a full disk into an
                // I/O storm on the actor's hot path. An un-trimmed log is the
                // lesser failure.
                self.trim_disabled = true;
                tracing::warn!(
                    log_path = %self.log_path.display(),
                    ?error,
                    "failed to trim oversized session log; \
                     it will keep growing and no further trims will be attempted"
                );
                return;
            }
        };

        // The trim is already committed to disk, so `bytes_logged` must be
        // rebased onto the new length before anything else can fail — leaving it
        // stale would break the invariant that it equals the file length, and
        // `read_raw_output_tail` would then seek past EOF.
        let dropped = self.bytes_logged.saturating_sub(len);
        self.bytes_logged = len;
        // The cache mirrors the head of the log, so it no longer corresponds to
        // anything on disk once the front is dropped.
        self.log_cache = None;

        // Reposition our own handle to the new end. Not all session logs are
        // opened in append mode — the freshly-created-session path opens a plain
        // `write(true).truncate(true)` handle, which keeps its own offset. Left
        // alone, that offset still points past the now-shorter file and the next
        // write would punch a sparse hole of NUL bytes into the log.
        //
        // A handle that cannot even seek is unusable for this, so fall back to
        // reopening it rather than leaving it parked past the end: disabling
        // future trims alone would not stop the *existing* handle from writing
        // at the stale offset. If the reopen fails too there is nothing left to
        // try — a seek and an open both failing on a file that was just
        // rewritten means the log is gone or the fd is broken, and the next
        // write will surface the real error.
        if let Err(error) = self.log.seek(SeekFrom::End(0)) {
            match OpenOptions::new()
                .read(true)
                .append(true)
                .open(&self.log_path)
            {
                Ok(reopened) => self.log = reopened,
                Err(reopen_error) => {
                    self.trim_disabled = true;
                    tracing::warn!(
                        log_path = %self.log_path.display(),
                        ?error,
                        ?reopen_error,
                        "failed to reposition or reopen session log handle after trimming; \
                         no further trims will be attempted"
                    );
                    return;
                }
            }
        }

        tracing::debug!(
            log_path = %self.log_path.display(),
            dropped_bytes = dropped,
            retained_bytes = len,
            "trimmed oversized session log"
        );
    }

    fn replay(&mut self, bytes: &[u8]) -> Result<Option<PathBuf>> {
        self.bytes_logged += bytes.len() as u64;
        self.output_seq += 1;
        if let Some(cache) = &mut self.log_cache {
            if cache.len() + bytes.len() <= 1024 * 1024 {
                cache.extend_from_slice(bytes);
            } else {
                self.log_cache = None;
            }
        }
        Ok(self.advance_replayed_bytes(bytes))
    }

    /// Replays the trailing `tail` of a log whose full length is `total_len`.
    ///
    /// Used by the adopt and restore paths, which need the emulator rebuilt from
    /// the end of the log but must still report the log's true length: replaying
    /// a truncated tail would otherwise leave `bytes_logged` short of the file
    /// size, and [`read_raw_output_tail`] would then seek to the wrong offset and
    /// hand clients a misaligned history.
    fn replay_tail(&mut self, total_len: u64, tail: &[u8]) -> Result<Option<PathBuf>> {
        let current_working_directory = self.replay(tail)?;
        if total_len != tail.len() as u64 {
            // The cache is only valid as a stand-in for the whole log; it holds
            // the tail alone here, so drop it and let readers go to the file.
            self.log_cache = None;
        }
        self.bytes_logged = total_len;
        Ok(current_working_directory)
    }

    fn reflow_from_log(&mut self, size: &SessionSize, writer: SharedPtyWriter) -> Result<()> {
        let (replay_writer, replay_gate) = replay_gated_pty_writer();
        self.terminal = terminal_with_writer(size, replay_writer);
        self.cwd_sequence_buffer.clear();

        if let Some(cache) = self.log_cache.clone() {
            self.advance_replayed_bytes(&cache);
        } else {
            self.log
                .flush()
                .context("flushing session log before reflow")?;
            // Same bounded read as the adopt and restore paths, so all three
            // agree on how much of a log a replay covers. Trimming keeps logs
            // within `REPLAY_TAIL_CAP`, so this is normally the whole file.
            let (_, replay) = read_replay_tail(&self.log_path)?;
            self.advance_replayed_bytes(&replay);
        }

        let replay_writes = replay_gate.dropped_write_count();
        let replay_flushes = replay_gate.dropped_flush_count();
        self.terminal.advance_bytes(b"\x1b[c");
        replay_gate.wait_for_dropped_activity_quiet_after(replay_writes, replay_flushes)?;
        replay_gate.enable(Box::new(SharedPtyWriterProxy { writer }))?;
        Ok(())
    }

    fn advance_replayed_bytes(&mut self, bytes: &[u8]) -> Option<PathBuf> {
        let current_working_directory = self.extract_current_working_directory(bytes);
        let translated = translate_newlines(bytes);
        self.terminal.advance_bytes(&translated);
        current_working_directory
    }

    fn extract_current_working_directory(&mut self, bytes: &[u8]) -> Option<PathBuf> {
        if self.cwd_sequence_buffer.is_empty() {
            let start = bytes.iter().position(|byte| *byte == 0x1b)?;
            self.cwd_sequence_buffer.extend_from_slice(&bytes[start..]);
        } else {
            self.cwd_sequence_buffer.extend_from_slice(bytes);
        }
        let mut current_working_directory = None;

        while let Some(start) = find_bytes(&self.cwd_sequence_buffer, b"\x1b]7;file://") {
            if start > 0 {
                self.cwd_sequence_buffer.drain(..start);
            }

            let Some(terminator) = find_osc_terminator(&self.cwd_sequence_buffer) else {
                break;
            };
            let payload = &self.cwd_sequence_buffer[b"\x1b]7;file://".len()..terminator];
            if let Some(path) = cwd_from_osc7_payload(payload) {
                current_working_directory = Some(path);
            }

            let drain_to = if self.cwd_sequence_buffer[terminator] == 0x07 {
                terminator + 1
            } else {
                terminator + 2
            };
            self.cwd_sequence_buffer.drain(..drain_to);
        }

        if !self.cwd_sequence_buffer.is_empty()
            && find_bytes(&self.cwd_sequence_buffer, b"\x1b]7;file://").is_none()
        {
            retain_osc_prefix_candidate(&mut self.cwd_sequence_buffer);
        }

        if self.cwd_sequence_buffer.len() > MAX_OSC_BUFFER {
            self.cwd_sequence_buffer.clear();
        }

        current_working_directory
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum LogInitialization {
    Truncate,
    ReplayExisting,
}

/// Session-identity markers that agent CLIs inject into their own environment
/// (here: Claude Code). If `triaged` was itself launched from inside such a
/// session, these leak into the daemon's environment and — because
/// `CommandBuilder::new` seeds the child env from the daemon's — get inherited
/// by every agent it spawns. The spawned agent then sees them and treats itself
/// as a nested *child* session: Claude Code, for one, skips writing a resumable
/// transcript, so the session never appears in `/resume`. Strip them so each
/// spawned agent starts as a fresh top-level session regardless of how
/// `triaged` was started. (User preferences such as `CLAUDE_EFFORT` are
/// deliberately left intact.)
const INHERITED_AGENT_SESSION_ENV: &[&str] = &[
    "CLAUDECODE",
    "CLAUDE_CODE_CHILD_SESSION",
    "CLAUDE_CODE_SESSION_ID",
    "CLAUDE_CODE_ENTRYPOINT",
    "CLAUDE_CODE_EXECPATH",
    "AI_AGENT",
];

/// Remove inherited agent session-identity markers from `command` so the
/// spawned agent does not mistake itself for a nested child session. See
/// [`INHERITED_AGENT_SESSION_ENV`].
fn scrub_inherited_agent_session_env(command: &mut CommandBuilder) {
    for key in INHERITED_AGENT_SESSION_ENV {
        command.env_remove(key);
    }
}

fn spawn_pty_runtime(
    config: SessionConfig,
    log_initialization: LogInitialization,
) -> Result<PtyRuntime> {
    config.validate()?;

    let pty_system = native_pty_system();
    let pair = pty_system
        .openpty(pty_size(&config.size))
        .context("opening PTY")?;

    let mut command = CommandBuilder::new(&config.command);
    for arg in &config.args {
        command.arg(arg);
    }
    if let Some(cwd) = &config.cwd {
        command.cwd(cwd);
    }
    scrub_inherited_agent_session_env(&mut command);
    // Pin TERM/COLORTERM to a standard, widely-supported terminal rather than
    // leaking whatever the daemon launched with. portable_pty doesn't default
    // TERM, so a headless daemon (login service, or one re-exec'd via handover)
    // would otherwise spawn shells with an empty TERM. With no TERM, zsh's ZLE
    // can't load terminfo, can't emit cursor-left to redraw, and renders a
    // backspace as a literal space ("backspace adds a space"). xterm-256color is
    // understood both by the server-side emulator (tattoy_wezterm_term) that
    // ingests this output and by the clients that render the session, so it's the
    // right value regardless of the daemon's own environment. Set after the scrub
    // so these are authoritative.
    command.env("TERM", "xterm-256color");
    command.env("COLORTERM", "truecolor");

    let child = pair
        .slave
        .spawn_command(command)
        .context("spawning PTY child")?;
    drop(pair.slave);

    let reader = pair
        .master
        .try_clone_reader()
        .context("cloning PTY reader")?;
    match log_initialization {
        LogInitialization::Truncate => {
            let writer = shared_pty_writer(pair.master.take_writer().context("taking PTY writer")?);
            let terminal = terminal_with_writer(&config.size, writer.clone());
            let log = OpenOptions::new()
                .create(true)
                .write(true)
                .truncate(true)
                .open(&config.log_path)
                .with_context(|| format!("opening session log {}", config.log_path.display()))?;
            Ok(PtyRuntime {
                master: pair.master,
                child,
                reader,
                writer,
                output: OutputState {
                    log,
                    log_path: config.log_path.clone(),
                    trim_disabled: false,
                    max_log_bytes: MAX_SESSION_LOG_BYTES,
                    retain_log_bytes: SESSION_LOG_RETAIN_BYTES,
                    terminal,
                    cwd_sequence_buffer: Vec::new(),
                    bytes_logged: 0,
                    output_seq: 0,
                    log_cache: Some(Vec::new()),
                },
                size: config.size,
                log_path: config.log_path,
                current_working_directory: None,
            })
        }
        LogInitialization::ReplayExisting => {
            let (writer, replay_gate) = replay_gated_pty_writer();
            let terminal = terminal_with_writer(&config.size, writer.clone());
            let log = OpenOptions::new()
                .create(true)
                .read(true)
                .append(true)
                .open(&config.log_path)
                .with_context(|| format!("opening session log {}", config.log_path.display()))?;
            let mut output = OutputState {
                log: log.try_clone().context("cloning restored session log")?,
                log_path: config.log_path.clone(),
                trim_disabled: false,
                max_log_bytes: MAX_SESSION_LOG_BYTES,
                retain_log_bytes: SESSION_LOG_RETAIN_BYTES,
                terminal,
                cwd_sequence_buffer: Vec::new(),
                bytes_logged: 0,
                output_seq: 0,
                log_cache: Some(Vec::new()),
            };
            let (replay_len, replay) = read_replay_tail(&config.log_path)?;
            let replayed_working_directory = if replay_len == 0 {
                None
            } else {
                output.replay_tail(replay_len, &replay)?
            };
            let current_working_directory =
                restorable_cwd(replayed_working_directory, config.cwd.clone());
            let replay_writes = replay_gate.dropped_write_count();
            let replay_flushes = replay_gate.dropped_flush_count();
            output.terminal.advance_bytes(b"\x1b[c");
            replay_gate.wait_for_dropped_activity_quiet_after(replay_writes, replay_flushes)?;
            replay_gate.enable(pair.master.take_writer().context("taking PTY writer")?)?;
            Ok(PtyRuntime {
                master: pair.master,
                child,
                reader,
                writer,
                output,
                size: config.size,
                log_path: config.log_path,
                current_working_directory,
            })
        }
    }
}

fn output_state_for_log(log_path: &PathBuf, size: SessionSize) -> Result<OutputState> {
    let log = OpenOptions::new()
        .read(true)
        .append(true)
        .open(log_path)
        .with_context(|| format!("opening session log {}", log_path.display()))?;
    Ok(OutputState {
        log,
        log_path: log_path.clone(),
        trim_disabled: false,
        max_log_bytes: MAX_SESSION_LOG_BYTES,
        retain_log_bytes: SESSION_LOG_RETAIN_BYTES,
        terminal: terminal_with_writer(&size, shared_pty_writer(Box::new(std::io::sink()))),
        cwd_sequence_buffer: Vec::new(),
        bytes_logged: 0,
        output_seq: 0,
        log_cache: Some(Vec::new()),
    })
}

fn terminal_with_writer(size: &SessionSize, writer: SharedPtyWriter) -> Terminal {
    Terminal::new(
        terminal_size(size),
        Arc::new(TriageTerminalConfig),
        "Triage",
        env!("CARGO_PKG_VERSION"),
        Box::new(TerminalOutputSink { writer }),
    )
}

fn snapshot_from_output(
    output: &OutputState,
    size: &SessionSize,
    current_working_directory: Option<PathBuf>,
    context: Option<SessionContext>,
    exited: bool,
) -> SessionSnapshot {
    let visible_rows = visible_rows(&output.terminal);
    let styled_rows_start = visible_rows.len().saturating_sub(size.rows);
    SessionSnapshot {
        output_seq: output.output_seq,
        bytes_logged: output.bytes_logged,
        size: size.clone(),
        styled_rows: styled_visible_rows_for_range(
            &output.terminal,
            styled_rows_start,
            visible_rows.len(),
        ),
        styled_rows_start,
        visible_rows,
        cursor: terminal_cursor(&output.terminal),
        current_working_directory,
        context,
        bracketed_paste_enabled: output.terminal.bracketed_paste_enabled(),
        exited,
        // History (raw_output) is attached only on the attach/resync/snapshot
        // paths via `*_with_history`; resize broadcasts carry none.
        raw_output: Vec::new(),
        raw_output_start: 0,
        // Populated by the manager from its snippet cache when a snapshot is
        // returned to a caller; the actor has no access to the cache.
        snippet: None,
        snippet_detail: None,
    }
}

/// Maximum bytes of raw output history carried in a snapshot for client-side
/// re-emulation. Bounded because a repainting TUI (e.g. Claude Code) self-heals
/// its whole viewport within one frame; the Phase 0 spike confirmed a small tail
/// reconstructs the screen exactly (a 64 KiB tail matched full replay). 1 MiB
/// gives generous headroom for full-screen TUIs run inside a session.
const RAW_OUTPUT_TAIL_CAP: u64 = 1024 * 1024;

/// Size at which a live session log is trimmed back to
/// [`SESSION_LOG_RETAIN_BYTES`]. Without this a long-lived session grows without
/// bound — logs of ~100 MB, and gigabytes across a session directory, are what
/// motivated the cap.
const MAX_SESSION_LOG_BYTES: u64 = 16 * 1024 * 1024;

/// Bytes of log kept when [`MAX_SESSION_LOG_BYTES`] is exceeded. The gap between
/// the two bounds is what makes trimming amortised: one rewrite buys
/// `MAX_SESSION_LOG_BYTES - SESSION_LOG_RETAIN_BYTES` of further output.
const SESSION_LOG_RETAIN_BYTES: u64 = 12 * 1024 * 1024;

/// Maximum bytes of a session log replayed through the terminal emulator when a
/// session is adopted, restored, or reflowed after a resize.
///
/// Replay is not just about the visible screen: it also rebuilds terminal
/// *modes* (bracketed paste, alternate screen, cursor-key and charset state) and
/// recovers the OSC 7 working directory, all of which are set early in a session
/// rather than in its tail.
///
/// This is therefore `>= MAX_SESSION_LOG_BYTES`, so replay never discards bytes
/// the log still holds: whatever survives on disk is replayed in full, exactly
/// like the full-file read this replaces. What the cap buys is a ceiling on a
/// legacy log written before trimming existed — 16 MiB of work instead of 100 MB.
///
/// Note what this does *not* promise. Trimming drops the front of the log, so a
/// session that outgrows [`MAX_SESSION_LOG_BYTES`] does lose the early bytes
/// where those modes were set — the loss moves from replay time to trim time,
/// it does not disappear. That is the accepted cost of bounding the log at all;
/// shells and full-screen TUIs re-assert their modes on the next repaint, and
/// `last_known_cwd` outranks the replayed OSC 7 cwd precisely because the replay
/// cannot be relied on to recover it.
const REPLAY_TAIL_CAP: u64 = MAX_SESSION_LOG_BYTES;

// These bounds only work together, so pin their ordering at compile time.
const _: () = assert!(
    SESSION_LOG_RETAIN_BYTES < MAX_SESSION_LOG_BYTES,
    "retaining at least the max would trim on every write"
);
const _: () = assert!(
    REPLAY_TAIL_CAP >= MAX_SESSION_LOG_BYTES,
    "a trimmed log must replay in full, or it loses terminal modes set before the tail"
);
const _: () = assert!(
    REPLAY_TAIL_CAP >= RAW_OUTPUT_TAIL_CAP,
    "replay must rebuild at least as much history as clients can request"
);

/// Overlays the raw output-history tail onto a snapshot for client-side
/// re-emulation. Used by the attach/resync/snapshot paths; the resize broadcast
/// keeps the plain `snapshot()` so it never carries the tail.
fn overlay_raw_output_history(
    mut snapshot: SessionSnapshot,
    log_path: &Path,
    bytes_logged: u64,
) -> SessionSnapshot {
    let (start, raw) = read_raw_output_tail(log_path, bytes_logged, RAW_OUTPUT_TAIL_CAP);
    snapshot.raw_output = raw;
    snapshot.raw_output_start = start;
    snapshot
}

/// Reads the last `cap` bytes of the raw output log, returning the byte offset of
/// the first returned byte (`raw_output_start`) and the bytes. These are the
/// untranslated PTY bytes — byte-identical to the live Output stream — so client
/// history and live writes are consistent and de-duplicate cleanly by
/// `output_seq`. `File` writes are unbuffered, so the on-disk tail is current.
fn read_raw_output_tail(log_path: &Path, bytes_logged: u64, cap: u64) -> (u64, Vec<u8>) {
    if bytes_logged == 0 {
        return (0, Vec::new());
    }
    let start = bytes_logged.saturating_sub(cap);
    let read = (|| -> std::io::Result<Vec<u8>> {
        let mut file = File::open(log_path)?;
        file.seek(SeekFrom::Start(start))?;
        let mut buf = Vec::new();
        file.read_to_end(&mut buf)?;
        Ok(buf)
    })();
    match read {
        Ok(buf) => (start, buf),
        Err(error) => {
            tracing::warn!(
                log_path = %log_path.display(),
                ?error,
                "failed to read raw output tail; sending empty history"
            );
            (0, Vec::new())
        }
    }
}

/// Reads the trailing [`REPLAY_TAIL_CAP`] bytes of a session log for replay,
/// returning the log's full length alongside them.
///
/// The length is the log's true size, not the length of the returned tail: it
/// becomes `bytes_logged`, which must stay equal to the on-disk file length so
/// the absolute offsets in [`read_raw_output_tail`] keep addressing the right
/// bytes.
///
/// Deliberately *not* built on [`read_raw_output_tail`], which reports an
/// unreadable log as empty history. That is the right call when serving a
/// snapshot, but here it would leave `bytes_logged` at zero while the file holds
/// data — silently breaking the invariant above — so I/O errors propagate.
///
/// The offset and the length come from a single open handle rather than a
/// stat-then-reopen pair, which can disagree because a session log is still
/// being written during a handover adoption. The reported length is the read's
/// own end position, clamped to the file's post-read size: `start` is derived
/// from the *pre*-read length, so a log trimmed below it in between would
/// otherwise have this report a length past EOF.
fn read_replay_tail(log_path: &Path) -> Result<(u64, Vec<u8>)> {
    let mut file = File::open(log_path)
        .with_context(|| format!("opening session log {}", log_path.display()))?;
    let len = file
        .metadata()
        .with_context(|| format!("reading session log metadata {}", log_path.display()))?
        .len();
    let start = len.saturating_sub(REPLAY_TAIL_CAP);
    if start > 0 {
        file.seek(SeekFrom::Start(start))
            .with_context(|| format!("seeking session log tail {}", log_path.display()))?;
    }
    let mut tail = Vec::new();
    file.read_to_end(&mut tail)
        .with_context(|| format!("reading session log {}", log_path.display()))?;

    // Clamp to the log's post-read size. `start` was computed from the *pre*-read
    // length, so a log trimmed below it in between (another daemon still owns
    // this session during a handover adoption) leaves the seek past EOF, the read
    // empty, and `start` describing a length the file no longer has. Reporting
    // that would put `bytes_logged` past EOF and send `read_raw_output_tail`
    // seeking beyond the end.
    let after = file
        .metadata()
        .with_context(|| format!("reading session log metadata {}", log_path.display()))?
        .len();
    Ok(((start + tail.len() as u64).min(after), tail))
}

/// Trims the log at `log_path` down to its trailing `retain` bytes, returning
/// the new file length (or the unchanged length if it was already under).
///
/// Rewrites through a *separate* handle on the same inode, because the caller's
/// handle cannot do the job in either of the two forms it takes: the restore and
/// adoption paths open the log with `append(true)`, where writes ignore the seek
/// position and always land at the end, while the fresh-session path opens a
/// plain `write(true).truncate(true)` handle that keeps its own offset. Sharing
/// the inode means the caller keeps its handle, but it *must* reseek it to the
/// end afterwards — the plain handle would otherwise still be positioned past
/// the now-shorter file and punch a sparse hole into it.
///
/// Callers must assign the returned length to `bytes_logged`: the front of the
/// stream is gone, so every absolute offset rebases by the number of bytes
/// dropped. That is safe because `bytes_logged` is never persisted — restore
/// re-derives it from the file — so absolute offsets are already per-daemon-run,
/// and `raw_output_start` only ever reaches a client paired with the
/// `raw_output` it describes.
///
/// The rewrite is not atomic: a crash between the write and the `set_len` leaves
/// the retained tail spliced onto stale bytes, which replays as garbled
/// scrollback. A temp-file-plus-rename would be atomic but would give the file a
/// new inode, breaking the shared-inode contract with the caller's still-open
/// handle — so the in-place rewrite is deliberate, and the next trim repairs the
/// length.
fn trim_session_log(log_path: &Path, retain: u64) -> std::io::Result<u64> {
    // One read/write handle: writes go to the seek position (no `append`), so the
    // same handle can read the tail and then write it back over the front.
    let mut file = OpenOptions::new().read(true).write(true).open(log_path)?;
    let len = file.metadata()?.len();
    if len <= retain {
        return Ok(len);
    }

    file.seek(SeekFrom::Start(len - retain))?;
    let mut tail = Vec::with_capacity(retain as usize);
    file.read_to_end(&mut tail)?;

    // Length comes from what was actually read, never from `retain`. The two
    // agree only if the file was exactly `len` bytes at read time; a log that
    // changed size in between would otherwise be either NUL-extended by
    // `set_len` or truncated past the bytes just written, and the returned
    // length — which the caller assigns to `bytes_logged` — would be a lie.
    let retained = tail.len() as u64;
    file.rewind()?;
    file.write_all(&tail)?;
    file.set_len(retained)?;
    Ok(retained)
}

fn pty_size(size: &SessionSize) -> PtySize {
    PtySize {
        rows: size.rows as u16,
        cols: size.cols as u16,
        pixel_width: size.pixel_width as u16,
        pixel_height: size.pixel_height as u16,
    }
}

fn terminal_size(size: &SessionSize) -> TerminalSize {
    TerminalSize {
        rows: size.rows,
        cols: size.cols,
        pixel_width: size.pixel_width,
        pixel_height: size.pixel_height,
        dpi: size.dpi as u32,
    }
}

fn read_pty_output(mut reader: Box<dyn Read + Send>, tx: SyncSender<ActorMessage>) {
    let mut chunk = [0; 8192];

    loop {
        match reader.read(&mut chunk) {
            Ok(0) => {
                let _ = tx.send(ActorMessage::OutputClosed(Ok(())));
                break;
            }
            Ok(read_len) => {
                if tx
                    .send(ActorMessage::Output(chunk[..read_len].to_vec()))
                    .is_err()
                {
                    break;
                }
            }
            Err(error) if error.kind() == ErrorKind::Interrupted => continue,
            Err(error)
                if matches!(
                    error.kind(),
                    ErrorKind::BrokenPipe | ErrorKind::ConnectionReset | ErrorKind::UnexpectedEof
                ) || is_closed_pty_error(&error) =>
            {
                let _ = tx.send(ActorMessage::OutputClosed(Ok(())));
                break;
            }
            Err(error) => {
                let _ = tx.send(ActorMessage::OutputClosed(
                    Err(error).context("reading PTY output"),
                ));
                break;
            }
        }
    }
}

fn recv_actor_result<T>(rx: Receiver<ActorResult<T>>, context: &'static str) -> Result<T> {
    rx.recv()
        .with_context(|| format!("{context}: actor stopped"))?
        .with_context(|| context)
}

/// Requests a cheap visible-rows snapshot via a cloned actor command channel.
/// The caller clones `tx` while briefly holding the sessions lock, then calls
/// this OFF-LOCK so the actor round-trip never blocks other session operations.
fn request_summary_rows(tx: &Sender<ActorCommand>) -> Result<SummaryRowsResponse> {
    let (resp_tx, resp_rx) = mpsc::channel();
    tx.send(ActorCommand::SummaryRows { response: resp_tx })
        .context("sending session summary-rows command")?;
    recv_actor_result(resp_rx, "reading session summary rows")
}

/// Requests the session's already-resolved git context via a cloned actor
/// command channel. Mirrors [`request_summary_rows`]: clone `tx` under a brief
/// lock, then call this OFF-LOCK so the round-trip never blocks other session
/// operations. Cheap — the actor just clones its cached `SessionContext`; it
/// never re-runs git.
fn request_session_context(tx: &Sender<ActorCommand>) -> Result<Option<SessionContext>> {
    let (resp_tx, resp_rx) = mpsc::channel();
    tx.send(ActorCommand::Context { response: resp_tx })
        .context("sending session context command")?;
    recv_actor_result(resp_rx, "reading session context")
}

/// Requests a full snapshot via a cloned actor command channel. Mirrors
/// [`request_summary_rows`]: clone `tx` under a brief lock, then call this
/// OFF-LOCK so the actor round-trip never blocks other session operations.
fn request_snapshot(tx: &Sender<ActorCommand>) -> Result<SessionSnapshot> {
    let (resp_tx, resp_rx) = mpsc::channel();
    tx.send(ActorCommand::Snapshot { response: resp_tx })
        .context("sending session snapshot command")?;
    recv_actor_result(resp_rx, "reading session snapshot")
}

fn reject_command_during_shutdown(command: ActorCommand) {
    let error = anyhow!("session is shutting down");
    match command {
        ActorCommand::WriteInput { response, .. } => {
            let _ = response.send(Err(error));
        }
        ActorCommand::Resize { response, .. } => {
            let _ = response.send(Err(error));
        }
        ActorCommand::Snapshot { response } => {
            let _ = response.send(Err(error));
        }
        ActorCommand::SummaryRows { response } => {
            let _ = response.send(Err(error));
        }
        ActorCommand::Context { response } => {
            let _ = response.send(Err(error));
        }
        ActorCommand::StyledRows { response, .. } => {
            let _ = response.send(Err(error));
        }
        ActorCommand::SubscribeEvents { response, .. } => {
            let _ = response.send(Err(error));
        }
        #[cfg(test)]
        ActorCommand::SubscriberCount { response } => {
            let _ = response.send(Err(error));
        }
        ActorCommand::BroadcastEvent { response, .. } => {
            let _ = response.send(Err(error));
        }
        ActorCommand::Shutdown { response } => {
            let _ = response.send(Err(error));
        }
        #[cfg(unix)]
        ActorCommand::ExtractHandoverState { response } => {
            let _ = response.send(Err(error));
        }
    }
}

fn join_thread_with_timeout(handle: JoinHandle<()>, name: &'static str) {
    let deadline = Instant::now() + Duration::from_secs(2);

    while !handle.is_finished() {
        if Instant::now() >= deadline {
            tracing::warn!(thread = name, "timed out joining thread");
            return;
        }
        thread::sleep(Duration::from_millis(10));
    }

    if handle.join().is_err() {
        tracing::error!(thread = name, "thread panicked during shutdown");
    }
}

fn shared_pty_writer(writer: Box<dyn Write + Send>) -> SharedPtyWriter {
    Arc::new(Mutex::new(writer))
}

fn replay_gated_pty_writer() -> (SharedPtyWriter, Arc<ReplayGateState>) {
    let state = Arc::new(ReplayGateState {
        live_writer: Mutex::new(None),
        pass_through: AtomicBool::new(false),
        dropped_writes: AtomicU64::new(0),
        dropped_flushes: AtomicU64::new(0),
    });
    let writer = shared_pty_writer(Box::new(ReplayGateWriter {
        state: state.clone(),
    }));
    (writer, state)
}

struct ReplayGateState {
    live_writer: Mutex<Option<Box<dyn Write + Send>>>,
    pass_through: AtomicBool,
    dropped_writes: AtomicU64,
    dropped_flushes: AtomicU64,
}

impl ReplayGateState {
    fn dropped_write_count(&self) -> u64 {
        self.dropped_writes.load(Ordering::SeqCst)
    }

    fn dropped_flush_count(&self) -> u64 {
        self.dropped_flushes.load(Ordering::SeqCst)
    }

    fn wait_for_dropped_activity_quiet_after(
        &self,
        previous_writes: u64,
        previous_flushes: u64,
    ) -> Result<()> {
        let deadline = Instant::now() + Duration::from_secs(5);
        let quiet_period = Duration::from_millis(50);
        let mut last_writes = self.dropped_write_count();
        let mut last_flushes = self.dropped_flush_count();
        let mut saw_activity = last_writes > previous_writes || last_flushes > previous_flushes;
        let mut quiet_since = Instant::now();

        loop {
            let current_writes = self.dropped_write_count();
            let current_flushes = self.dropped_flush_count();
            if current_writes != last_writes || current_flushes != last_flushes {
                last_writes = current_writes;
                last_flushes = current_flushes;
                saw_activity =
                    current_writes > previous_writes || current_flushes > previous_flushes;
                quiet_since = Instant::now();
            }
            if saw_activity && quiet_since.elapsed() >= quiet_period {
                return Ok(());
            }
            ensure!(
                Instant::now() < deadline,
                "timed out draining restored terminal replay replies"
            );
            thread::sleep(Duration::from_millis(10));
        }
    }

    fn enable(&self, writer: Box<dyn Write + Send>) -> Result<()> {
        *self
            .live_writer
            .lock()
            .map_err(|_| anyhow!("PTY writer lock poisoned"))? = Some(writer);
        self.pass_through.store(true, Ordering::SeqCst);
        Ok(())
    }
}

struct ReplayGateWriter {
    state: Arc<ReplayGateState>,
}

struct SharedPtyWriterProxy {
    writer: SharedPtyWriter,
}

impl Write for SharedPtyWriterProxy {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.writer
            .lock()
            .map_err(|_| std::io::Error::other("PTY writer lock poisoned"))?
            .write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.writer
            .lock()
            .map_err(|_| std::io::Error::other("PTY writer lock poisoned"))?
            .flush()
    }
}

impl Write for ReplayGateWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        if !self.state.pass_through.load(Ordering::SeqCst) {
            self.state.dropped_writes.fetch_add(1, Ordering::SeqCst);
            return Ok(buf.len());
        }
        let mut live_writer = self
            .state
            .live_writer
            .lock()
            .map_err(|_| std::io::Error::other("PTY writer lock poisoned"))?;
        let live_writer = live_writer
            .as_mut()
            .ok_or_else(|| std::io::Error::other("PTY writer is not installed"))?;
        live_writer.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        if !self.state.pass_through.load(Ordering::SeqCst) {
            self.state.dropped_flushes.fetch_add(1, Ordering::SeqCst);
            return Ok(());
        }
        let mut live_writer = self
            .state
            .live_writer
            .lock()
            .map_err(|_| std::io::Error::other("PTY writer lock poisoned"))?;
        let live_writer = live_writer
            .as_mut()
            .ok_or_else(|| std::io::Error::other("PTY writer is not installed"))?;
        live_writer.flush()
    }
}

/// Minimum interval between OS-level working-directory polls. Bounds how often
/// [`ActorState::apply_cwd`] (which shells out to `git`) runs for sessions whose
/// shell does not emit OSC 7.
const CWD_POLL_INTERVAL: Duration = Duration::from_millis(750);

/// Reads the working directory of `pid` directly from the kernel.
///
/// Triage tracks each session's cwd from the OSC 7 sequence emitted by the
/// injected `PROMPT_COMMAND` hook, but `PROMPT_COMMAND` is a bash feature —
/// zsh, fish, and others ignore it and never report their cwd, leaving the side
/// rail stuck on the daemon's startup directory. Reading the PTY child's cwd
/// from the OS works regardless of the user's shell (the same approach terminal
/// multiplexers use).
#[cfg(target_os = "linux")]
fn child_cwd(pid: u32) -> Option<PathBuf> {
    std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
}

#[cfg(target_os = "macos")]
fn child_cwd(pid: u32) -> Option<PathBuf> {
    use std::os::unix::ffi::OsStringExt;

    // SAFETY: `proc_vnodepathinfo` is a plain-old-data struct; zeroing it is a
    // valid initial state and `proc_pidinfo` fully populates it on success.
    let mut info: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() };
    let size = std::mem::size_of::<libc::proc_vnodepathinfo>() as libc::c_int;
    // SAFETY: `info` is a correctly sized, writable buffer matching the
    // `PROC_PIDVNODEPATHINFO` flavor.
    let written = unsafe {
        libc::proc_pidinfo(
            pid as libc::c_int,
            libc::PROC_PIDVNODEPATHINFO,
            0,
            (&mut info as *mut libc::proc_vnodepathinfo).cast(),
            size,
        )
    };
    if written != size {
        return None;
    }
    // `vip_path` is a NUL-terminated C string stored as a flattened byte buffer.
    let path = &info.pvi_cdir.vip_path;
    let bytes = unsafe {
        std::slice::from_raw_parts(path.as_ptr().cast::<u8>(), std::mem::size_of_val(path))
    };
    let len = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
    if len == 0 {
        return None;
    }
    Some(PathBuf::from(std::ffi::OsString::from_vec(
        bytes[..len].to_vec(),
    )))
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn child_cwd(_pid: u32) -> Option<PathBuf> {
    None
}

fn resolve_session_context(cwd: Option<&PathBuf>) -> Option<SessionContext> {
    let cwd = cwd?;
    let worktree_root = git_path_output(cwd, &["rev-parse", "--show-toplevel"]);
    let repository_root = git_repository_root(cwd).or_else(|| worktree_root.clone());
    let branch = git_output(cwd, &["branch", "--show-current"]).filter(|branch| !branch.is_empty());

    (repository_root.is_some() || worktree_root.is_some() || branch.is_some()).then_some(
        SessionContext {
            repository_root,
            worktree_root,
            branch,
        },
    )
}

fn git_repository_root(cwd: &PathBuf) -> Option<PathBuf> {
    let common_dir = git_path_output(
        cwd,
        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
    )?;
    if common_dir.file_name() == Some(OsStr::new(".git")) {
        return common_dir.parent().map(Path::to_path_buf);
    }
    let mut ancestors = common_dir.ancestors();
    let _worktree_name = ancestors.next()?;
    let worktrees_dir = ancestors.next()?;
    if worktrees_dir.file_name() != Some(OsStr::new("worktrees")) {
        return None;
    }
    let git_dir = ancestors.next()?;
    if git_dir.file_name() != Some(OsStr::new(".git")) {
        return None;
    }
    git_dir.parent().map(Path::to_path_buf)
}

fn git_raw_output(cwd: &PathBuf, args: &[&str]) -> Option<Vec<u8>> {
    let output = Command::new("git")
        .arg("-C")
        .arg(cwd)
        .args(args)
        .output()
        .ok()?;
    output.status.success().then_some(output.stdout)
}

/// Decodes git stdout as UTF-8. Use only for textual fields (e.g. branch
/// names); paths can contain non-UTF-8 bytes and must use `git_path_output`.
fn git_output(cwd: &PathBuf, args: &[&str]) -> Option<String> {
    let value = String::from_utf8(git_raw_output(cwd, args)?).ok()?;
    let value = value.trim().to_string();
    (!value.is_empty()).then_some(value)
}

fn trim_ascii_whitespace(bytes: &[u8]) -> &[u8] {
    let start = bytes
        .iter()
        .position(|b| !b.is_ascii_whitespace())
        .unwrap_or(bytes.len());
    let end = bytes
        .iter()
        .rposition(|b| !b.is_ascii_whitespace())
        .map_or(start, |index| index + 1);
    &bytes[start..end]
}

/// Resolves a path-valued git command without lossy UTF-8 decoding so repos
/// whose path contains non-UTF-8 bytes still produce a usable `PathBuf`.
#[cfg(unix)]
fn git_path_output(cwd: &PathBuf, args: &[&str]) -> Option<PathBuf> {
    use std::ffi::OsString;

    let bytes = git_raw_output(cwd, args)?;
    let trimmed = trim_ascii_whitespace(&bytes);
    (!trimmed.is_empty()).then(|| PathBuf::from(OsString::from_vec(trimmed.to_vec())))
}

#[cfg(not(unix))]
fn git_path_output(cwd: &PathBuf, args: &[&str]) -> Option<PathBuf> {
    git_output(cwd, args).map(PathBuf::from)
}

struct TerminalOutputSink {
    writer: SharedPtyWriter,
}

impl Write for TerminalOutputSink {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.writer
            .lock()
            .map_err(|_| std::io::Error::other("PTY writer lock poisoned"))?
            .write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.writer
            .lock()
            .map_err(|_| std::io::Error::other("PTY writer lock poisoned"))?
            .flush()
    }
}

#[cfg(unix)]
fn is_closed_pty_error(error: &std::io::Error) -> bool {
    // Linux PTY masters report EIO after the slave side closes.
    error.raw_os_error() == Some(5)
}

#[cfg(not(unix))]
fn is_closed_pty_error(_: &std::io::Error) -> bool {
    false
}

fn visible_rows(terminal: &Terminal) -> Vec<String> {
    let screen = terminal.screen();
    let end = screen.scrollback_rows();

    screen
        .lines_in_phys_range(0..end)
        .iter()
        .map(|line| line.as_str().trim_end().to_owned())
        .collect()
}

#[cfg(test)]
fn styled_visible_rows(terminal: &Terminal) -> Vec<StyledRow> {
    let screen = terminal.screen();
    let end = screen.scrollback_rows();
    styled_visible_rows_for_range(terminal, 0, end)
}

fn styled_visible_rows_for_range(terminal: &Terminal, start: usize, end: usize) -> Vec<StyledRow> {
    let screen = terminal.screen();
    let palette = ColorPalette::default();
    let mut lines = screen.lines_in_phys_range(start..end);

    lines
        .iter_mut()
        .map(|line| {
            let mut spans: Vec<StyledSpan> = Vec::new();
            let mut skip_cells = 0;
            let visible_cols = visible_line_width(&line.as_str());
            let mut col = 0;
            for cell in line.cells_mut() {
                if skip_cells > 0 {
                    skip_cells -= 1;
                    continue;
                }
                let width = cell.width().max(1);
                skip_cells = width.saturating_sub(1);
                let style = terminal_style(cell.attrs(), &palette);
                let text = if col >= visible_cols {
                    " ".repeat(width)
                } else {
                    cell.str().to_string()
                };
                col += width;
                if let Some(span) = spans.last_mut()
                    && span.style == style
                {
                    span.text.push_str(&text);
                    continue;
                }
                spans.push(StyledSpan { text, style });
            }
            StyledRow { spans }
        })
        .collect()
}

fn visible_line_width(line: &str) -> usize {
    UnicodeWidthStr::width(line.trim_end())
}

fn terminal_cursor(terminal: &Terminal) -> TerminalCursor {
    let screen = terminal.screen();
    let cursor = terminal.cursor_pos();
    TerminalCursor {
        row: screen
            .scrollback_rows()
            .saturating_sub(screen.physical_rows)
            + cursor.y.max(0) as usize,
        col: cursor.x,
        visible: matches!(
            cursor.visibility,
            tattoy_wezterm_surface::CursorVisibility::Visible
        ),
    }
}

fn terminal_style(
    attrs: &tattoy_wezterm_term::CellAttributes,
    palette: &ColorPalette,
) -> TerminalStyle {
    TerminalStyle {
        foreground: terminal_color(attrs.foreground(), palette, true),
        background: terminal_color(attrs.background(), palette, false),
        bold: attrs.intensity() == Intensity::Bold,
        dim: attrs.intensity() == Intensity::Half,
        italic: attrs.italic(),
        underline: attrs.underline() != Underline::None,
        reverse: attrs.reverse(),
    }
}

fn terminal_color(
    color: ColorAttribute,
    palette: &ColorPalette,
    foreground: bool,
) -> Option<TerminalColor> {
    if color == ColorAttribute::Default {
        return None;
    }
    let SrgbaTuple(red, green, blue, _) = if foreground {
        palette.resolve_fg(color)
    } else {
        palette.resolve_bg(color)
    };
    Some(TerminalColor {
        red: srgb_component(red),
        green: srgb_component(green),
        blue: srgb_component(blue),
    })
}

fn srgb_component(value: f32) -> u8 {
    (value.clamp(0.0, 1.0) * 255.0).round() as u8
}

fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack
        .windows(needle.len())
        .position(|window| window == needle)
}

fn find_osc_terminator(bytes: &[u8]) -> Option<usize> {
    let mut index = b"\x1b]7;file://".len();
    while index < bytes.len() {
        if bytes[index] == 0x07 {
            return Some(index);
        }
        if bytes[index] == 0x1b && bytes.get(index + 1) == Some(&b'\\') {
            return Some(index);
        }
        index += 1;
    }
    None
}

fn retain_osc_prefix_candidate(buffer: &mut Vec<u8>) {
    let prefix = b"\x1b]7;file://";
    let keep = (1..prefix.len())
        .rev()
        .find(|len| buffer.ends_with(&prefix[..*len]))
        .unwrap_or(0);
    if keep == 0 {
        buffer.clear();
    } else if buffer.len() > keep {
        buffer.drain(..buffer.len() - keep);
    }
}

fn cwd_from_osc7_payload(payload: &[u8]) -> Option<PathBuf> {
    let slash = payload.iter().position(|byte| *byte == b'/')?;
    let path_bytes = percent_decode_uri_path(&payload[slash..])?;
    path_buf_from_uri_path_bytes(path_bytes)
}

#[cfg(unix)]
fn path_buf_from_uri_path_bytes(path_bytes: Vec<u8>) -> Option<PathBuf> {
    Some(std::ffi::OsString::from_vec(path_bytes).into())
}

#[cfg(not(unix))]
fn path_buf_from_uri_path_bytes(path_bytes: Vec<u8>) -> Option<PathBuf> {
    String::from_utf8(path_bytes).ok().map(PathBuf::from)
}

fn percent_decode_uri_path(path: &[u8]) -> Option<Vec<u8>> {
    let mut decoded = Vec::with_capacity(path.len());
    let mut index = 0;
    while index < path.len() {
        if path[index] == b'%' {
            let high = hex_value(*path.get(index + 1)?)?;
            let low = hex_value(*path.get(index + 2)?)?;
            decoded.push((high << 4) | low);
            index += 3;
        } else {
            decoded.push(path[index]);
            index += 1;
        }
    }
    Some(decoded)
}

fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

impl triage_transport_ws::WebSocketAuthenticator for SessionManager {
    fn require_pairing(&self) -> bool {
        self.require_pairing
    }

    fn authenticate(&self, client_id: &ClientId, token: &str) -> Result<bool> {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(token.as_bytes());
        let hash = hex::encode(hasher.finalize());

        let devices = self.paired_devices()?;
        if let Some(stored_hash) = devices.get(client_id) {
            Ok(stored_hash == &hash)
        } else {
            Ok(false)
        }
    }

    fn pairing_challenge(
        &self,
        client_id: &ClientId,
    ) -> Result<triage_transport_ws::PairingChallenge> {
        let challenge = self.request_pairing_challenge(client_id)?;
        Ok(triage_transport_ws::PairingChallenge {
            device_code: challenge.device_code,
            expires_at: challenge.expires_at,
        })
    }

    fn pair(&self, code: &str, client_id: &ClientId) -> Result<String> {
        use rand::Rng;
        use sha2::{Digest, Sha256};

        let normalized = normalize_pairing_code(code);
        {
            let now = Instant::now();
            let mut challenges = self.pairing_challenges()?;
            challenges.retain(|_, challenge| challenge.expires_at > now);

            let device_code = challenges.iter().find_map(|(device_code, challenge)| {
                let pin = challenge.pin.as_ref()?;
                if pin.code == normalized {
                    Some((
                        device_code.clone(),
                        challenge.client_id.clone(),
                        pin.expires_at,
                    ))
                } else {
                    None
                }
            });

            let Some((device_code, paired_client_id, pin_expires_at)) = device_code else {
                bail!("invalid pairing PIN");
            };

            if &paired_client_id != client_id {
                bail!("pairing PIN was issued for a different device");
            }

            if pin_expires_at <= now {
                if let Some(challenge) = challenges.get_mut(&device_code) {
                    challenge.pin = None;
                }
                bail!("pairing PIN has expired");
            }

            challenges.remove(&device_code);
        }

        let mut token_bytes = [0u8; 32];
        rand::thread_rng().fill(&mut token_bytes);
        let token = hex::encode(token_bytes);

        let mut hasher = Sha256::new();
        hasher.update(token.as_bytes());
        let hash = hex::encode(hasher.finalize());

        let mut devices = self.paired_devices()?;
        devices.insert(client_id.clone(), hash);

        save_paired_devices(&self.config.log_dir, &devices)?;

        let pairing_code_path = self.config.log_dir.join("pairing_code.json");
        if pairing_code_path.exists() {
            let _ = fs::remove_file(pairing_code_path);
        }

        Ok(token)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{Duration, Instant};

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn child_cwd_reads_a_live_process_working_directory() {
        // The test process is a live process, so reading its own pid must yield
        // its current working directory — the same shell-agnostic mechanism used
        // to track session cwd when no OSC 7 is emitted.
        let expected = std::env::current_dir().expect("current dir");
        let got = child_cwd(std::process::id()).expect("child_cwd resolves a live pid");
        assert_eq!(
            std::fs::canonicalize(&got).expect("canonicalize got"),
            std::fs::canonicalize(&expected).expect("canonicalize expected"),
        );
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    #[test]
    fn adopted_session_cwd_prefers_the_live_process_over_replay_and_launch() {
        // Regression: a session adopted across a handover whose shell never
        // emits OSC 7 must come back at its *current* cwd, not the launch dir.
        // Model the three candidate sources with three distinct directories and
        // a real live process sitting in the "current" one.
        let base = std::env::temp_dir().join(format!(
            "triage-adopted-cwd-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let live_dir = base.join("live");
        let replayed_dir = base.join("replayed");
        let launch_dir = base.join("launch");
        for dir in [&live_dir, &replayed_dir, &launch_dir] {
            std::fs::create_dir_all(dir).expect("create candidate dir");
        }

        // A long-lived child whose working directory is `live_dir`.
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .current_dir(&live_dir)
            .spawn()
            .expect("spawn live process");
        // Give the kernel a moment to settle the new process's cwd.
        std::thread::sleep(Duration::from_millis(100));

        let resolved = adopted_session_cwd(
            child.id(),
            None,
            Some(replayed_dir.clone()),
            Some(launch_dir.clone()),
        )
        .expect("a cwd is resolved");
        assert_eq!(
            std::fs::canonicalize(&resolved).expect("canonicalize resolved"),
            std::fs::canonicalize(&live_dir).expect("canonicalize live"),
            "the live process cwd must win over replayed/launch cwds",
        );

        // The foreground process group is preferred over the direct child pid:
        // even with a dead `pid` arg, a live `foreground_pgid` resolves the cwd.
        let via_pgid = adopted_session_cwd(
            u32::MAX,
            Some(child.id()),
            Some(replayed_dir.clone()),
            Some(launch_dir.clone()),
        )
        .expect("a cwd is resolved via the foreground pgid");
        assert_eq!(
            std::fs::canonicalize(&via_pgid).expect("canonicalize pgid-resolved"),
            std::fs::canonicalize(&live_dir).expect("canonicalize live"),
            "the foreground process group cwd must be preferred over the pid",
        );

        child.kill().expect("kill live process");
        child.wait().expect("reap live process");

        // When the live read fails we fall back to the replayed cwd (OSC 7 log),
        // then the launch cwd. The helper treats "process exited" and "unknown
        // pid" identically (`child_cwd(pid) == None`), so use a pid that cannot
        // exist rather than the just-reaped one — a recycled pid could belong to
        // an unrelated live process and make this flaky.
        let dead_pid = u32::MAX;
        assert!(
            child_cwd(dead_pid).is_none(),
            "u32::MAX must not map to a live process",
        );
        let fallback = adopted_session_cwd(
            dead_pid,
            None,
            Some(replayed_dir.clone()),
            Some(launch_dir.clone()),
        )
        .expect("a fallback cwd is resolved");
        assert_eq!(
            std::fs::canonicalize(&fallback).expect("canonicalize fallback"),
            std::fs::canonicalize(&replayed_dir).expect("canonicalize replayed"),
            "with no live process, the replayed cwd is the next-best source",
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn scrub_removes_inherited_agent_session_markers() {
        let mut command = CommandBuilder::new("claude");
        // Simulate a daemon environment polluted by a parent Claude Code
        // session (e.g. triaged launched from inside `claude`).
        command.env("CLAUDECODE", "1");
        command.env("CLAUDE_CODE_CHILD_SESSION", "1");
        command.env("CLAUDE_CODE_SESSION_ID", "stale-session-id");
        command.env("CLAUDE_EFFORT", "high");

        scrub_inherited_agent_session_env(&mut command);

        for key in INHERITED_AGENT_SESSION_ENV {
            assert!(
                command.get_env(key).is_none(),
                "{key} should be scrubbed before spawning the agent"
            );
        }
        // User preferences must survive the scrub.
        assert_eq!(
            command.get_env("CLAUDE_EFFORT"),
            Some(std::ffi::OsStr::new("high"))
        );
    }

    #[test]
    fn output_state_extracts_osc7_working_directory() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        assert!(
            output
                .ingest(b"\x1b]7;file://host/tmp/tria")
                .unwrap()
                .is_none()
        );
        let cwd = output.ingest(b"ge\x1b\\").unwrap();

        assert_eq!(cwd, Some(PathBuf::from("/tmp/triage")));
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_tracks_bracketed_paste_mode() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        assert!(!output.terminal.bracketed_paste_enabled());
        output
            .ingest(b"\x1b[?2004h")
            .expect("enable bracketed paste");
        assert!(output.terminal.bracketed_paste_enabled());
        output
            .ingest(b"\x1b[?2004l")
            .expect("disable bracketed paste");
        assert!(!output.terminal.bracketed_paste_enabled());
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_skips_cwd_scan_when_chunk_has_no_escape() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        let cwd = output
            .ingest(b"plain output without control bytes")
            .unwrap();

        assert_eq!(cwd, None);
        assert!(output.cwd_sequence_buffer.is_empty());
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_preserves_split_osc7_prefix_candidate() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        assert!(output.ingest(b"noise\x1b]7;file").unwrap().is_none());
        let cwd = output.ingest(b"://host/tmp/split\x07").unwrap();

        assert_eq!(cwd, Some(PathBuf::from("/tmp/split")));
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_decodes_osc7_percent_encoded_working_directory() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        let cwd = output
            .ingest(b"\x1b]7;file://host/tmp/a%20b/%23hash%25\x07")
            .unwrap();

        assert_eq!(cwd, Some(PathBuf::from("/tmp/a b/#hash%")));
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    #[cfg(unix)]
    fn output_state_preserves_non_utf8_percent_encoded_working_directory() {
        use std::os::unix::ffi::OsStrExt;

        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        let cwd = output.ingest(b"\x1b]7;file://host/tmp/%FF\x07").unwrap();

        assert_eq!(
            cwd.as_ref().expect("cwd").as_os_str().as_bytes(),
            b"/tmp/\xFF"
        );
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_ignores_malformed_osc7_percent_encoding() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        let cwd = output.ingest(b"\x1b]7;file://host/tmp/a%2x\x07").unwrap();

        assert_eq!(cwd, None);
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_bounds_unterminated_osc7_working_directory() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        output
            .ingest(b"\x1b]7;file://host/")
            .expect("ingest partial OSC 7");
        output
            .ingest(&vec![b'a'; MAX_OSC_BUFFER * 2])
            .expect("ingest unterminated OSC 7 payload");

        assert!(output.cwd_sequence_buffer.is_empty());
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_recovers_after_aborting_overlong_osc7_working_directory() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        output
            .ingest(b"\x1b]7;file://host/")
            .expect("ingest partial OSC 7");
        output
            .ingest(&vec![b'a'; MAX_OSC_BUFFER * 2])
            .expect("ingest overlong unterminated OSC 7 payload");

        let cwd = output
            .ingest(b"\x1b]7;file://host/tmp/recovered\x07")
            .expect("ingest next OSC 7");

        assert_eq!(cwd, Some(PathBuf::from("/tmp/recovered")));
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn styled_rows_preserve_foreground_color() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        output
            .ingest(b"\x1b[31mred\x1b[0m plain")
            .expect("ingest styled output");
        let rows = styled_visible_rows(&output.terminal);
        let red_span = rows
            .iter()
            .flat_map(|row| &row.spans)
            .find(|span| span.text.contains("red"))
            .expect("red span");

        assert!(red_span.style.foreground.is_some());
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn styled_rows_preserve_dim_intensity() {
        let log_path = unique_log_path();
        let mut output = test_output_state(&log_path, SessionSize::default());

        output
            .ingest(b"\x1b[2mhint\x1b[0m")
            .expect("ingest dim output");
        let rows = styled_visible_rows(&output.terminal);
        let dim_span = rows
            .iter()
            .flat_map(|row| &row.spans)
            .find(|span| span.text.contains("hint"))
            .expect("dim span");

        assert!(dim_span.style.dim);
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn visible_rows_include_retained_scrollback() {
        let log_path = unique_log_path();
        let mut output = test_output_state(
            &log_path,
            SessionSize {
                rows: 3,
                cols: 24,
                pixel_width: 240,
                pixel_height: 60,
                dpi: 96,
            },
        );

        output
            .ingest(b"line-1\r\nline-2\r\nline-3\r\nline-4\r\nline-5")
            .expect("ingest scrollback output");
        let rows = visible_rows(&output.terminal);

        assert!(
            rows.iter().any(|row| row.contains("line-1")),
            "scrollback rows should include line-1: {rows:?}"
        );
        assert!(
            rows.iter().any(|row| row.contains("line-5")),
            "scrollback rows should include line-5: {rows:?}"
        );
        assert!(rows.len() > output.terminal.screen().physical_rows);
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_reflows_log_at_resized_width() {
        let log_path = unique_log_path();
        let narrow = SessionSize {
            rows: 6,
            cols: 12,
            pixel_width: 120,
            pixel_height: 120,
            dpi: 96,
        };
        let wide = SessionSize {
            rows: 6,
            cols: 80,
            pixel_width: 800,
            pixel_height: 120,
            dpi: 96,
        };
        let long_line = "0123456789abcdefghijklmnopqrstuvwxyz";
        let mut output = test_output_state(&log_path, narrow);

        output
            .ingest(long_line.as_bytes())
            .expect("ingest long line");
        let bytes_logged = output.bytes_logged;
        let output_seq = output.output_seq;
        let narrow_rows = visible_rows(&output.terminal);
        assert!(
            !narrow_rows.iter().any(|row| row == long_line),
            "narrow terminal should soft-wrap the long line: {narrow_rows:?}"
        );

        output
            .reflow_from_log(&wide, shared_pty_writer(Box::new(std::io::sink())))
            .expect("reflow log");

        let wide_rows = visible_rows(&output.terminal);
        assert!(
            wide_rows.iter().any(|row| row == long_line),
            "wide terminal should replay the log without narrow wrapping: {wide_rows:?}"
        );
        assert_eq!(output.bytes_logged, bytes_logged);
        assert_eq!(output.output_seq, output_seq);
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn output_state_reflow_suppresses_historical_terminal_replies() {
        let log_path = unique_log_path();
        let captured = Arc::new(Mutex::new(Vec::new()));
        let writer = shared_pty_writer(Box::new(RecordingWriter {
            bytes: captured.clone(),
        }));
        let mut output = test_output_state(&log_path, SessionSize::default());

        output.ingest(b"\x1b[6n").expect("ingest cursor query");
        captured.lock().expect("captured writer lock").clear();

        output
            .reflow_from_log(&SessionSize::default(), writer)
            .expect("reflow log");
        assert!(
            captured.lock().expect("captured writer lock").is_empty(),
            "historical reflow should not write terminal replies to the live PTY"
        );
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn styled_rows_can_be_limited_to_current_viewport() {
        let log_path = unique_log_path();
        let mut output = test_output_state(
            &log_path,
            SessionSize {
                rows: 3,
                cols: 24,
                pixel_width: 240,
                pixel_height: 60,
                dpi: 96,
            },
        );

        output
            .ingest(b"\x1b[31mline-1\r\nline-2\r\nline-3\r\nline-4\r\nline-5\x1b[0m")
            .expect("ingest scrollback output");
        let row_count = output.terminal.screen().scrollback_rows();
        let styled_start = row_count.saturating_sub(output.terminal.screen().physical_rows);
        let rows = styled_visible_rows_for_range(&output.terminal, styled_start, row_count);

        assert_eq!(rows.len(), output.terminal.screen().physical_rows);
        assert!(
            rows.iter()
                .flat_map(|row| &row.spans)
                .any(|span| span.text.contains("line-5"))
        );
        assert!(
            rows.iter()
                .flat_map(|row| &row.spans)
                .all(|span| !span.text.contains("line-1"))
        );
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn styled_rows_response_extracts_requested_history_range() {
        let log_path = unique_log_path();
        let mut config = command_that_prints_marker(log_path.clone());
        config.size = SessionSize {
            rows: 2,
            cols: 24,
            pixel_width: 240,
            pixel_height: 40,
            dpi: 96,
        };
        let actor = SessionActor::spawn(config).expect("spawn session actor");
        let snapshot = wait_for_visible_marker(&actor, "triage-ready");
        let end = snapshot.visible_rows.len().min(2);
        let response = actor.styled_rows(0, end).expect("load styled rows");

        assert_eq!(response.output_seq, snapshot.output_seq);
        assert_eq!(response.start, 0);
        assert_eq!(response.rows.len(), end);
        actor.shutdown().expect("shutdown session actor");
        let _ = std::fs::remove_file(log_path);
    }

    // Regression: a spawned shell must see TERM=xterm-256color regardless of the
    // daemon's own environment. A headless daemon has an empty TERM, which left
    // zsh unable to redraw on backspace (it rendered a backspace as a space). We
    // pin TERM on the spawned command, so the shell reports it back here.
    #[cfg(not(windows))]
    #[test]
    fn spawned_session_pins_term_for_the_client_emulator() {
        let log_path = unique_log_path();
        let mut config = SessionConfig::new("/bin/sh", log_path.clone());
        // Print TERM with a delimiter so the assertion can't match a substring of
        // some other value; run via the shell so $TERM is expanded by the child.
        config.args = vec![
            "-c".to_string(),
            "printf 'TERM=<%s>\\r\\n' \"$TERM\"".to_string(),
        ];
        let actor = SessionActor::spawn(config).expect("spawn session actor");
        wait_for_visible_marker(&actor, "TERM=<xterm-256color>");
        actor.shutdown().expect("shutdown session actor");
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn session_snapshot_styles_only_current_viewport() {
        let log_path = unique_log_path();
        let actor = SessionActor::spawn(command_that_prints_marker(log_path.clone()))
            .expect("spawn session actor");
        let snapshot = wait_for_visible_marker(&actor, "triage-ready");

        assert!(snapshot.styled_rows.len() <= snapshot.size.rows);
        assert_eq!(
            snapshot.styled_rows_start,
            snapshot
                .visible_rows
                .len()
                .saturating_sub(snapshot.size.rows)
        );
        actor.shutdown().expect("shutdown session actor");
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn session_context_discovers_git_worktree_branch_and_root() {
        let repo = unique_log_dir();
        let _ = std::fs::remove_dir_all(&repo);
        std::fs::create_dir_all(repo.join("nested")).expect("create nested repo dir");
        git_test_command(&repo, &["init"]);
        git_test_command(&repo, &["checkout", "-b", "feature/context"]);

        let context =
            resolve_session_context(Some(&repo.join("nested"))).expect("git session context");

        // git normalizes its reported toplevel (macOS resolves the /var ->
        // /private/var symlink; Windows expands 8.3 names and uses forward
        // slashes), so compare canonicalized paths rather than the raw
        // temp-dir path.
        let canonical = |path: &std::path::Path| {
            std::fs::canonicalize(path).expect("canonicalize path for comparison")
        };
        let expected = Some(canonical(&repo));
        assert_eq!(context.repository_root.as_deref().map(canonical), expected);
        assert_eq!(context.worktree_root.as_deref().map(canonical), expected);
        assert_eq!(context.branch.as_deref(), Some("feature/context"));
        let _ = std::fs::remove_dir_all(repo);
    }

    #[test]
    fn session_context_distinguishes_repository_root_from_linked_worktree() {
        let repo = unique_log_dir();
        let worktree = repo.with_extension("worktree");
        let _ = std::fs::remove_dir_all(&repo);
        let _ = std::fs::remove_dir_all(&worktree);
        std::fs::create_dir_all(&repo).expect("create repo dir");
        git_test_command(&repo, &["init"]);
        git_test_command(&repo, &["config", "user.email", "triage@example.invalid"]);
        git_test_command(&repo, &["config", "user.name", "Triage Test"]);
        std::fs::write(repo.join("README.md"), "test\n").expect("write test file");
        git_test_command(&repo, &["add", "README.md"]);
        git_test_command(&repo, &["commit", "-m", "initial"]);
        git_test_command(
            &repo,
            &[
                "worktree",
                "add",
                "-b",
                "feature/context-worktree",
                worktree.to_str().expect("utf-8 worktree path"),
            ],
        );
        std::fs::create_dir_all(worktree.join("nested")).expect("create nested worktree dir");

        let context =
            resolve_session_context(Some(&worktree.join("nested"))).expect("git session context");

        let canonical = |path: &std::path::Path| {
            std::fs::canonicalize(path).expect("canonicalize path for comparison")
        };
        assert_eq!(
            context.repository_root.as_deref().map(canonical),
            Some(canonical(&repo))
        );
        assert_eq!(
            context.worktree_root.as_deref().map(canonical),
            Some(canonical(&worktree))
        );
        assert_eq!(context.branch.as_deref(), Some("feature/context-worktree"));
        let _ = std::fs::remove_dir_all(worktree);
        let _ = std::fs::remove_dir_all(repo);
    }

    #[test]
    fn session_context_reports_submodule_checkout_as_repository_root() {
        let super_repo = unique_log_dir();
        let submodule_repo = super_repo.with_extension("submodule-src");
        let _ = std::fs::remove_dir_all(&super_repo);
        let _ = std::fs::remove_dir_all(&submodule_repo);
        std::fs::create_dir_all(&super_repo).expect("create super repo dir");
        std::fs::create_dir_all(&submodule_repo).expect("create submodule repo dir");

        git_test_command(&submodule_repo, &["init"]);
        git_test_command(
            &submodule_repo,
            &["config", "user.email", "triage@example.invalid"],
        );
        git_test_command(&submodule_repo, &["config", "user.name", "Triage Test"]);
        std::fs::write(submodule_repo.join("README.md"), "submodule\n")
            .expect("write submodule file");
        git_test_command(&submodule_repo, &["add", "README.md"]);
        git_test_command(&submodule_repo, &["commit", "-m", "initial"]);

        git_test_command(&super_repo, &["init"]);
        git_test_command(
            &super_repo,
            &["config", "user.email", "triage@example.invalid"],
        );
        git_test_command(&super_repo, &["config", "user.name", "Triage Test"]);
        git_test_command(
            &super_repo,
            &[
                "-c",
                "protocol.file.allow=always",
                "submodule",
                "add",
                submodule_repo.to_str().expect("utf-8 submodule repo path"),
                "vendor/submodule",
            ],
        );
        git_test_command(&super_repo, &["commit", "-m", "add submodule"]);
        std::fs::create_dir_all(super_repo.join("vendor/submodule/nested"))
            .expect("create nested submodule dir");

        let submodule_checkout = super_repo.join("vendor/submodule");
        let context = resolve_session_context(Some(&submodule_checkout.join("nested")))
            .expect("git session context");

        let canonical = |path: &std::path::Path| {
            std::fs::canonicalize(path).expect("canonicalize path for comparison")
        };
        let expected = Some(canonical(&submodule_checkout));
        assert_eq!(context.repository_root.as_deref().map(canonical), expected);
        assert_eq!(context.worktree_root.as_deref().map(canonical), expected);
        let _ = std::fs::remove_dir_all(super_repo);
        let _ = std::fs::remove_dir_all(submodule_repo);
    }

    #[test]
    fn session_context_is_absent_outside_git_worktree() {
        let dir = unique_log_dir();
        std::fs::create_dir_all(&dir).expect("create non-git dir");

        assert!(resolve_session_context(Some(&dir)).is_none());
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn test_translate_newlines_direct() {
        use std::borrow::Cow;

        // Empty bytes should remain borrowed and empty
        assert!(matches!(translate_newlines(b""), Cow::Borrowed(b"")));

        // Normal text without bare newlines should remain borrowed
        assert!(matches!(
            translate_newlines(b"hello world"),
            Cow::Borrowed(b"hello world")
        ));
        assert!(matches!(
            translate_newlines(b"hello\r\nworld\r\n"),
            Cow::Borrowed(b"hello\r\nworld\r\n")
        ));

        // Text with a bare newline should be translated to Owned with \r\n
        let translated = translate_newlines(b"hello\nworld");
        assert!(matches!(translated, Cow::Owned(_)));
        assert_eq!(translated.as_ref(), b"hello\r\nworld");

        // Mixed content with both CRLF and bare newlines should translate only bare ones
        let mixed = translate_newlines(b"hello\r\nworld\nagain\r\n");
        assert!(matches!(mixed, Cow::Owned(_)));
        assert_eq!(mixed.as_ref(), b"hello\r\nworld\r\nagain\r\n");
    }

    #[test]
    fn visible_rows_align_raw_bare_line_feed_to_column_0() {
        let log_path = unique_log_path();
        let mut output = test_output_state(
            &log_path,
            SessionSize {
                rows: 4,
                cols: 32,
                pixel_width: 320,
                pixel_height: 80,
                dpi: 96,
            },
        );

        output
            .ingest(b"Nodes: 330\nEdges: 2400\nFiles: 8")
            .expect("ingest bare line feeds");
        let rows = visible_rows(&output.terminal);

        assert!(rows.iter().any(|row| row == "Nodes: 330"));
        assert!(rows.iter().any(|row| row == "Edges: 2400"));
        assert!(rows.iter().any(|row| row == "Files: 8"));
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn translate_newlines_across_chunk_boundaries() {
        let log_path = unique_log_path();
        let mut output = test_output_state(
            &log_path,
            SessionSize {
                rows: 4,
                cols: 32,
                pixel_width: 320,
                pixel_height: 80,
                dpi: 96,
            },
        );

        // First chunk ends with \r
        output.ingest(b"Nodes: 330\r").expect("ingest first chunk");
        // Second chunk starts with \n
        output
            .ingest(b"\nEdges: 2400")
            .expect("ingest second chunk");

        let rows = visible_rows(&output.terminal);
        assert!(rows.iter().any(|row| row == "Nodes: 330"));
        assert!(rows.iter().any(|row| row == "Edges: 2400"));
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn terminal_cursor_uses_scrollback_row_coordinates() {
        let log_path = unique_log_path();
        let mut output = test_output_state(
            &log_path,
            SessionSize {
                rows: 3,
                cols: 24,
                pixel_width: 240,
                pixel_height: 60,
                dpi: 96,
            },
        );

        output
            .ingest(b"line-1\r\nline-2\r\nline-3\r\nline-4\r\nline-5")
            .expect("ingest scrollback output");
        let cursor = terminal_cursor(&output.terminal);

        assert!(
            cursor.row
                >= output
                    .terminal
                    .screen()
                    .scrollback_rows()
                    .saturating_sub(output.terminal.screen().physical_rows),
            "cursor should be positioned within the scrollback-backed row list: {cursor:?}"
        );
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn styled_rows_preserve_trailing_background_cells() {
        let log_path = unique_log_path();
        let mut output = test_output_state(
            &log_path,
            SessionSize {
                rows: 2,
                cols: 12,
                pixel_width: 120,
                pixel_height: 40,
                dpi: 96,
            },
        );

        output
            .ingest(b"\x1b[44mbox    \x1b[0m")
            .expect("ingest background output");
        let rows = styled_visible_rows(&output.terminal);
        let background_span = rows
            .iter()
            .flat_map(|row| &row.spans)
            .find(|span| span.text.contains("box"))
            .expect("background span");

        assert_eq!(background_span.text, "box    ");
        assert!(background_span.style.background.is_some());
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn styled_rows_preserve_clear_to_end_background_cells() {
        let log_path = unique_log_path();
        let mut output = test_output_state(
            &log_path,
            SessionSize {
                rows: 2,
                cols: 12,
                pixel_width: 120,
                pixel_height: 40,
                dpi: 96,
            },
        );

        output
            .ingest(b"\x1b[48;2;32;32;32m\x1b[K")
            .expect("ingest background clear output");
        let rows = styled_visible_rows(&output.terminal);
        let background_span = rows
            .iter()
            .flat_map(|row| &row.spans)
            .find(|span| span.text == "            ")
            .expect("clear-to-end background span");

        assert_eq!(
            background_span.style.background,
            Some(TerminalColor {
                red: 32,
                green: 32,
                blue: 32
            })
        );
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn styled_rows_do_not_keep_submitted_text_after_line_clear() {
        let log_path = unique_log_path();
        let mut output = test_output_state(
            &log_path,
            SessionSize {
                rows: 2,
                cols: 20,
                pixel_width: 200,
                pixel_height: 40,
                dpi: 96,
            },
        );

        output
            .ingest(b"\x1b[48;2;32;32;32msubmitted prompt\r\x1b[2K\x1b[K")
            .expect("ingest cleared submitted prompt");
        let rows = styled_visible_rows(&output.terminal);
        let text = rows
            .iter()
            .flat_map(|row| &row.spans)
            .map(|span| span.text.as_str())
            .collect::<String>();

        assert!(!text.contains("submitted prompt"), "{text:?}");
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    fn visible_line_width_uses_terminal_columns() {
        assert_eq!(visible_line_width("e\u{301} "), 1);
        assert_eq!(visible_line_width("表 "), 2);
    }

    #[test]
    fn terminal_color_queries_are_written_back_to_pty() {
        let log_path = unique_log_path();
        let responses = Arc::new(Mutex::new(Vec::new()));
        let mut output = test_output_state_with_writer(
            &log_path,
            SessionSize::default(),
            Box::new(RecordingWriter {
                bytes: responses.clone(),
            }),
        );

        output
            .ingest(b"\x1b]11;?\x07")
            .expect("ingest background color query");
        let deadline = Instant::now() + Duration::from_secs(2);
        let response = loop {
            let response = responses.lock().expect("response buffer lock").clone();
            if !response.is_empty() || Instant::now() >= deadline {
                break response;
            }
            std::thread::sleep(Duration::from_millis(10));
        };

        assert!(
            std::str::from_utf8(&response)
                .expect("terminal response utf8")
                .contains("]11;"),
            "expected OSC 11 terminal response, got {response:?}"
        );
        let _ = std::fs::remove_file(log_path);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn pty_session_logs_raw_bytes_and_updates_visible_rows() {
        let log_path = unique_log_path();
        let mut config = command_that_prints_marker(log_path.clone());
        config.size = SessionSize {
            rows: 6,
            cols: 32,
            pixel_width: 640,
            pixel_height: 240,
            dpi: 96,
        };

        let completed = PtySession::spawn(config)
            .expect("spawn PTY session")
            .drain_until_exit()
            .expect("drain PTY output");

        let logged = std::fs::read(&log_path).expect("read raw PTY log");
        let _ = std::fs::remove_file(&log_path);

        assert_eq!(completed.bytes_logged, logged.len() as u64);
        assert!(completed.output_seq > 0);
        assert!(
            String::from_utf8_lossy(&logged).contains("triage-ready"),
            "raw PTY output did not contain marker: {:?}",
            logged
        );
        assert!(
            completed
                .visible_rows
                .iter()
                .any(|row| row.contains("triage-ready")),
            "visible rows did not contain marker: {:?}",
            completed.visible_rows
        );
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_actor_accepts_input_resizes_snapshots_and_shuts_down() {
        let log_path = unique_log_path();
        let mut config = long_running_shell(log_path.clone());
        config.size = SessionSize {
            rows: 6,
            cols: 40,
            pixel_width: 800,
            pixel_height: 240,
            dpi: 96,
        };

        let actor = SessionActor::spawn(config).expect("spawn session actor");
        actor
            .write_input(input_that_prints_marker())
            .expect("write PTY input");

        let first = wait_for_visible_marker(&actor, "actor-ready");
        assert!(
            first.output_seq > 0,
            "snapshot should include output sequence after PTY output"
        );
        assert!(
            first.bytes_logged > 0,
            "snapshot should include logged byte count"
        );

        let resized = actor
            .resize(SessionSize {
                rows: 8,
                cols: 48,
                pixel_width: 960,
                pixel_height: 320,
                dpi: 96,
            })
            .expect("resize session actor");
        assert_eq!(resized.size.rows, 8);
        assert_eq!(resized.size.cols, 48);
        assert!(resized.output_seq >= first.output_seq);

        let completed = actor.shutdown().expect("shutdown session actor");
        let logged = std::fs::read(&log_path).expect("read raw PTY log");
        let _ = std::fs::remove_file(&log_path);

        assert_eq!(completed.bytes_logged, logged.len() as u64);
        assert!(completed.output_seq >= first.output_seq);
        assert!(
            String::from_utf8_lossy(&logged).contains("actor-ready"),
            "raw PTY output did not contain actor marker: {:?}",
            logged
        );
        assert!(
            completed
                .visible_rows
                .iter()
                .any(|row| row.contains("actor-ready")),
            "final visible rows did not contain marker: {:?}",
            completed.visible_rows
        );
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_actor_keeps_final_state_after_output_closes() {
        let log_path = unique_log_path();
        let mut config = command_that_prints_marker(log_path.clone());
        config.size = SessionSize {
            rows: 6,
            cols: 32,
            pixel_width: 640,
            pixel_height: 240,
            dpi: 96,
        };

        let actor = SessionActor::spawn(config).expect("spawn session actor");
        let snapshot = wait_for_exited_snapshot(&actor);
        assert!(
            snapshot
                .visible_rows
                .iter()
                .any(|row| row.contains("triage-ready")),
            "snapshot visible rows did not contain marker: {:?}",
            snapshot.visible_rows
        );

        let completed = actor.shutdown().expect("shutdown exited session actor");
        let logged = std::fs::read(&log_path).expect("read raw PTY log");
        let _ = std::fs::remove_file(&log_path);

        assert_eq!(completed.bytes_logged, logged.len() as u64);
        assert_eq!(completed.output_seq, snapshot.output_seq);
        assert!(
            completed
                .visible_rows
                .iter()
                .any(|row| row.contains("triage-ready")),
            "completed visible rows did not contain marker: {:?}",
            completed.visible_rows
        );
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_manager_enforces_input_lease_before_writing() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let mut request = StartSessionRequest::new(long_running_shell_command());
        request.size = SessionSize {
            rows: 6,
            cols: 40,
            pixel_width: 800,
            pixel_height: 240,
            dpi: 96,
        };
        let session_id = manager.start_session(request).expect("start session");
        let observer = ClientId::new("observer").expect("observer id");
        let local_tui = ClientId::new("local-tui").expect("local tui id");
        let remote_agent = ClientId::new("remote-agent").expect("remote agent id");

        let observed = manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: observer.clone(),
                mode: triage_core::session::AttachMode::Observer,
            })
            .expect("attach observer");
        assert!(observed.lease.holder.is_none());
        assert!(
            manager
                .write_input(WriteInputRequest {
                    session_id: session_id.clone(),
                    client_id: observer,
                    bytes: input_that_prints_marker(),
                })
                .is_err(),
            "observer should not be allowed to write PTY input"
        );

        let controlled = manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: local_tui.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach controller");
        assert_eq!(
            controlled.lease.holder.as_ref().unwrap().client_id,
            local_tui
        );
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id: local_tui.clone(),
                bytes: input_that_prints_marker(),
            })
            .expect("controller writes input");
        let first = wait_for_manager_marker(&manager, session_id.clone(), "actor-ready");
        assert!(first.output_seq > 0);

        let takeover = manager
            .acquire_input_lease(InputLeaseRequest {
                session_id: session_id.clone(),
                client_id: remote_agent.clone(),
                kind: triage_core::session::InputControllerKind::Agent,
            })
            .expect("agent takes lease");
        assert_eq!(takeover.previous.unwrap().client_id, local_tui);
        assert!(
            manager
                .write_input(WriteInputRequest {
                    session_id: session_id.clone(),
                    client_id: local_tui,
                    bytes: input_that_prints_marker(),
                })
                .is_err(),
            "previous holder should not be allowed to write after takeover"
        );

        manager
            .release_input_lease(session_id.clone(), remote_agent.clone())
            .expect("release agent lease");
        assert!(
            manager
                .write_input(WriteInputRequest {
                    session_id: session_id.clone(),
                    client_id: remote_agent,
                    bytes: input_that_prints_marker(),
                })
                .is_err(),
            "released holder should not be allowed to write"
        );

        // Read the log before shutting down: shutdown removes the session from
        // the manifest and reclaims its log, so it is gone afterwards.
        let log_path = log_dir.join(format!("{session_id}.log"));
        let logged = std::fs::read(&log_path).expect("read managed session log");
        let completed = manager
            .shutdown_session(session_id.clone())
            .expect("shutdown managed session");
        assert!(
            !log_path.exists(),
            "shutdown must reclaim the session log; an unreferenced log is leaked disk"
        );
        let _ = std::fs::remove_dir_all(&log_dir);

        assert_eq!(completed.bytes_logged, logged.len() as u64);
        assert!(
            String::from_utf8_lossy(&logged).contains("actor-ready"),
            "managed PTY log did not contain marker: {:?}",
            logged
        );
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_manager_lists_running_sessions() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let mut request = StartSessionRequest::new(long_running_shell_command());
        request.size = SessionSize {
            rows: 6,
            cols: 40,
            pixel_width: 800,
            pixel_height: 240,
            dpi: 96,
        };
        let session_id = manager.start_session(request).expect("start session");

        let sessions = manager.list_sessions().expect("list sessions");

        assert!(sessions.contains(&session_id));
        manager
            .shutdown_session(session_id)
            .expect("shutdown managed session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_manager_persists_manifest_when_session_starts() {
        let log_dir = unique_log_dir();
        let config = SessionManagerConfig::new(log_dir.clone());
        let manager = SessionManager::new(config.clone());
        let request = StartSessionRequest::new(long_running_shell_command());

        let session_id = manager.start_session(request).expect("start session");

        let manifest: SessionManifest = serde_json::from_slice(
            &std::fs::read(config.manifest_path()).expect("read session manifest"),
        )
        .expect("decode session manifest");
        assert_eq!(manifest.version, 1);
        let persisted = manifest
            .sessions
            .iter()
            .find(|session| session.id == session_id)
            .expect("persisted session");
        assert_eq!(
            persisted.log_path,
            log_dir.join(format!("{session_id}.log"))
        );
        assert!(!persisted.exited);

        manager
            .shutdown_session(session_id)
            .expect("shutdown managed session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn session_manager_replaces_existing_manifest() {
        let log_dir = unique_log_dir();
        let config = SessionManagerConfig::new(log_dir.clone());
        let manager = SessionManager::new(config.clone());
        let sessions = std::collections::HashMap::new();

        manager
            .persist_manifest(&sessions)
            .expect("write initial manifest");
        manager
            .persist_manifest(&sessions)
            .expect("replace existing manifest");

        let manifest: SessionManifest = serde_json::from_slice(
            &std::fs::read(config.manifest_path()).expect("read session manifest"),
        )
        .expect("decode session manifest");
        assert_eq!(manifest.version, 1);
        assert!(manifest.sessions.is_empty());

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn manifest_backup_replace_restores_existing_manifest_when_install_fails() {
        let log_dir = unique_log_dir();
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        let manifest_path = log_dir.join("sessions.json");
        let temp_path = log_dir.join("sessions.json.tmp");
        std::fs::write(&manifest_path, b"previous manifest").expect("write previous manifest");

        let error = replace_manifest_with_backup(&temp_path, &manifest_path)
            .expect_err("missing temp manifest should fail replacement");

        assert!(
            error.to_string().contains("moving session manifest"),
            "unexpected replacement error: {error:?}"
        );
        assert_eq!(
            std::fs::read(&manifest_path).expect("read restored manifest"),
            b"previous manifest"
        );
        assert!(!manifest_path.with_extension("json.bak").exists());

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_manager_rolls_back_started_session_when_manifest_persist_fails() {
        let log_dir = unique_log_dir();
        let config = SessionManagerConfig::new(log_dir.clone());
        std::fs::create_dir_all(config.manifest_path()).expect("create manifest path directory");
        let manager = SessionManager::new(config);

        let error = manager
            .start_session(StartSessionRequest::new(long_running_shell_command()))
            .expect_err("start session should fail when manifest cannot be replaced");

        assert!(
            error.to_string().contains("moving session manifest")
                || error
                    .to_string()
                    .contains("removing existing session manifest"),
            "unexpected persist error: {error:?}"
        );
        assert!(
            manager
                .list_sessions()
                .expect("list sessions after rollback")
                .is_empty(),
            "failed manifest persistence should not retain the started session"
        );

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_manager_keeps_session_when_shutdown_manifest_persist_fails() {
        let log_dir = unique_log_dir();
        let config = SessionManagerConfig::new(log_dir.clone());
        let manager = SessionManager::new(config.clone());
        let session_id = manager
            .start_session(StartSessionRequest::new(long_running_shell_command()))
            .expect("start session");
        std::fs::remove_file(config.manifest_path()).expect("remove manifest file");
        std::fs::create_dir_all(config.manifest_path()).expect("create manifest path directory");

        let error = manager
            .shutdown_session(session_id.clone())
            .expect_err("shutdown should fail when manifest cannot be replaced");

        assert!(
            error.to_string().contains("moving session manifest"),
            "unexpected persist error: {error:?}"
        );
        assert!(
            manager
                .list_sessions()
                .expect("list sessions after failed shutdown")
                .contains(&session_id),
            "failed shutdown persistence should keep the session registered"
        );

        std::fs::remove_dir_all(config.manifest_path()).expect("remove blocking manifest dir");
        manager
            .shutdown_session(session_id)
            .expect("shutdown after manifest path restored");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn session_manager_restores_historical_sessions_from_manifest() {
        let log_dir = unique_log_dir();
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::write(&log_path, b"restored-ready\r\n").expect("write session log");
        let manifest = SessionManifest {
            version: 1,
            sessions: vec![PersistedSession {
                id: session_id.clone(),
                command: "/bin/sh".to_string(),
                args: Vec::new(),
                cwd: None,
                size: SessionSize {
                    rows: 6,
                    cols: 40,
                    pixel_width: 800,
                    pixel_height: 240,
                    dpi: 96,
                },
                log_path,
                exited: false,
                last_known_cwd: None,
                last_activity_ms: 0,
            }],
        };
        std::fs::write(
            SessionManagerConfig::new(log_dir.clone()).manifest_path(),
            serde_json::to_vec(&manifest).expect("encode manifest"),
        )
        .expect("write manifest");

        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));

        let sessions = manager.list_sessions().expect("list sessions");
        assert_eq!(sessions.len(), 1);
        assert!(sessions.contains(&session_id));
        let snapshot = manager
            .snapshot_session(session_id.clone())
            .expect("restored snapshot");
        assert!(snapshot.exited);
        assert_eq!(snapshot.bytes_logged, b"restored-ready\r\n".len() as u64);
        assert!(
            snapshot
                .visible_rows
                .iter()
                .any(|row| row.contains("restored-ready")),
            "restored rows did not include replayed log: {:?}",
            snapshot.visible_rows
        );

        let rows = manager
            .styled_rows(StyledRowsRequest {
                session_id: session_id.clone(),
                start: 0,
                end: snapshot.visible_rows.len(),
            })
            .expect("restored styled rows");
        assert_eq!(rows.output_seq, snapshot.output_seq);
        assert_eq!(rows.rows.len(), snapshot.visible_rows.len());
        let restored_events = manager
            .subscribe_session_events(session_id.clone())
            .expect("subscribe to restored session events");
        assert!(matches!(
            restored_events.try_recv(),
            Err(TryRecvError::Disconnected)
        ));
        assert!(
            manager
                .write_input(WriteInputRequest {
                    session_id: session_id.clone(),
                    client_id: ClientId::new("client").expect("client id"),
                    bytes: b"echo nope\n".to_vec(),
                })
                .is_err(),
            "historical sessions should reject input"
        );

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_manager_restores_historical_shell_as_live_session() {
        let log_dir = unique_log_dir();
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::write(&log_path, b"history-before-restore\r\n").expect("write session log");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                args: Vec::new(),
                cwd: None,
                size: SessionSize {
                    rows: 6,
                    cols: 40,
                    pixel_width: 800,
                    pixel_height: 240,
                    dpi: 96,
                },
                log_path: log_path.clone(),
                exited: false,
                last_known_cwd: None,
                last_activity_ms: 0,
            },
        );
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));

        let snapshot = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize {
                    rows: 6,
                    cols: 40,
                    pixel_width: 800,
                    pixel_height: 240,
                    dpi: 96,
                },
            })
            .expect("restore shell session");

        assert!(!snapshot.exited);
        assert!(
            snapshot
                .visible_rows
                .iter()
                .any(|row| row.contains("history-before-restore")),
            "restored live snapshot lost historical rows: {:?}",
            snapshot.visible_rows
        );
        let client_id = ClientId::new("restore-client").expect("client id");
        manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach restored session");
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id,
                bytes: input_that_prints_marker(),
            })
            .expect("write restored session input");
        wait_for_manager_marker(&manager, session_id.clone(), "actor-ready");

        let logged = std::fs::read_to_string(&log_path).expect("read restored log");
        assert!(logged.contains("history-before-restore"));
        assert!(logged.contains("actor-ready"));
        manager
            .shutdown_session(session_id)
            .expect("shutdown restored session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn restore_revives_live_session_whose_process_died() {
        // A session whose child process exits while it is still `Live` (e.g. one
        // adopted across a handover, then exited) must remain restorable. It used
        // to be rejected with "already live or restoring" and stay stuck.
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let mut request = StartSessionRequest::new(long_running_shell_command());
        request.size = SessionSize {
            rows: 6,
            cols: 40,
            pixel_width: 800,
            pixel_height: 240,
            dpi: 96,
        };
        let session_id = manager.start_session(request).expect("start session");

        let client_id = ClientId::new("revive-client").expect("client id");
        manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach controller");

        // Tell the shell to exit, then wait for the manager to observe the death.
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                bytes: b"exit\n".to_vec(),
            })
            .expect("write exit input");

        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            let snapshot = manager
                .snapshot_session(session_id.clone())
                .expect("snapshot dead live session");
            if snapshot.exited {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "timed out waiting for live session to exit"
            );
            std::thread::sleep(Duration::from_millis(20));
        }

        // The session is still `Live` (dead actor) here; restore must revive it
        // rather than bail.
        let restored = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize {
                    rows: 6,
                    cols: 40,
                    pixel_width: 800,
                    pixel_height: 240,
                    dpi: 96,
                },
            })
            .expect("restore revives dead live session");
        assert!(!restored.exited, "restored session should be live again");

        // It accepts input again through the normal attach + write path.
        manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("re-attach revived session");
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id,
                bytes: input_that_prints_marker(),
            })
            .expect("write input to revived session");
        wait_for_manager_marker(&manager, session_id.clone(), "actor-ready");

        manager
            .shutdown_session(session_id)
            .expect("shutdown revived session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn demoting_dead_live_session_carries_its_activity_into_the_manifest() {
        // `into_persisted` rebuilds from the launch config, which has no activity
        // stamp, so the demotion has to carry the live one over. Without it a
        // session that exits is written to the manifest as "unknown" and sinks to
        // the bottom of the rail despite having been busy moments earlier.
        // Asserted against the manifest on disk rather than the revived actor:
        // the restored shell prints a prompt within milliseconds, which
        // legitimately re-stamps activity and would make this a race.
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let session_id = manager
            .start_session(StartSessionRequest::new(long_running_shell_command()))
            .expect("start session");
        let client_id = ClientId::new("demote-activity-client").expect("client id");
        manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach controller");

        std::thread::sleep(Duration::from_millis(5));
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                bytes: b"echo triage-demote-marker\n".to_vec(),
            })
            .expect("write input");
        wait_for_manager_marker(&manager, session_id.clone(), "triage-demote-marker");

        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id,
                bytes: b"exit\n".to_vec(),
            })
            .expect("write exit input");
        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            let snapshot = manager
                .snapshot_session(session_id.clone())
                .expect("snapshot dead live session");
            if snapshot.exited {
                break;
            }
            assert!(Instant::now() < deadline, "timed out waiting for exit");
            std::thread::sleep(Duration::from_millis(20));
        }

        // Read after the exit, not before it: typing `exit` is itself echoed by
        // the shell, so a stamp captured earlier is legitimately stale by the
        // time the session dies. This is the value the demotion has to carry.
        //
        // Waited out rather than read straight away. `exited` flips when the
        // child dies, but the reader thread can still be draining what the shell
        // printed on its way out, and every chunk re-stamps activity: reading
        // immediately made the equality below a race that only showed up under a
        // loaded full-suite run. Settling for one quiet interval keeps the
        // assertion exact, where relaxing it to `>=` would hold with the
        // demotion deleted outright.
        let read_activity = || {
            let sessions = manager.sessions().expect("sessions lock");
            match sessions.get(&session_id).expect("dead live session") {
                ManagedSession::Live { actor, .. } => actor.last_activity_ms(),
                _ => panic!("expected a live session"),
            }
        };
        let at_exit = {
            let deadline = Instant::now() + Duration::from_secs(5);
            let mut previous = read_activity();
            loop {
                std::thread::sleep(Duration::from_millis(50));
                let current = read_activity();
                if current == previous {
                    break current;
                }
                assert!(Instant::now() < deadline, "activity stamp never settled");
                previous = current;
            }
        };
        assert!(at_exit > 0);

        // Demoted directly rather than through `restore_session`, which is the
        // only production caller. Restore demotes and then immediately revives
        // the session, and the revived shell prints a prompt and persists the
        // manifest again a couple of hundred milliseconds later: reading the file
        // afterwards was reading the *restored* session's stamp, not the demoted
        // one, and the equality below held only when the suite happened to be
        // quiet enough for the read to win that race.
        manager
            .demote_dead_live_session(&session_id)
            .expect("demote dead live session");

        let persisted = read_manifest(&log_dir)
            .sessions
            .into_iter()
            .find(|session| session.id == session_id)
            .expect("demoted session in manifest");
        assert_eq!(
            persisted.last_activity_ms, at_exit,
            "the demotion must carry the live stamp, not zero it",
        );

        let _ = manager.shutdown_session(session_id);
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn restoring_a_pre_field_manifest_keeps_the_spawn_time_default() {
        // A manifest written before `last_activity_ms` existed decodes as 0,
        // which the rail reads as "never active". Seeding the actor with it would
        // bury every session restored from such a manifest below every session
        // that has one, so 0 must leave the spawn-time default alone.
        let log_dir = unique_log_dir();
        let session_id = SessionId::new("session-3").expect("session id");
        let log_path = log_dir.join("session-3.log");
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        std::fs::write(&log_path, b"prior output\r\n").expect("write session log");
        let before_restore = now_unix_millis();
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                args: vec![
                    "-c".to_string(),
                    "sleep 60; exec \"${SHELL:-/bin/sh}\"".to_string(),
                ],
                cwd: None,
                size: SessionSize::default(),
                log_path,
                exited: false,
                last_known_cwd: None,
                last_activity_ms: 0,
            },
        );

        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize::default(),
            })
            .expect("restore session");

        let restored = {
            let sessions = manager.sessions().expect("sessions lock");
            match sessions.get(&session_id).expect("restored session") {
                ManagedSession::Live { actor, .. } => actor.last_activity_ms(),
                _ => panic!("expected the restored session to be live"),
            }
        };
        assert!(
            restored >= before_restore,
            "a 0 stamp must leave the spawn-time default, got {restored}",
        );

        let _ = manager.shutdown_session(session_id);
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn demoting_dead_live_session_preserves_last_known_cwd() {
        // A live session that moved away from its launch dir (tracked in
        // last_known_cwd) and then exited must, when restored via the demote
        // path, come back at the tracked dir — demote_dead_live_session must not
        // drop last_known_cwd (into_persisted hardcodes None) and reset it to the
        // launch dir.
        let log_dir = unique_log_dir();
        let launch_cwd = log_dir.join("launch");
        let live_cwd = log_dir.join("live");
        std::fs::create_dir_all(&launch_cwd).expect("create launch cwd");
        std::fs::create_dir_all(&live_cwd).expect("create live cwd");
        // Canonicalize: the restored shell reports its cwd symlink-resolved.
        let live_cwd = std::fs::canonicalize(&live_cwd).expect("canonicalize live cwd");
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let mut request = StartSessionRequest::new(long_running_shell_command());
        request.cwd = Some(launch_cwd.clone());
        request.size = SessionSize::default();
        let session_id = manager.start_session(request).expect("start session");

        // Simulate the live cwd tracking having recorded a `cd` into live_cwd.
        // (start_cwd_persistence is not running in tests, so nothing overwrites
        // this field while the shell sits in the launch dir.)
        {
            let mut sessions = manager.sessions().expect("lock sessions");
            let Some(ManagedSession::Live { last_known_cwd, .. }) = sessions.get_mut(&session_id)
            else {
                panic!("expected live session");
            };
            *last_known_cwd = Some(live_cwd.clone());
        }

        let client_id = ClientId::new("demote-cwd-client").expect("client id");
        manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach controller");
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id,
                bytes: b"exit\n".to_vec(),
            })
            .expect("write exit input");

        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            let snapshot = manager
                .snapshot_session(session_id.clone())
                .expect("snapshot dead live session");
            if snapshot.exited {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "timed out waiting for live session to exit"
            );
            std::thread::sleep(Duration::from_millis(20));
        }

        // Restore goes through demote_dead_live_session; the tracked cwd must
        // survive rather than being reset to the launch dir.
        let restored = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize::default(),
            })
            .expect("restore revives dead live session");
        assert_eq!(
            restored.current_working_directory,
            Some(live_cwd.clone()),
            "demote -> restore must preserve the live-tracked cwd, not reset to launch"
        );

        manager
            .shutdown_session(session_id)
            .expect("shutdown restored session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn restore_does_not_demote_a_non_restorable_dead_live_session() {
        // A dead `Live` session that was NOT launched as a restorable shell must
        // be left as `Live` (its actor not reaped) rather than irreversibly
        // downgraded to `Historical` for a restore that bails anyway.
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let mut request = StartSessionRequest::new(long_running_shell_command());
        // `-c "exit 0"` exits immediately and is not the triage default shell
        // wrapper, so is_restorable_shell_launch rejects it.
        request.args = vec!["-c".to_string(), "exit 0".to_string()];
        request.size = SessionSize {
            rows: 6,
            cols: 40,
            pixel_width: 800,
            pixel_height: 240,
            dpi: 96,
        };
        let session_id = manager.start_session(request).expect("start session");

        let deadline = Instant::now() + Duration::from_secs(5);
        loop {
            let snapshot = manager
                .snapshot_session(session_id.clone())
                .expect("snapshot dead live session");
            if snapshot.exited {
                break;
            }
            assert!(
                Instant::now() < deadline,
                "timed out waiting for non-restorable session to exit"
            );
            std::thread::sleep(Duration::from_millis(20));
        }

        // Restore must reject it (not a restorable shell).
        assert!(
            manager
                .restore_session(RestoreSessionRequest {
                    session_id: session_id.clone(),
                    size: SessionSize {
                        rows: 6,
                        cols: 40,
                        pixel_width: 800,
                        pixel_height: 240,
                        dpi: 96,
                    },
                })
                .is_err(),
            "restore of a non-restorable session should fail"
        );

        // It must still be `Live`: attaching as a controller acquires the input
        // lease (the `Historical` attach branch never grants one), proving the
        // session was not demoted and its actor not reaped.
        let response = manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: ClientId::new("non-restorable-client").expect("client id"),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach still-live session");
        assert!(
            response.lease.holder.is_some(),
            "non-restorable dead session should remain Live with an acquirable lease"
        );

        manager
            .shutdown_session(session_id)
            .expect("shutdown session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn restored_live_session_reflows_history_on_resize() {
        let log_dir = unique_log_dir();
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        let long_line = "0123456789abcdefghijklmnopqrstuvwxyz";
        std::fs::write(&log_path, long_line).expect("write session log");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                args: Vec::new(),
                cwd: None,
                size: SessionSize {
                    rows: 6,
                    cols: 12,
                    pixel_width: 120,
                    pixel_height: 120,
                    dpi: 96,
                },
                log_path: log_path.clone(),
                exited: false,
                last_known_cwd: None,
                last_activity_ms: 0,
            },
        );
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));

        let restored = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize {
                    rows: 6,
                    cols: 12,
                    pixel_width: 120,
                    pixel_height: 120,
                    dpi: 96,
                },
            })
            .expect("restore shell session");
        assert!(
            !restored.visible_rows.iter().any(|row| row == long_line),
            "narrow restored session should initially wrap history: {:?}",
            restored.visible_rows
        );

        let resized = manager
            .resize_session(ResizeSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize {
                    rows: 6,
                    cols: 80,
                    pixel_width: 800,
                    pixel_height: 120,
                    dpi: 96,
                },
            })
            .expect("resize restored session");

        assert!(
            resized
                .visible_rows
                .iter()
                .any(|row| row.starts_with(long_line)),
            "resized restored session should reflow history: {:?}",
            resized.visible_rows
        );
        manager
            .shutdown_session(session_id)
            .expect("shutdown restored session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn session_manager_restores_shell_in_last_known_cwd() {
        let log_dir = unique_log_dir();
        let cwd = log_dir.join("last-cwd");
        std::fs::create_dir_all(&cwd).expect("create restored cwd");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::write(
            &log_path,
            format!("\x1b]7;file://localhost{}\x1b\\", cwd.display()),
        )
        .expect("write OSC 7 session log");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                args: Vec::new(),
                cwd: Some(log_dir.clone()),
                size: SessionSize::default(),
                log_path,
                exited: false,
                last_known_cwd: None,
                last_activity_ms: 0,
            },
        );
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let client_id = ClientId::new("restore-client").expect("client id");

        let snapshot = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize::default(),
            })
            .expect("restore shell session");

        assert_eq!(snapshot.current_working_directory, Some(cwd.clone()));
        manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach restored session");
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id,
                bytes: b"pwd\n".to_vec(),
            })
            .expect("write pwd");
        wait_for_manager_marker(&manager, session_id.clone(), &cwd.display().to_string());

        manager
            .shutdown_session(session_id)
            .expect("shutdown restored session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn session_manager_falls_back_when_last_known_cwd_is_unusable() {
        let log_dir = unique_log_dir();
        let launch_cwd = log_dir.join("launch-cwd");
        let stale_cwd = log_dir.join("deleted-cwd");
        std::fs::create_dir_all(&launch_cwd).expect("create launch cwd");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::write(
            &log_path,
            format!("\x1b]7;file://localhost{}\x1b\\", stale_cwd.display()),
        )
        .expect("write stale OSC 7 session log");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                args: Vec::new(),
                cwd: Some(launch_cwd.clone()),
                size: SessionSize::default(),
                log_path,
                exited: false,
                last_known_cwd: None,
                last_activity_ms: 0,
            },
        );
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let client_id = ClientId::new("restore-client").expect("client id");

        let snapshot = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize::default(),
            })
            .expect("restore shell session");

        assert_eq!(snapshot.current_working_directory, Some(launch_cwd.clone()));
        manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach restored session");
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id,
                bytes: b"pwd\n".to_vec(),
            })
            .expect("write pwd");
        wait_for_manager_marker(
            &manager,
            session_id.clone(),
            &launch_cwd.display().to_string(),
        );

        manager
            .shutdown_session(session_id)
            .expect("shutdown restored session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn restored_session_keeps_its_persisted_activity_stamp() {
        // The corruption this guards against is what ruled out log-file mtimes as
        // the activity source: restoring stamped every session with the restart
        // instant, collapsing the rail's activity order into one arbitrary tie.
        // A restored session must come back with its real recency.
        let log_dir = unique_log_dir();
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        std::fs::write(&log_path, b"prior output\r\n").expect("write session log");

        // A stamp comfortably in the past, so "restored the real value" and
        // "re-stamped as now" cannot be confused.
        let persisted_activity_ms = now_unix_millis() - 86_400_000;
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                // The `-c` wrapper shape triage itself launches with, so
                // `is_restorable_shell_launch` accepts it, but sleeping before
                // the exec so the restored session writes nothing. An
                // interactive shell prints a prompt, which re-stamps activity
                // and would make the assertion below a race, which is how it
                // ended up as the toothless `>=` this replaces.
                args: vec![
                    "-c".to_string(),
                    "sleep 60; exec \"${SHELL:-/bin/sh}\"".to_string(),
                ],
                cwd: None,
                size: SessionSize {
                    rows: 6,
                    cols: 12,
                    pixel_width: 120,
                    pixel_height: 120,
                    dpi: 96,
                },
                log_path: log_path.clone(),
                exited: false,
                last_known_cwd: None,
                last_activity_ms: persisted_activity_ms,
            },
        );

        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize {
                    rows: 6,
                    cols: 12,
                    pixel_width: 120,
                    pixel_height: 120,
                    dpi: 96,
                },
            })
            .expect("restore session");

        let restored_activity_ms = {
            let sessions = manager.sessions().expect("sessions lock");
            match sessions.get(&session_id).expect("restored session") {
                ManagedSession::Live { actor, .. } => actor.last_activity_ms(),
                _ => panic!("expected the restored session to be live"),
            }
        };

        // Exactly the persisted value. A `>=` assertion here would pass under
        // the very bug it names: an actor whose seed was discarded reads back
        // spawn time, which is newer than a day-old stamp and so satisfies
        // `>=`. Equality is what distinguishes "restored" from "re-stamped".
        assert_eq!(
            restored_activity_ms, persisted_activity_ms,
            "a restored session must come back with its persisted stamp, not the \
             restart instant",
        );

        let _ = manager.shutdown_session(session_id);
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn live_session_activity_is_written_into_the_manifest() {
        // `persisted()` reads through to the actor, which is what lets the
        // periodic flush be a plain re-persist rather than a separate path.
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let session_id = manager
            .start_session(StartSessionRequest::new(long_running_shell_command()))
            .expect("start session");

        let persisted = {
            let sessions = manager.sessions().expect("sessions lock");
            sessions
                .get(&session_id)
                .expect("live session")
                .persisted(session_id.clone())
        };

        // Compared against the actor's own value, not merely `> 0`: the actor
        // seeds this field at spawn, so `> 0` holds even if `persisted()` made
        // its own timestamp up and never read through at all.
        let live = {
            let sessions = manager.sessions().expect("sessions lock");
            match sessions.get(&session_id).expect("live session") {
                ManagedSession::Live { actor, .. } => actor.last_activity_ms(),
                _ => panic!("expected a live session"),
            }
        };
        assert_eq!(
            persisted.last_activity_ms, live,
            "the manifest value must read through to the actor",
        );
        assert!(persisted.last_activity_ms > 0);

        let _ = manager.shutdown_session(session_id);
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn session_activity_advances_when_output_arrives() {
        // The stamp the whole feature rests on. Nothing else asserted that
        // producing output moves it: every other test is satisfied by the
        // spawn-time seed, so deleting the store in the output-ingest path left
        // the suite green while the rail silently stopped tracking recency.
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let session_id = manager
            .start_session(StartSessionRequest::new(long_running_shell_command()))
            .expect("start session");
        let client_id = ClientId::new("client-1").expect("client id");

        let at_spawn = {
            let sessions = manager.sessions().expect("sessions lock");
            match sessions.get(&session_id).expect("live session") {
                ManagedSession::Live { actor, .. } => actor.last_activity_ms(),
                _ => panic!("expected a live session"),
            }
        };

        // The stamp has millisecond resolution, so without this the output could
        // land in the same millisecond as the spawn and the assertion below would
        // be a coin flip rather than a test.
        std::thread::sleep(Duration::from_millis(5));
        manager
            .attach_session(AttachSessionRequest {
                session_id: session_id.clone(),
                client_id: client_id.clone(),
                mode: triage_core::session::AttachMode::InteractiveController,
            })
            .expect("attach controller");
        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id,
                bytes: b"echo triage-activity-marker\n".to_vec(),
            })
            .expect("write input");
        wait_for_manager_marker(&manager, session_id.clone(), "triage-activity-marker");

        let after_output = {
            let sessions = manager.sessions().expect("sessions lock");
            match sessions.get(&session_id).expect("live session") {
                ManagedSession::Live { actor, .. } => actor.last_activity_ms(),
                _ => panic!("expected a live session"),
            }
        };
        assert!(
            after_output > at_spawn,
            "output must advance the activity stamp: {after_output} vs {at_spawn}",
        );

        let _ = manager.shutdown_session(session_id);
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn session_manager_restores_persisted_last_known_cwd_without_osc7() {
        // A zsh-style session that never emits OSC 7: the only durable record of
        // where it ended up is `last_known_cwd`, tracked live and persisted. A
        // daemon kill must restore it there, not at the launch dir.
        let log_dir = unique_log_dir();
        let live_cwd = log_dir.join("live-cwd");
        let launch_cwd = log_dir.join("launch-cwd");
        std::fs::create_dir_all(&live_cwd).expect("create live cwd");
        std::fs::create_dir_all(&launch_cwd).expect("create launch cwd");
        // Canonicalize: the live cwd poll resolves symlinks (macOS /var ->
        // /private/var), so the restored shell reports the canonical path.
        let live_cwd = std::fs::canonicalize(&live_cwd).expect("canonicalize live cwd");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::write(&log_path, b"shell output with no osc 7 reports\r\n")
            .expect("write session log");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                args: Vec::new(),
                cwd: Some(launch_cwd.clone()),
                size: SessionSize::default(),
                log_path,
                exited: false,
                last_known_cwd: Some(live_cwd.clone()),
                last_activity_ms: 0,
            },
        );
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));

        let snapshot = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize::default(),
            })
            .expect("restore shell session");

        assert_eq!(
            snapshot.current_working_directory,
            Some(live_cwd.clone()),
            "restore should prefer the persisted live cwd over the launch dir"
        );
        manager
            .shutdown_session(session_id)
            .expect("shutdown restored session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn session_manager_restore_ignores_unusable_last_known_cwd() {
        // The live cwd recorded at kill time no longer exists (worktree removed);
        // restore must fall back to the launch dir rather than a dead path.
        let log_dir = unique_log_dir();
        let launch_cwd = log_dir.join("launch-cwd");
        let gone_cwd = log_dir.join("removed-worktree");
        std::fs::create_dir_all(&launch_cwd).expect("create launch cwd");
        // Canonicalize: the live cwd poll resolves symlinks, so the restored
        // shell reports the canonical launch path after falling back.
        let launch_cwd = std::fs::canonicalize(&launch_cwd).expect("canonicalize launch cwd");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::write(&log_path, b"shell output\r\n").expect("write session log");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                args: Vec::new(),
                cwd: Some(launch_cwd.clone()),
                size: SessionSize::default(),
                log_path,
                exited: false,
                last_known_cwd: Some(gone_cwd),
                last_activity_ms: 0,
            },
        );
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));

        let snapshot = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize::default(),
            })
            .expect("restore shell session");

        assert_eq!(
            snapshot.current_working_directory,
            Some(launch_cwd.clone()),
            "restore should fall back to the launch dir when the live cwd is gone"
        );
        manager
            .shutdown_session(session_id)
            .expect("shutdown restored session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn persisted_session_deserializes_legacy_manifest_without_last_known_cwd() {
        // Manifests written before `last_known_cwd` existed must still load.
        let size_json = serde_json::to_string(&SessionSize::default()).expect("encode size");
        let json = format!(
            r#"{{"id":"session-1","command":"/bin/zsh","args":[],"cwd":null,"size":{size_json},"log_path":"/tmp/session-1.log","exited":false}}"#
        );
        let persisted: PersistedSession =
            serde_json::from_str(&json).expect("deserialize legacy manifest entry");
        assert_eq!(persisted.last_known_cwd, None);
    }

    #[test]
    fn session_manager_rejects_restore_already_in_progress() {
        let log_dir = unique_log_dir();
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::write(&log_path, b"history-before-restore\r\n").expect("write session log");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: long_running_shell_command().to_string(),
                args: Vec::new(),
                cwd: None,
                size: SessionSize::default(),
                log_path,
                exited: false,
                last_known_cwd: None,
                last_activity_ms: 0,
            },
        );
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        {
            let mut sessions = manager.sessions().expect("lock sessions");
            let existing = sessions.remove(&session_id).expect("historical session");
            let ManagedSession::Historical { session, lease } = existing else {
                panic!("expected historical session");
            };
            sessions.insert(
                session_id.clone(),
                ManagedSession::Restoring { session, lease },
            );
        }

        let error = manager
            .restore_session(RestoreSessionRequest {
                session_id,
                size: SessionSize::default(),
            })
            .expect_err("restore in progress should fail");

        assert!(
            error.to_string().contains("already live or restoring"),
            "unexpected restore error: {error:?}"
        );
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn session_manager_rejects_non_shell_historical_restore() {
        let log_dir = unique_log_dir();
        std::fs::create_dir_all(&log_dir).expect("create log dir");
        let session_id = SessionId::new("session-7").expect("session id");
        let log_path = log_dir.join("session-7.log");
        std::fs::write(&log_path, b"not-a-shell\r\n").expect("write session log");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: session_id.clone(),
                command: "python".to_string(),
                args: Vec::new(),
                cwd: None,
                size: SessionSize::default(),
                log_path,
                exited: false,
                last_known_cwd: None,
                last_activity_ms: 0,
            },
        );
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));

        let error = manager
            .restore_session(RestoreSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize::default(),
            })
            .expect_err("non-shell restore should fail");

        assert!(
            error
                .to_string()
                .contains("not launched as a restorable shell"),
            "unexpected restore error: {error:?}"
        );
        assert!(
            manager
                .snapshot_session(session_id)
                .expect("historical session remains available")
                .exited
        );
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    fn activity_map(entries: &[(&str, u64)]) -> HashMap<SessionId, u64> {
        entries
            .iter()
            .map(|(id, millis)| (SessionId::new(*id).expect("session id"), *millis))
            .collect()
    }

    #[test]
    fn activity_advanced_is_false_when_nothing_moved() {
        // The property that keeps an idle daemon off the disk entirely: with
        // every session quiet, the stamps stop advancing and this keeps
        // returning false, so the 60s tick does no I/O.
        let persisted = activity_map(&[("session-1", 100), ("session-2", 200)]);
        assert!(!activity_advanced(&persisted, &persisted.clone()));
    }

    #[test]
    fn activity_advanced_detects_a_newer_stamp() {
        let persisted = activity_map(&[("session-1", 100)]);
        let current = activity_map(&[("session-1", 101)]);
        assert!(activity_advanced(&persisted, &current));
    }

    #[test]
    fn activity_advanced_detects_a_session_that_did_not_exist_before() {
        let persisted = activity_map(&[("session-1", 100)]);
        let current = activity_map(&[("session-1", 100), ("session-2", 5)]);
        assert!(activity_advanced(&persisted, &current));
    }

    #[test]
    fn activity_advanced_ignores_a_session_that_went_away() {
        // Shutdown and demotion persist the manifest themselves, so firing here
        // too would make every shutdown cost a second write.
        let persisted = activity_map(&[("session-1", 100), ("session-2", 200)]);
        let current = activity_map(&[("session-1", 100)]);
        assert!(!activity_advanced(&persisted, &current));
    }

    #[test]
    fn start_activity_persistence_is_idempotent() {
        let log_dir = unique_log_dir();
        let manager = Arc::new(SessionManager::new(SessionManagerConfig::new(
            log_dir.clone(),
        )));
        manager.start_activity_persistence();
        assert_eq!(
            Arc::weak_count(&manager),
            1,
            "the first call spawns the loop, which holds one Weak"
        );

        // A second call must not spawn a second thread writing the same
        // manifest; the guard flag is what prevents it. Counted through the
        // `Weak` each spawned loop holds, because asserting the flag alone is
        // true after the *first* call: that test stayed green with the guard
        // deleted entirely.
        manager.start_activity_persistence();
        assert_eq!(
            Arc::weak_count(&manager),
            1,
            "a second call must not spawn a second persistence loop"
        );
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn session_sort_key_orders_generated_ids_numerically() {
        // The bug this guards: sorting the raw string puts `session-10` before
        // `session-2`, so the rail's fallback order goes wrong the moment a
        // daemon passes its tenth session.
        let mut ids = [
            SessionId::new("session-10").expect("session id"),
            SessionId::new("session-2").expect("session id"),
            SessionId::new("session-1").expect("session id"),
        ];
        ids.sort_by(|left, right| session_sort_key(left).cmp(&session_sort_key(right)));

        let ordered: Vec<&str> = ids.iter().map(SessionId::as_str).collect();
        assert_eq!(ordered, ["session-1", "session-2", "session-10"]);
    }

    #[test]
    fn session_sort_key_places_custom_ids_after_generated_ones() {
        let mut ids = [
            SessionId::new("zeta").expect("session id"),
            SessionId::new("session-3").expect("session id"),
            SessionId::new("alpha").expect("session id"),
        ];
        ids.sort_by(|left, right| session_sort_key(left).cmp(&session_sort_key(right)));

        let ordered: Vec<&str> = ids.iter().map(SessionId::as_str).collect();
        // Generated ids first in sequence order, then custom ids
        // lexicographically: a total order, so the result never depends on the
        // input order.
        assert_eq!(ordered, ["session-3", "alpha", "zeta"]);
    }

    #[test]
    #[cfg(not(windows))]
    fn list_sessions_returns_ids_in_creation_order() {
        // `sessions` is a HashMap whose iteration order is reseeded per process,
        // so this is the regression guard for the original complaint: the rail
        // was ordered differently on every daemon restart.
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let mut started = Vec::new();
        for _ in 0..12 {
            started.push(
                manager
                    .start_session(StartSessionRequest::new(long_running_shell_command()))
                    .expect("start session"),
            );
        }

        // Compared against `started` directly, which *is* creation order.
        // Deriving the expectation by sorting with `session_sort_key` (the
        // function under test) would make this pass under the very bug it
        // names: a lexicographic key satisfies its own sort, and `session-10`
        // would sit before `session-2` on both sides.
        let listed = manager.list_sessions().expect("list sessions");
        assert_eq!(listed, started, "ids must come back in creation order");

        // Repeated calls against the same map must not vary either.
        assert_eq!(
            manager.list_sessions().expect("list sessions again"),
            listed
        );

        for session_id in started {
            let _ = manager.shutdown_session(session_id);
        }
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn next_session_sequence_advances_past_restored_ids() {
        let sessions = [
            SessionId::new("session-7").expect("session id"),
            SessionId::new("session-41").expect("session id"),
            SessionId::new("custom").expect("session id"),
        ];

        assert_eq!(next_session_sequence(sessions.iter()), 42);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn session_manager_fans_out_session_events_to_subscribers() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let mut request = StartSessionRequest::new(long_running_shell_command());
        request.size = SessionSize {
            rows: 6,
            cols: 40,
            pixel_width: 800,
            pixel_height: 240,
            dpi: 96,
        };
        let session_id = manager.start_session(request).expect("start session");
        let local_tui = ClientId::new("local-tui").expect("local tui id");
        let first_subscriber = manager
            .subscribe_session_events(session_id.clone())
            .expect("subscribe first client");
        let second_subscriber = manager
            .subscribe_session_events(session_id.clone())
            .expect("subscribe second client");

        manager
            .acquire_input_lease(InputLeaseRequest {
                session_id: session_id.clone(),
                client_id: local_tui.clone(),
                kind: triage_core::session::InputControllerKind::Interactive,
            })
            .expect("acquire input lease");
        assert!(matches!(
            wait_for_event(&first_subscriber, "first lease event", |event| {
                matches!(
                    event,
                    SessionEvent::LeaseChanged { session_id: event_session_id, change }
                        if event_session_id == &session_id
                            && change.action == triage_core::session::LeaseChangeAction::Acquired
                )
            }),
            SessionEvent::LeaseChanged { .. }
        ));
        assert!(matches!(
            wait_for_event(&second_subscriber, "second lease event", |event| {
                matches!(
                    event,
                    SessionEvent::LeaseChanged { session_id: event_session_id, change }
                        if event_session_id == &session_id
                            && change.action == triage_core::session::LeaseChangeAction::Acquired
                )
            }),
            SessionEvent::LeaseChanged { .. }
        ));

        manager
            .write_input(WriteInputRequest {
                session_id: session_id.clone(),
                client_id: local_tui,
                bytes: input_that_prints_marker(),
            })
            .expect("write PTY input");
        wait_for_output_event(&first_subscriber, &session_id, "actor-ready");
        wait_for_output_event(&second_subscriber, &session_id, "actor-ready");

        manager
            .resize_session(ResizeSessionRequest {
                session_id: session_id.clone(),
                size: SessionSize {
                    rows: 8,
                    cols: 48,
                    pixel_width: 960,
                    pixel_height: 320,
                    dpi: 96,
                },
            })
            .expect("resize managed session");
        wait_for_snapshot_event(&first_subscriber, &session_id, 8);
        wait_for_snapshot_event(&second_subscriber, &session_id, 8);

        manager
            .shutdown_session(session_id.clone())
            .expect("shutdown managed session");
        wait_for_exit_event(&first_subscriber, &session_id);
        wait_for_exit_event(&second_subscriber, &session_id);
        assert_no_exit_event(&first_subscriber, &session_id);
        assert_no_exit_event(&second_subscriber, &session_id);
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg_attr(
        windows,
        ignore = "portable-pty ConPTY EOF handling needs a dedicated Windows lifecycle test"
    )]
    fn full_event_buffer_drops_output_without_disconnect() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let request = StartSessionRequest::new(long_running_shell_command());
        let session_id = manager.start_session(request).expect("start session");
        let subscriber = manager
            .subscribe_session_events(session_id.clone())
            .expect("subscribe client");

        for index in 0..=EVENT_SUBSCRIBER_BUFFER {
            let sessions = manager.sessions().expect("lock sessions");
            let session = sessions.get(&session_id).expect("managed session");
            let ManagedSession::Live { actor, .. } = session else {
                panic!("expected live session");
            };
            actor
                .broadcast_event(SessionEvent::Output {
                    session_id: session_id.clone(),
                    output_seq: index as u64,
                    bytes: format!("burst-{index}").into_bytes(),
                })
                .expect("broadcast output");
        }

        for _ in 0..EVENT_SUBSCRIBER_BUFFER {
            let _ = subscriber
                .recv_timeout(Duration::from_secs(1))
                .expect("drain queued output event");
        }

        {
            let sessions = manager.sessions().expect("lock sessions");
            let session = sessions.get(&session_id).expect("managed session");
            let ManagedSession::Live { actor, .. } = session else {
                panic!("expected live session");
            };
            actor
                .broadcast_event(SessionEvent::Output {
                    session_id: session_id.clone(),
                    output_seq: 999,
                    bytes: b"still-subscribed".to_vec(),
                })
                .expect("broadcast sentinel output");
        }

        wait_for_output_event(&subscriber, &session_id, "still-subscribed");
        manager
            .shutdown_session(session_id)
            .expect("shutdown managed session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn dropped_event_subscribers_are_pruned_on_next_flush() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let request = StartSessionRequest::new(long_running_shell_command());
        let session_id = manager.start_session(request).expect("start session");
        let subscriber = manager
            .subscribe_session_events(session_id.clone())
            .expect("subscribe client");
        drop(subscriber);

        {
            let sessions = manager.sessions().expect("lock sessions");
            let session = sessions.get(&session_id).expect("managed session");
            let ManagedSession::Live { actor, .. } = session else {
                panic!("expected live session");
            };
            actor
                .broadcast_event(SessionEvent::Output {
                    session_id: session_id.clone(),
                    output_seq: 1,
                    bytes: b"after-disconnect".to_vec(),
                })
                .expect("broadcast output after subscriber disconnect");
            assert_eq!(actor.subscriber_count().expect("subscriber count"), 0);
        }

        manager
            .shutdown_session(session_id)
            .expect("shutdown managed session");
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    #[cfg(not(windows))]
    fn full_event_buffer_replays_exit_after_subscriber_drains() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let request = StartSessionRequest::new(long_running_shell_command());
        let session_id = manager.start_session(request).expect("start session");
        let subscriber = manager
            .subscribe_session_events(session_id.clone())
            .expect("subscribe client");

        for index in 0..=EVENT_SUBSCRIBER_BUFFER {
            let sessions = manager.sessions().expect("lock sessions");
            let session = sessions.get(&session_id).expect("managed session");
            let ManagedSession::Live { actor, .. } = session else {
                panic!("expected live session");
            };
            actor
                .broadcast_event(SessionEvent::Output {
                    session_id: session_id.clone(),
                    output_seq: index as u64,
                    bytes: format!("burst-{index}").into_bytes(),
                })
                .expect("broadcast output");
        }

        {
            let sessions = manager.sessions().expect("lock sessions");
            let session = sessions.get(&session_id).expect("managed session");
            let ManagedSession::Live { actor, .. } = session else {
                panic!("expected live session");
            };
            actor.write_input(b"exit\n".to_vec()).expect("exit shell");
        }

        wait_for_exit_event(&subscriber, &session_id);
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn replay_with_delayed_writer_suppresses_historical_terminal_replies() {
        let log_path = unique_log_path();
        let log = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&log_path)
            .expect("open test log");
        let captured = Arc::new(Mutex::new(Vec::new()));
        let (writer, replay_gate) = replay_gated_pty_writer();
        let mut output = OutputState {
            log,
            log_path: log_path.clone(),
            trim_disabled: false,
            max_log_bytes: MAX_SESSION_LOG_BYTES,
            retain_log_bytes: SESSION_LOG_RETAIN_BYTES,
            terminal: terminal_with_writer(&SessionSize::default(), writer.clone()),
            cwd_sequence_buffer: Vec::new(),
            bytes_logged: 0,
            output_seq: 0,
            log_cache: Some(Vec::new()),
        };

        output
            .replay(b"\x1b[c")
            .expect("replay historical device attributes query");
        assert!(
            captured.lock().expect("captured writer lock").is_empty(),
            "historical replay should not write terminal replies to the live PTY"
        );

        let replay_writes = replay_gate.dropped_write_count();
        let replay_flushes = replay_gate.dropped_flush_count();
        output.terminal.advance_bytes(b"\x1b[c");
        replay_gate
            .wait_for_dropped_activity_quiet_after(replay_writes, replay_flushes)
            .expect("drain replay writer");
        replay_gate
            .enable(Box::new(RecordingWriter {
                bytes: captured.clone(),
            }))
            .expect("install live writer");
        assert!(
            captured.lock().expect("captured writer lock").is_empty(),
            "queued historical terminal replies should drain before the live writer is installed"
        );

        output
            .ingest(b"\x1b[c")
            .expect("ingest live device attributes query");
        wait_for_recorded_bytes(&captured);
        assert!(
            !captured.lock().expect("captured writer lock").is_empty(),
            "live terminal queries should still receive terminal replies after restore"
        );
        let _ = std::fs::remove_file(&log_path);
    }

    fn unique_log_path() -> PathBuf {
        let unique = format!(
            "triage-pty-session-{}-{:?}.log",
            std::process::id(),
            std::thread::current().id()
        );
        std::env::temp_dir().join(unique)
    }

    #[test]
    fn read_raw_output_tail_respects_cap_and_offset() {
        let path = std::env::temp_dir().join(format!(
            "triage-rawtail-{}-{:?}.log",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = std::fs::remove_file(&path);
        std::fs::write(&path, b"0123456789").unwrap(); // 10 bytes

        // cap larger than the log -> whole log from offset 0.
        let (start, bytes) = read_raw_output_tail(&path, 10, 1024);
        assert_eq!(start, 0);
        assert_eq!(bytes, b"0123456789");

        // cap smaller than the log -> last `cap` bytes, offset advanced.
        let (start, bytes) = read_raw_output_tail(&path, 10, 4);
        assert_eq!(start, 6);
        assert_eq!(bytes, b"6789");

        // empty session -> empty, no read.
        let (start, bytes) = read_raw_output_tail(&path, 0, 1024);
        assert_eq!(start, 0);
        assert!(bytes.is_empty());

        // missing log -> empty, no panic.
        let _ = std::fs::remove_file(&path);
        let (start, bytes) = read_raw_output_tail(&path, 10, 1024);
        assert_eq!(start, 0);
        assert!(bytes.is_empty());
    }

    /// Trimming must drop the *front* of the log and keep the newest bytes: the
    /// tail is what rebuilds the screen, and it is what clients are served.
    #[test]
    fn trim_session_log_keeps_the_newest_bytes() {
        let path = unique_log_path();
        fs::write(&path, b"0123456789").expect("write test log");

        let len = trim_session_log(&path, 4).expect("trim log");
        assert_eq!(len, 4);
        assert_eq!(fs::read(&path).expect("read trimmed log"), b"6789");

        // Already under the retain size -> untouched, reported length unchanged.
        let len = trim_session_log(&path, 100).expect("trim under-size log");
        assert_eq!(len, 4);
        assert_eq!(fs::read(&path).expect("read log"), b"6789");

        let _ = fs::remove_file(&path);
    }

    /// After a trim, appends through the caller's existing append-mode handle
    /// must land at the new, shorter end — the whole reason trimming rewrites
    /// through a separate non-append handle instead of the caller's.
    #[test]
    fn trimming_leaves_an_append_mode_handle_writing_at_the_new_end() {
        let path = unique_log_path();
        fs::write(&path, b"").expect("create test log");
        // Unlike `test_output_state`, this opens the log the way the restore and
        // handover-adoption paths do — `append(true)`, sharing the inode that
        // `trim_session_log` rewrites through its own handle.
        let mut output =
            output_state_for_log(&path, SessionSize::default()).expect("open append-mode log");
        output.max_log_bytes = 8;
        output.retain_log_bytes = 4;

        output.ingest(b"0123456789").expect("ingest past the bound");
        assert_eq!(output.bytes_logged, 4);
        assert_eq!(fs::read(&path).expect("read log"), b"6789");

        output.ingest(b"ab").expect("ingest after trim");
        assert_eq!(fs::read(&path).expect("read log"), b"6789ab");
        assert_eq!(output.bytes_logged, 6);

        let _ = fs::remove_file(&path);
    }

    /// `bytes_logged` must track the log's true length, not the length of the
    /// replayed tail — `read_raw_output_tail` seeks by absolute offset, so a
    /// short count would hand clients a misaligned history.
    #[test]
    fn replay_tail_reports_the_full_log_length() {
        let path = unique_log_path();
        // After the output state, which truncates the log it opens.
        let mut output = test_output_state(&path, SessionSize::default());
        fs::write(&path, b"0123456789").expect("write test log");

        output.replay_tail(10, b"6789").expect("replay tail");

        assert_eq!(output.bytes_logged, 10);
        // A partial replay invalidates the cache, so history reads hit the file.
        assert!(output.log_cache.is_none());

        let (start, bytes) = read_raw_output_tail(&path, output.bytes_logged, 4);
        assert_eq!(start, 6);
        assert_eq!(bytes, b"6789");

        let _ = fs::remove_file(&path);
    }

    /// A full-length "tail" is the whole log, so the cache stays usable.
    #[test]
    fn replay_tail_of_a_whole_log_keeps_the_cache() {
        let path = unique_log_path();
        let mut output = test_output_state(&path, SessionSize::default());
        fs::write(&path, b"0123456789").expect("write test log");

        output.replay_tail(10, b"0123456789").expect("replay tail");

        assert_eq!(output.bytes_logged, 10);
        assert_eq!(output.log_cache.as_deref(), Some(&b"0123456789"[..]));

        let _ = fs::remove_file(&path);
    }

    /// `ingest` must drive the trim end to end: write past the bound, and the
    /// log shrinks, `bytes_logged` follows it, and subsequent output still lands
    /// at the end.
    #[test]
    fn ingest_trims_the_log_once_it_passes_the_bound() {
        let path = unique_log_path();
        let mut output = test_output_state(&path, SessionSize::default());
        output.max_log_bytes = 8;
        output.retain_log_bytes = 4;

        output.ingest(b"0123456789").expect("ingest past the bound");

        assert_eq!(output.bytes_logged, 4, "bytes_logged must track the trim");
        assert_eq!(fs::read(&path).expect("read log"), b"6789");

        output.ingest(b"ab").expect("ingest after trim");
        assert_eq!(fs::read(&path).expect("read log"), b"6789ab");
        assert_eq!(output.bytes_logged, 6);

        let _ = fs::remove_file(&path);
    }

    /// A failed trim must latch off, not retry on every subsequent write — an
    /// unwritable log would otherwise re-attempt a multi-megabyte rewrite per
    /// chunk of PTY output.
    ///
    /// Unix-only: it forces the failure by unlinking a file that is still open,
    /// which Windows may refuse or leave delete-pending.
    #[cfg(not(windows))]
    #[test]
    fn a_failed_trim_is_not_retried() {
        let path = unique_log_path();
        let mut output = test_output_state(&path, SessionSize::default());
        output.max_log_bytes = 8;
        output.retain_log_bytes = 4;

        // Delete the log out from under the handle so the trim's open fails.
        fs::remove_file(&path).expect("remove log");
        output.ingest(b"0123456789").expect("ingest past the bound");

        assert!(output.trim_disabled, "a failed trim must disable trimming");
        let logged = output.bytes_logged;
        assert!(logged > 8, "a failed trim must leave bytes_logged alone");

        // Re-create the log; a retry would now succeed, so if trimming still
        // fires the latch did not hold.
        fs::write(&path, b"0123456789").expect("recreate log");
        output.ingest(b"cd").expect("ingest after failed trim");
        assert!(output.bytes_logged > logged, "trimming must stay disabled");

        let _ = fs::remove_file(&path);
    }

    /// The log path is data from the manifest or a handover payload, so a
    /// corrupted one must not turn shutdown into an arbitrary-file delete.
    #[test]
    fn remove_session_log_refuses_a_mismatched_name() {
        let dir = std::env::temp_dir().join(format!(
            "triage-rmguard-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("create test dir");

        let session_id = SessionId::new("session-7").expect("session id");
        let bystander = dir.join("something-important.txt");
        let correct = dir.join("session-7.log");
        fs::write(&bystander, b"do not delete").expect("write bystander");
        fs::write(&correct, b"log").expect("write log");

        remove_session_log(&session_id, &bystander);
        assert!(
            bystander.exists(),
            "a path that is not this session's log must never be unlinked"
        );

        remove_session_log(&session_id, &correct);
        assert!(!correct.exists(), "the session's own log must be removed");

        let _ = fs::remove_dir_all(&dir);
    }

    /// Orphaned logs are reclaimed, but only once stale — and a log a session
    /// still refers to is never touched, however old it looks.
    #[test]
    fn purge_removes_only_stale_unreferenced_logs() {
        let dir = std::env::temp_dir().join(format!(
            "triage-purge-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).expect("create purge test dir");

        let orphan = dir.join("session-1.log");
        let referenced = dir.join("session-2.log");
        let unrelated = dir.join("sessions.json");
        for path in [&orphan, &referenced, &unrelated] {
            fs::write(path, b"x").expect("write test file");
        }

        // Spelled differently from what `read_dir` will produce — the manifest
        // records whatever absolute path a session was created with, and that can
        // denote the same file by another spelling. Matching must survive it, or
        // every referenced log is mistaken for an orphan and deleted.
        let manifest_paths = HashSet::from([dir.join("nested").join("..").join("session-2.log")]);
        assert_ne!(
            manifest_paths.iter().next().expect("manifest path"),
            &referenced,
            "the manifest path must differ textually from the scanned path"
        );

        // Nothing is stale yet, so even the orphan survives.
        purge_orphaned_session_logs(&dir, &manifest_paths, std::time::Duration::from_secs(3600));
        assert!(orphan.exists(), "fresh orphan must be kept");

        // With no grace period the orphan goes; the referenced log and the
        // non-.log manifest must both survive.
        purge_orphaned_session_logs(&dir, &manifest_paths, std::time::Duration::ZERO);
        assert!(!orphan.exists(), "stale orphan must be removed");
        assert!(referenced.exists(), "referenced log must never be removed");
        assert!(unrelated.exists(), "non-log files must be left alone");

        let _ = fs::remove_dir_all(&dir);
    }

    fn test_output_state(log_path: &PathBuf, size: SessionSize) -> OutputState {
        test_output_state_with_writer(log_path, size, Box::new(std::io::sink()))
    }

    fn test_output_state_with_writer(
        log_path: &PathBuf,
        size: SessionSize,
        writer: Box<dyn Write + Send>,
    ) -> OutputState {
        let log = OpenOptions::new()
            .create(true)
            .write(true)
            .truncate(true)
            .open(log_path)
            .expect("open test log");
        let writer = shared_pty_writer(writer);
        OutputState {
            log,
            log_path: log_path.clone(),
            trim_disabled: false,
            max_log_bytes: MAX_SESSION_LOG_BYTES,
            retain_log_bytes: SESSION_LOG_RETAIN_BYTES,
            terminal: terminal_with_writer(&size, writer),
            cwd_sequence_buffer: Vec::new(),
            bytes_logged: 0,
            output_seq: 0,
            log_cache: Some(Vec::new()),
        }
    }

    fn unique_log_dir() -> PathBuf {
        let unique = format!(
            "triage-session-manager-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        );
        std::env::temp_dir().join(unique)
    }

    #[test]
    fn default_log_dir_uses_xdg_state_home_when_set() {
        let log_dir = default_log_dir_from_env(
            Some(OsString::from("/tmp/triage-state")),
            Some(OsString::from("/tmp/home")),
            None,
        );

        assert_eq!(
            log_dir,
            PathBuf::from("/tmp/triage-state").join("triage/sessions")
        );
    }

    #[test]
    fn default_log_dir_falls_back_to_home_local_state() {
        let log_dir = default_log_dir_from_env(None, Some(OsString::from("/tmp/home")), None);

        assert_eq!(
            log_dir,
            PathBuf::from("/tmp/home").join(".local/state/triage/sessions")
        );
    }

    #[test]
    fn pairing_challenges_are_device_specific() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let first_client = ClientId::new("browser-a").expect("client id");
        let second_client = ClientId::new("browser-b").expect("client id");

        let first = manager
            .request_pairing_challenge(&first_client)
            .expect("first challenge");
        let repeated = manager
            .request_pairing_challenge(&first_client)
            .expect("repeat challenge");
        let second = manager
            .request_pairing_challenge(&second_client)
            .expect("second challenge");

        assert_eq!(first.device_code, repeated.device_code);
        assert_ne!(first.device_code, second.device_code);

        let pin = manager
            .approve_pairing_device_code(&first.device_code)
            .expect("issue pin");
        let wrong_client_result =
            triage_transport_ws::WebSocketAuthenticator::pair(&manager, &pin.pin, &second_client);
        assert!(wrong_client_result.is_err());

        let token =
            triage_transport_ws::WebSocketAuthenticator::pair(&manager, &pin.pin, &first_client)
                .expect("pair first client");
        assert!(
            triage_transport_ws::WebSocketAuthenticator::authenticate(
                &manager,
                &first_client,
                &token,
            )
            .expect("authenticate first client")
        );
        assert!(
            !triage_transport_ws::WebSocketAuthenticator::authenticate(
                &manager,
                &second_client,
                &token,
            )
            .expect("reject second client")
        );

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn pending_pairing_challenges_evict_oldest_unapproved_at_limit() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let first_client = ClientId::new("browser-0").expect("client id");
        let first = manager
            .request_pairing_challenge(&first_client)
            .expect("first challenge");

        for index in 1..MAX_PENDING_PAIRING_CHALLENGES {
            let client_id = ClientId::new(format!("browser-{index}")).expect("client id");
            manager
                .request_pairing_challenge(&client_id)
                .expect("challenge within limit");
        }

        manager
            .request_pairing_challenge(&first_client)
            .expect("existing challenge is reused at limit");

        let overflow_client = ClientId::new("overflow-browser").expect("client id");
        let overflow = manager
            .request_pairing_challenge(&overflow_client)
            .expect("overflow challenge evicts oldest unapproved challenge");

        let challenges = manager
            .pairing_challenges()
            .expect("pairing challenges lock");
        assert_eq!(challenges.len(), MAX_PENDING_PAIRING_CHALLENGES);
        assert!(!challenges.contains_key(&first.device_code));
        assert!(challenges.contains_key(&overflow.device_code));

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn long_pairing_client_id_is_rejected() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let client_id =
            ClientId::new("x".repeat(MAX_PAIRING_CLIENT_ID_LENGTH + 1)).expect("client id");

        let error = manager
            .request_pairing_challenge(&client_id)
            .expect_err("long client id should fail");
        assert!(error.to_string().contains("client id is too long"));

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn pairing_pin_expiry_is_clamped_to_device_code_expiry() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let client_id = ClientId::new("browser").expect("client id");
        let challenge = manager
            .request_pairing_challenge(&client_id)
            .expect("challenge");
        let challenge_expires_at_unix = unix_timestamp_secs().expect("unix timestamp") + 60;

        {
            let mut challenges = manager
                .pairing_challenges()
                .expect("pairing challenges lock");
            let stored = challenges
                .get_mut(&challenge.device_code)
                .expect("stored challenge");
            stored.expires_at = Instant::now() + Duration::from_secs(60);
            stored.expires_at_unix = challenge_expires_at_unix;
        }

        let pin = manager
            .approve_pairing_device_code(&challenge.device_code)
            .expect("issue pin");

        assert_eq!(pin.expires_at, challenge_expires_at_unix);

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn expired_pairing_pin_is_rejected_and_can_be_regenerated() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let client_id = ClientId::new("browser").expect("client id");
        let challenge = manager
            .request_pairing_challenge(&client_id)
            .expect("challenge");
        let pin = manager
            .approve_pairing_device_code(&challenge.device_code)
            .expect("issue pin");

        {
            let mut challenges = manager
                .pairing_challenges()
                .expect("pairing challenges lock");
            let challenge = challenges
                .get_mut(&challenge.device_code)
                .expect("stored challenge");
            challenge.pin.as_mut().expect("stored pin").expires_at =
                Instant::now() - Duration::from_secs(1);
        }

        let expired_result =
            triage_transport_ws::WebSocketAuthenticator::pair(&manager, &pin.pin, &client_id);
        assert!(expired_result.is_err());
        assert!(
            expired_result
                .expect_err("expired pin should fail")
                .to_string()
                .contains("expired")
        );

        let replacement = manager
            .approve_pairing_device_code(&challenge.device_code)
            .expect("regenerate pin");
        triage_transport_ws::WebSocketAuthenticator::pair(&manager, &replacement.pin, &client_id)
            .expect("replacement pin pairs");

        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn expired_pairing_challenge_is_replaced_for_same_device() {
        let log_dir = unique_log_dir();
        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        let client_id = ClientId::new("browser").expect("client id");
        let first = manager
            .request_pairing_challenge(&client_id)
            .expect("first challenge");

        {
            let mut challenges = manager
                .pairing_challenges()
                .expect("pairing challenges lock");
            challenges
                .get_mut(&first.device_code)
                .expect("stored challenge")
                .expires_at = Instant::now() - Duration::from_secs(1);
        }

        let second = manager
            .request_pairing_challenge(&client_id)
            .expect("replacement challenge");

        assert_ne!(first.device_code, second.device_code);
        let _ = std::fs::remove_dir_all(&log_dir);
    }

    #[test]
    fn normalize_pairing_code_maps_ambiguous_chars() {
        assert_eq!(normalize_pairing_code("abc def"), "ABCDEF");
        assert_eq!(normalize_pairing_code("oLi"), "011");
        assert_eq!(normalize_pairing_code("  9kxq4m7p  "), "9KXQ4M7P");
        assert_eq!(normalize_pairing_code("Oil-LIO"), "011-110");
    }

    fn git_test_command(cwd: &PathBuf, args: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(cwd)
            .args(args)
            .status()
            .expect("run git test command");
        assert!(status.success(), "git {args:?} failed");
    }

    /// The manifest half of the union is what protects a session whose restore
    /// *failed*: it is warn-skipped from the map but still listed, and still
    /// recoverable, so its log must survive the purge.
    ///
    /// Unix-only: the failure is forced by making the log unopenable, and the
    /// mode bits that do that are not portable (nor effective as root).
    #[cfg(not(windows))]
    #[test]
    fn purge_orphaned_logs_keeps_logs_the_manifest_still_references() {
        use std::os::unix::fs::PermissionsExt;

        let log_dir = unique_log_dir();
        let _ = fs::remove_dir_all(&log_dir);
        fs::create_dir_all(&log_dir).expect("create log dir");

        let referenced = log_dir.join("session-1.log");
        let orphan = log_dir.join("session-2.log");
        fs::write(&referenced, b"kept").expect("write referenced log");
        fs::write(&orphan, b"dropped").expect("write orphan log");
        // Unopenable, so `HistoricalSession::restore` fails and this session
        // never reaches the map — leaving the manifest as its only voucher.
        fs::set_permissions(&referenced, fs::Permissions::from_mode(0o000))
            .expect("make log unreadable");
        write_manifest(
            &log_dir,
            PersistedSession {
                id: SessionId::new("session-1").expect("session id"),
                command: "/bin/sh".into(),
                args: Vec::new(),
                cwd: None,
                size: SessionSize::default(),
                log_path: referenced.clone(),
                exited: true,
                last_known_cwd: None,
                last_activity_ms: 0,
            },
        );

        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        // Guard the premise: if the log were still restorable the session would
        // be in the map and the map half would protect it, so the assertion
        // below would pass without the manifest half ever being exercised.
        assert!(
            !manager
                .sessions()
                .expect("sessions")
                .contains_key(&SessionId::new("session-1").expect("session id")),
            "restore must have failed for this test to exercise the manifest half"
        );

        manager.purge_orphaned_logs_with_retention(std::time::Duration::ZERO);

        assert!(
            referenced.exists(),
            "a log the manifest still references must survive, even with no live session"
        );
        assert!(
            !orphan.exists(),
            "an unreferenced stale log must be removed"
        );

        let _ = fs::remove_dir_all(&log_dir);
    }

    /// An unreadable manifest means the union is missing half its input, so the
    /// purge must decline rather than delete on a partial picture.
    #[test]
    fn purge_orphaned_logs_skips_when_the_manifest_is_unreadable() {
        let log_dir = unique_log_dir();
        let _ = fs::remove_dir_all(&log_dir);
        fs::create_dir_all(&log_dir).expect("create log dir");

        let orphan = log_dir.join("session-9.log");
        fs::write(&orphan, b"stale").expect("write orphan log");
        fs::write(
            SessionManagerConfig::new(log_dir.clone()).manifest_path(),
            b"{ this is not json",
        )
        .expect("write corrupt manifest");

        let manager = SessionManager::new(SessionManagerConfig::new(log_dir.clone()));
        manager.purge_orphaned_logs_with_retention(std::time::Duration::ZERO);

        assert!(
            orphan.exists(),
            "a corrupt manifest must abort the purge, not license deleting everything"
        );

        let _ = fs::remove_dir_all(&log_dir);
    }

    fn read_manifest(log_dir: &Path) -> SessionManifest {
        let bytes = std::fs::read(SessionManagerConfig::new(log_dir.to_path_buf()).manifest_path())
            .expect("read manifest");
        serde_json::from_slice(&bytes).expect("decode manifest")
    }

    fn write_manifest(log_dir: &PathBuf, persisted: PersistedSession) {
        std::fs::create_dir_all(log_dir).expect("create log dir");
        let manifest = SessionManifest {
            version: 1,
            sessions: vec![persisted],
        };
        std::fs::write(
            SessionManagerConfig::new(log_dir.clone()).manifest_path(),
            serde_json::to_vec(&manifest).expect("encode manifest"),
        )
        .expect("write manifest");
    }

    struct RecordingWriter {
        bytes: Arc<Mutex<Vec<u8>>>,
    }

    impl Write for RecordingWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.bytes
                .lock()
                .map_err(|_| std::io::Error::other("recording writer lock poisoned"))?
                .extend_from_slice(buf);
            Ok(buf.len())
        }

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

    fn wait_for_recorded_bytes(bytes: &Arc<Mutex<Vec<u8>>>) {
        let deadline = Instant::now() + Duration::from_secs(1);

        loop {
            if !bytes.lock().expect("recorded bytes lock").is_empty() {
                return;
            }
            assert!(
                Instant::now() < deadline,
                "timed out waiting for recorded terminal reply"
            );
            std::thread::sleep(Duration::from_millis(10));
        }
    }

    #[cfg(windows)]
    fn long_running_shell_command() -> &'static str {
        "cmd.exe"
    }

    #[cfg(not(windows))]
    fn long_running_shell_command() -> &'static str {
        "/bin/sh"
    }

    #[cfg(windows)]
    fn command_that_prints_marker(log_path: PathBuf) -> SessionConfig {
        let mut config = SessionConfig::new("cmd.exe", log_path);
        config.args = vec!["/C".to_string(), "echo triage-ready".to_string()];
        config
    }

    #[cfg(not(windows))]
    fn command_that_prints_marker(log_path: PathBuf) -> SessionConfig {
        let mut config = SessionConfig::new("/bin/sh", log_path);
        config.args = vec!["-c".to_string(), "printf 'triage-ready\\r\\n'".to_string()];
        config
    }

    #[cfg(windows)]
    fn long_running_shell(log_path: PathBuf) -> SessionConfig {
        SessionConfig::new("cmd.exe", log_path)
    }

    #[cfg(not(windows))]
    fn long_running_shell(log_path: PathBuf) -> SessionConfig {
        SessionConfig::new("/bin/sh", log_path)
    }

    #[cfg(windows)]
    fn input_that_prints_marker() -> Vec<u8> {
        b"echo actor-ready\r\n".to_vec()
    }

    #[cfg(not(windows))]
    fn input_that_prints_marker() -> Vec<u8> {
        b"printf 'actor-ready\\r\\n'\n".to_vec()
    }

    fn wait_for_visible_marker(actor: &SessionActor, marker: &str) -> SessionSnapshot {
        let deadline = Instant::now() + Duration::from_secs(5);

        loop {
            let snapshot = actor.snapshot().expect("snapshot session actor");
            if snapshot.visible_rows.iter().any(|row| row.contains(marker)) {
                return snapshot;
            }

            assert!(
                Instant::now() < deadline,
                "timed out waiting for {marker}; latest snapshot: {:?}",
                snapshot
            );
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    fn wait_for_exited_snapshot(actor: &SessionActor) -> SessionSnapshot {
        let deadline = Instant::now() + Duration::from_secs(5);

        loop {
            let snapshot = actor.snapshot().expect("snapshot session actor");
            if snapshot.exited {
                return snapshot;
            }

            assert!(
                Instant::now() < deadline,
                "timed out waiting for session exit; latest snapshot: {:?}",
                snapshot
            );
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    fn wait_for_manager_marker(
        manager: &SessionManager,
        session_id: SessionId,
        marker: &str,
    ) -> SessionSnapshot {
        let deadline = Instant::now() + Duration::from_secs(5);

        loop {
            let snapshot = manager
                .snapshot_session(session_id.clone())
                .expect("snapshot managed session");
            if snapshot.visible_rows.iter().any(|row| row.contains(marker))
                || snapshot.visible_rows.join("").contains(marker)
            {
                return snapshot;
            }

            assert!(
                Instant::now() < deadline,
                "timed out waiting for {marker}; latest snapshot: {:?}",
                snapshot
            );
            std::thread::sleep(Duration::from_millis(20));
        }
    }

    fn wait_for_output_event(
        receiver: &SessionEventReceiver,
        session_id: &SessionId,
        marker: &str,
    ) {
        let deadline = Instant::now() + Duration::from_secs(5);
        let mut output = Vec::new();

        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            assert!(
                !remaining.is_zero(),
                "timed out waiting for output marker {marker}; latest output: {:?}",
                String::from_utf8_lossy(&output)
            );
            let event = receiver
                .recv_timeout(remaining.min(Duration::from_millis(100)))
                .unwrap_or_else(|error| {
                    panic!("event stream ended while waiting for output marker {marker}: {error}")
                })
                .event;
            if let SessionEvent::Output {
                session_id: event_session_id,
                bytes,
                ..
            } = event
                && &event_session_id == session_id
            {
                output.extend_from_slice(&bytes);
                if output.len() > 8192 {
                    output.drain(..output.len() - 8192);
                }
                if String::from_utf8_lossy(&output).contains(marker) {
                    return;
                }
            }
        }
    }

    fn wait_for_snapshot_event(
        receiver: &SessionEventReceiver,
        session_id: &SessionId,
        rows: usize,
    ) {
        assert!(matches!(
            wait_for_event(receiver, "resize snapshot event", |event| {
                matches!(
                    event,
                    SessionEvent::Snapshot { session_id: event_session_id, snapshot }
                        if event_session_id == session_id && snapshot.size.rows == rows
                )
            }),
            SessionEvent::Snapshot { .. }
        ));
    }

    fn wait_for_exit_event(receiver: &SessionEventReceiver, session_id: &SessionId) {
        assert!(matches!(
            wait_for_event(receiver, "exit event", |event| {
                matches!(
                    event,
                    SessionEvent::Exited { session_id: event_session_id, completed }
                        if event_session_id == session_id && completed.output_seq > 0
                )
            }),
            SessionEvent::Exited { .. }
        ));
    }

    fn assert_no_exit_event(receiver: &SessionEventReceiver, session_id: &SessionId) {
        let deadline = Instant::now() + Duration::from_millis(100);

        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return;
            }

            match receiver.recv_timeout(remaining.min(Duration::from_millis(20))) {
                Ok(envelope)
                    if matches!(
                        envelope.event,
                        SessionEvent::Exited {
                            session_id: ref event_session_id,
                            ..
                        } if event_session_id == session_id
                    ) =>
                {
                    panic!("received duplicate exit event for session {session_id}");
                }
                Ok(_) => {}
                Err(std::sync::mpsc::RecvTimeoutError::Timeout)
                | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => return,
            }
        }
    }

    fn wait_for_event(
        receiver: &SessionEventReceiver,
        label: &str,
        matches_event: impl Fn(&SessionEvent) -> bool,
    ) -> SessionEvent {
        let deadline = Instant::now() + Duration::from_secs(5);

        loop {
            let remaining = deadline.saturating_duration_since(Instant::now());
            assert!(!remaining.is_zero(), "timed out waiting for {label}");
            match receiver.recv_timeout(remaining.min(Duration::from_millis(100))) {
                Ok(envelope) if matches_event(&envelope.event) => return envelope.event,
                Ok(_) => {}
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                    panic!("event stream closed while waiting for {label}");
                }
            }
        }
    }
}