croft-software 0.2.232

VSCode-style TUI written in Rust
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
//! Replicated text document for multiplayer Phase D (independent viewports).
//!
//! croft's shared-viewport multiplayer (src/session_host.rs) broadcasts one
//! PTY verbatim, so every participant sees the same screen. Phase D lets
//! participants edit the same buffer from independent viewports, which needs
//! one croft process per participant holding its own replica of the buffer.
//! With no central authority to serialize edits, concurrent inserts and
//! deletes must still converge to the same text on every replica: that is the
//! job of a CRDT.
//!
//! [`CollabDoc`] wraps a [`cola::Replica`] (which tracks only edit *positions*)
//! next to the canonical linear text (which croft owns, exactly as it owns the
//! editor's `Vec<String>`). A local edit returns an [`Op`] to broadcast; a
//! remote [`Op`] is integrated back into the text at the position cola resolves
//! against concurrent edits.
//!
//! This module is the whole collab layer below the app:
//! - [`CollabDoc`]: the replicated buffer, with [`text_delta_ops`] extracting
//!   ops from arbitrary text-state transitions (diff-based, so the editor
//!   needs no apply-edit chokepoint).
//! - [`byte_offset`]/[`position`]: bridge the editor's `(row, char-column)` to
//!   `CollabDoc`'s linear byte offsets, UTF-8 aware.
//! - [`Envelope`]/[`CollabMsg`] + [`relay_serve`]: the wire messages and the
//!   dumb fan-out relay over a dedicated collab socket.
//! - [`CollabChannel`] + [`CollabSession`]: a participant's connection and
//!   per-file state machine (bootstrap handshake, site allocation, backlog).
//!
//! The app side (`App::poll_collab`, src/app/mod.rs) feeds buffer text in
//! and applies the returned [`CollabEvent`]s to open tabs.

use std::io::{Read, Write};

use cola::{Deletion, Insertion, Replica};
use serde::{Deserialize, Serialize};

/// One edit to send to (or receive from) other replicas. cola's operations
/// carry position metadata but not the inserted characters, so an insert also
/// carries the literal text; a delete needs only the range metadata.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Op {
    Insert { insertion: Insertion, text: String },
    Delete { deletion: Deletion },
}

/// One text change `apply_remote` resolved against the local replica: delete
/// `deleted` bytes at `at`, then insert `inserted` at `at`. Spans are emitted
/// in application order, each relative to the text after every earlier span
/// in the same batch was applied, so a consumer replays them sequentially
/// (the editor wiring converts each to line coordinates via [`position`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedSpan {
    pub at: usize,
    pub deleted: usize,
    pub inserted: String,
}

/// A replicated text buffer: the canonical text plus the cola replica that
/// resolves concurrent edits into a convergent order.
pub struct CollabDoc {
    replica: Replica,
    text: String,
    /// Bumped on every text mutation (local or integrated remote). The
    /// editor wiring pins each buffer of a live file to the generation it
    /// last synced at, so a buffer created after the file went live (a
    /// split duplicate loaded from stale disk text) is detectable and gets
    /// seeded from the replica instead of poisoning the session.
    text_gen: u64,
    /// Literal text of insertions cola backlogged (its backlog keeps only
    /// position metadata), keyed by the run's identity so the drain can
    /// splice the right characters back in. An entry for a duplicate
    /// delivery is never drained; the transport delivers each op once, so
    /// that leak never materializes.
    pending_insert_texts: std::collections::HashMap<(u64, usize), String>,
}

/// Identity of an insertion's text run: who inserted it and where the run
/// starts on that author's own timeline. Stable between the op arriving
/// (unmergeable) and the backlog yielding it (ready).
fn insert_key(text: &cola::Text) -> (u64, usize) {
    (text.inserted_by(), text.temporal_range().start)
}

impl CollabDoc {
    /// A fresh document with `id` as this replica's identity and `initial` as
    /// its starting contents. Every replica of the same document must start
    /// from the same text (bootstrap it once, then exchange [`Op`]s).
    pub fn new(id: u64, initial: &str) -> Self {
        Self {
            replica: Replica::new(id, initial.len()),
            text: initial.to_string(),
            text_gen: 1,
            pending_insert_texts: std::collections::HashMap::new(),
        }
    }

    /// A second replica of this document for a new peer `id`, sharing the
    /// current contents and edit history so their future ops integrate.
    /// In-process only: production peers join over [`Self::from_snapshot`];
    /// the convergence tests bootstrap through this.
    #[allow(dead_code)]
    pub fn fork(&self, id: u64) -> Self {
        Self {
            replica: self.replica.fork(id),
            text: self.text.clone(),
            text_gen: 1,
            pending_insert_texts: self.pending_insert_texts.clone(),
        }
    }

    /// The replica's edit history in cola's compact binary format, sent in a
    /// [`CollabMsg::SnapshotReply`] next to the canonical text so a joining
    /// peer's future ops integrate against the same history.
    pub fn encode(&self) -> Vec<u8> {
        self.replica.encode().as_bytes().to_vec()
    }

    /// Rebuild a document from a snapshot (`text` + [`encode`](Self::encode)d
    /// history) under a fresh site `id` — the joining side of bootstrap.
    /// Fails on corrupt bytes or a cola protocol mismatch between peers.
    pub fn from_snapshot(id: u64, text: &str, encoded: &[u8]) -> anyhow::Result<Self> {
        let replica = Replica::decode(id, &cola::EncodedReplica::from_bytes(encoded))?;
        Ok(Self {
            replica,
            text: text.to_string(),
            text_gen: 1,
            pending_insert_texts: std::collections::HashMap::new(),
        })
    }

    pub fn text(&self) -> &str {
        &self.text
    }

    /// The current text generation (see the field doc).
    pub fn text_gen(&self) -> u64 {
        self.text_gen
    }

    /// This replica's site id (unique per participant per document).
    pub fn site_id(&self) -> u64 {
        self.replica.id()
    }

    /// Apply a local insertion at byte offset `at` and return the op to
    /// broadcast to the other replicas.
    pub fn local_insert(&mut self, at: usize, s: &str) -> Op {
        self.text_gen += 1;
        self.text.insert_str(at, s);
        let insertion = self.replica.inserted(at, s.len());
        Op::Insert {
            insertion,
            text: s.to_string(),
        }
    }

    /// Apply a local deletion of byte range `at..at+len` and return the op.
    pub fn local_delete(&mut self, at: usize, len: usize) -> Op {
        self.text_gen += 1;
        let deletion = self.replica.deleted(at..at + len);
        self.text.replace_range(at..at + len, "");
        Op::Delete { deletion }
    }

    /// Integrate an op from another replica into this document's text at the
    /// position cola resolves against any concurrent local edits, returning
    /// the text changes it caused (see [`ResolvedSpan`] for the replay
    /// contract). An op whose causal context has not arrived yet integrates
    /// to nothing now — cola backlogs its position metadata, this document
    /// stashes its text — and the drain after any later op that supplies the
    /// context applies it, so out-of-order delivery never diverges replicas.
    pub fn apply_remote(&mut self, op: &Op) -> Vec<ResolvedSpan> {
        let mut spans = Vec::new();
        match op {
            Op::Insert { insertion, text } => {
                match self.replica.integrate_insertion(insertion) {
                    Some(offset) => {
                        self.text.insert_str(offset, text);
                        spans.push(ResolvedSpan {
                            at: offset,
                            deleted: 0,
                            inserted: text.clone(),
                        });
                    }
                    None => {
                        // Backlogged (or a duplicate; see the field docs).
                        self.pending_insert_texts
                            .insert(insert_key(insertion.text()), text.clone());
                    }
                }
            }
            Op::Delete { deletion } => {
                let ranges = self.replica.integrate_deletion(deletion);
                self.splice_deletion_ranges(ranges, &mut spans);
            }
        }
        self.drain_backlog(&mut spans);
        if !spans.is_empty() {
            self.text_gen += 1;
        }
        spans
    }

    /// Splice one integrated deletion's ranges out of the text. The ranges
    /// come back ascending and non-overlapping, all relative to the text
    /// before any of them is applied, so splicing back-to-front keeps every
    /// offset valid — and the emitted spans, in that same order, still honor
    /// the sequential replay contract (removing a later range never shifts
    /// an earlier one).
    fn splice_deletion_ranges(
        &mut self,
        mut ranges: Vec<std::ops::Range<usize>>,
        spans: &mut Vec<ResolvedSpan>,
    ) {
        ranges.sort_by_key(|r| std::cmp::Reverse(r.start));
        for range in ranges {
            spans.push(ResolvedSpan {
                at: range.start,
                deleted: range.len(),
                inserted: String::new(),
            });
            self.text.replace_range(range, "");
        }
    }

    /// Apply every backlogged op that became ready. cola's backlog iterators
    /// merge as they yield; each yielded offset is relative to the text with
    /// all earlier yields applied, which is exactly how the text is updated.
    /// Insertions loop to a fixed point because an insertion's anchor can sit
    /// inside another author's run, so one merge can unlock an author's queue
    /// the same iterator pass already skipped. Deletions then drain once:
    /// merging a deletion never unlocks anything (it advances no version map
    /// and removes no anchors).
    fn drain_backlog(&mut self, spans: &mut Vec<ResolvedSpan>) {
        loop {
            let ready: Vec<(cola::Text, usize)> = self.replica.backlogged_insertions().collect();
            if ready.is_empty() {
                break;
            }
            for (run, offset) in ready {
                let inserted = match self.pending_insert_texts.remove(&insert_key(&run)) {
                    Some(s) => s,
                    None => {
                        // Only reachable when a snapshot's encoded history
                        // carried a backlog (the stash does not travel with
                        // it). Splice in placeholder spaces so text offsets
                        // stay aligned with the replica instead of corrupting
                        // every later edit; the characters are wrong until
                        // the owner's next resync.
                        debug_assert!(false, "backlogged insertion with no stashed text");
                        " ".repeat(run.temporal_range().len())
                    }
                };
                self.text.insert_str(offset, &inserted);
                spans.push(ResolvedSpan {
                    at: offset,
                    deleted: 0,
                    inserted,
                });
            }
        }
        let ready: Vec<Vec<std::ops::Range<usize>>> = self.replica.backlogged_deletions().collect();
        for ranges in ready {
            self.splice_deletion_ranges(ranges, spans);
        }
    }
}

/// Diff `doc`'s current text against `new` and apply the difference as local
/// ops, returned for broadcast. This is the op-extraction path for the live
/// editor (slice 4): croft's editor has no single apply-edit chokepoint (~46
/// scattered mutation sites), so instead of threading positional deltas
/// through every one, each shared file diffs its last-synced text against the
/// current buffer whenever its edit seq advances. Multi-cursor edits, paste,
/// undo, and wholesale reloads all reduce to a text-state transition here.
pub fn text_delta_ops(doc: &mut CollabDoc, new: &str) -> Vec<Op> {
    use similar::{ChangeTag, TextDiff};
    let old = doc.text().to_string();
    // A timed-out diff yields a coarser but still valid edit script, bounding
    // the cost of reload-sized changes on the interactive tick.
    let diff = TextDiff::configure()
        .timeout(std::time::Duration::from_millis(200))
        .diff_chars(old.as_str(), new);
    let mut ops = Vec::new();
    let mut cursor = 0usize; // byte offset into doc's evolving text
    let mut del = 0usize; // bytes of a pending delete run
    let mut ins = String::new(); // text of a pending insert run
    let mut flush = |doc: &mut CollabDoc, cursor: &mut usize, del: &mut usize, ins: &mut String| {
        if *del > 0 {
            ops.push(doc.local_delete(*cursor, *del));
            *del = 0;
        }
        if !ins.is_empty() {
            ops.push(doc.local_insert(*cursor, ins));
            *cursor += ins.len();
            ins.clear();
        }
    };
    for change in diff.iter_all_changes() {
        let bytes = change.value().len();
        match change.tag() {
            ChangeTag::Equal => {
                flush(doc, &mut cursor, &mut del, &mut ins);
                cursor += bytes;
            }
            ChangeTag::Delete => del += bytes,
            ChangeTag::Insert => ins.push_str(change.value()),
        }
    }
    flush(doc, &mut cursor, &mut del, &mut ins);
    debug_assert_eq!(doc.text(), new);
    ops
}

/// Three-way merge of a shared file after an offline gap: `base` is the last
/// text every participant agreed on (harvested when the link died), `ours`
/// the local buffer that diverged offline, `theirs` the owner's bootstrap
/// snapshot (which may carry edits made during the outage). Line-level
/// hunks against `base` from both sides are combined; where they touch the
/// same lines, ours wins — the offline buffer is the only home of that work,
/// while the owner's side of a genuine conflict still lives in its replicas'
/// history. Replaying `ours` wholesale instead read every owner edit made
/// during the outage as a deletion.
pub fn merge_offline_texts(base: &str, ours: &str, theirs: &str) -> String {
    use similar::{ChangeTag, TextDiff};
    /// A run of changed base lines: half-open line range + replacement
    /// lines; a pure insertion has start == end.
    type Hunk = (usize, usize, Vec<String>);
    if base == theirs {
        return ours.to_string(); // nothing happened on their side
    }
    if base == ours {
        return theirs.to_string(); // nothing happened here
    }

    // Line hunks against base.
    fn hunks(base_lines: &[&str], derived_lines: &[&str]) -> Vec<Hunk> {
        let diff = TextDiff::from_slices(base_lines, derived_lines);
        let mut out: Vec<Hunk> = Vec::new();
        let mut cur: Option<Hunk> = None;
        let mut old_pos = 0usize;
        for change in diff.iter_all_changes() {
            match change.tag() {
                ChangeTag::Equal => {
                    if let Some(h) = cur.take() {
                        out.push(h);
                    }
                    old_pos += 1;
                }
                ChangeTag::Delete => {
                    match &mut cur {
                        Some(h) => h.1 = old_pos + 1,
                        None => cur = Some((old_pos, old_pos + 1, Vec::new())),
                    }
                    old_pos += 1;
                }
                ChangeTag::Insert => {
                    let line = change.value().to_string();
                    match &mut cur {
                        Some(h) => h.2.push(line),
                        None => cur = Some((old_pos, old_pos, vec![line])),
                    }
                }
            }
        }
        if let Some(h) = cur.take() {
            out.push(h);
        }
        out
    }

    let base_lines: Vec<&str> = base.split('\n').collect();
    let ours_hunks = hunks(&base_lines, &ours.split('\n').collect::<Vec<_>>());
    let theirs_hunks = hunks(&base_lines, &theirs.split('\n').collect::<Vec<_>>());

    // Two hunks conflict when their base ranges genuinely intersect, or when
    // both are insertions at the same point (no order between them exists).
    // An insertion merely TOUCHING the other side's replacement at its start
    // offset is not a conflict: both survive, ours-first at the boundary.
    let conflicts =
        |a: &Hunk, b: &Hunk| (a.0 < b.1 && b.0 < a.1) || (a.0 == b.0 && a.0 == a.1 && b.0 == b.1);
    let mut chosen: Vec<(&Hunk, bool)> = ours_hunks.iter().map(|h| (h, true)).collect();
    for th in &theirs_hunks {
        if !ours_hunks.iter().any(|oh| conflicts(oh, th)) {
            chosen.push((th, false));
        }
    }
    // Ours-first at equal starts, so an offline insertion lands before a
    // same-point owner replacement; either order is textually valid.
    chosen.sort_by_key(|(h, is_ours)| (h.0, !*is_ours));

    let mut out: Vec<String> = Vec::new();
    let mut pos = 0usize;
    for (h, _) in chosen {
        while pos < h.0 {
            out.push(base_lines[pos].to_string());
            pos += 1;
        }
        out.extend(h.2.iter().cloned());
        pos = pos.max(h.1);
    }
    while pos < base_lines.len() {
        out.push(base_lines[pos].to_string());
        pos += 1;
    }
    out.join("\n")
}

/// Byte offset of the char-indexed position `(row, col)` within the text
/// formed by joining `lines` with `'\n'` — the linear coordinate CollabDoc and
/// cola operate in. croft's editor addresses the buffer as `(row, char-column)`
/// (`cursor_col` is a char index throughout src/widgets/editor.rs); cola
/// addresses it as one byte offset. The editor wiring only converts the other
/// way ([`position`]; extraction is diff-based); this direction anchors the
/// `croft pair` edit fences (src/pair.rs, `range_bytes`), whose coordinates
/// arrive as char positions.
pub fn byte_offset(lines: &[String], row: usize, col: usize) -> usize {
    let mut offset = 0;
    for line in lines.iter().take(row) {
        offset += line.len() + 1; // +1 for the '\n' separator
    }
    if let Some(line) = lines.get(row) {
        offset += line
            .char_indices()
            .nth(col)
            .map(|(b, _)| b)
            .unwrap_or(line.len());
    }
    offset
}

/// Inverse of [`byte_offset`]: the `(row, char-column)` of a byte `offset`.
/// `offset` is assumed char-aligned (every offset cola or [`byte_offset`]
/// produces is); a mid-char offset would clamp at the enclosing char boundary
/// via `chars().count()`. Past-the-end clamps to the end of the last line.
pub fn position(lines: &[String], offset: usize) -> (usize, usize) {
    let mut remaining = offset;
    for (row, line) in lines.iter().enumerate() {
        let line_bytes = line.len();
        if remaining <= line_bytes {
            let end = line
                .char_indices()
                .map(|(b, _)| b)
                .chain(std::iter::once(line_bytes))
                .take_while(|&b| b <= remaining)
                .count()
                .saturating_sub(1);
            return (row, end);
        }
        remaining -= line_bytes + 1; // consume the line and its '\n'
    }
    let row = lines.len().saturating_sub(1);
    let col = lines.get(row).map(|l| l.chars().count()).unwrap_or(0);
    (row, col)
}

/// A per-file, per-site edit on the wire: which file (a workspace-relative
/// key), which participant produced it, and the op. Peers route it to their
/// `CollabDoc` for that file and integrate.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Envelope {
    pub file: String,
    pub site: u64,
    pub op: Op,
}

impl Envelope {
    /// Serialize into one framed message for the collab socket, reusing the
    /// session-host wire framing (`[type][len][payload]`). Production sends
    /// [`CollabMsg::Op`] (via [`CollabMsg::encode`]); the transport tests
    /// drive the relay with bare envelopes.
    #[allow(dead_code)]
    pub fn encode(&self) -> Vec<u8> {
        let json = serde_json::to_vec(self).unwrap_or_default();
        crate::session_host::encode_bytes_frame(&json)
    }
}

/// Everything the collab socket carries: edit ops plus the bootstrap
/// handshake. The relay stays a dumb fan-out (every message is a
/// `Frame::Bytes` broadcast to the other participants); peers filter by
/// `file` and, for snapshots, by `nonce` — only the save owner answers a
/// [`SnapshotRequest`], so a request never draws competing replies.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum CollabMsg {
    Op(Envelope),
    /// A joining peer (or one opening a file already shared) asks for the
    /// document's current state; `nonce` pairs the reply to this request.
    SnapshotRequest {
        file: String,
        nonce: u64,
    },
    /// The owner's atomic answer: the canonical text, the encoded replica
    /// history it corresponds to, and the site id the owner allocated for
    /// the joiner (site ids must be unique per participant; the owner is
    /// the single allocator, so ids never collide).
    SnapshotReply {
        file: String,
        nonce: u64,
        assigned_site: u64,
        text: String,
        replica: Vec<u8>,
    },
    /// A participant's caret moved: peers with the file open paint it as a
    /// ghost caret in that participant's color, with a name tag while it
    /// moves. `name` defaults empty so a 0.1.632 peer's carets still parse
    /// (site ids are per-file, so identity has to ride the wire).
    Caret {
        file: String,
        site: u64,
        row: usize,
        col: usize,
        #[serde(default)]
        name: String,
    },
    /// An AI pilot's token stream into `file` started (`active`) or ended
    /// (finished, cancelled, or reverted). Peers surface the state (badge,
    /// stop button) while active. `site` is the pilot's site id in `file`
    /// when the doc is live, 0 before bootstrap — identity is `name`, same
    /// as carets. 0.1.633 peers drop this variant in `drain`.
    StreamState {
        site: u64,
        name: String,
        file: String,
        active: bool,
    },
    /// Any participant asks the streaming pilot to stop and revert. Bare by
    /// design: at most one stream runs per relay (one pilot seat), so there
    /// is nothing to address.
    StreamCancel {},
    /// A sticky note (#367) was added or changed. Peers keep the newest
    /// revision of each note; older peers drop the variant in `drain`.
    Note {
        note: crate::sticky_notes::Note,
    },
    /// A joiner asks the owner for every note in the workspace.
    NotesRequest {},
    /// The owner's heartbeat (#1147), every [`OWNER_HEARTBEAT`]: guests that
    /// stop hearing it for [`OWNER_GONE_AFTER`] treat the owner as gone.
    /// Older peers drop the variant in `drain`, and a guest that never
    /// heard one never decides an owner left.
    OwnerHere {},
    /// The owner is quitting (#1147): guests stop deferring saves to it.
    OwnerLeft {},
}

impl CollabMsg {
    /// Serialize into one framed message for the collab socket, same framing
    /// as [`Envelope::encode`].
    pub fn encode(&self) -> Vec<u8> {
        let json = serde_json::to_vec(self).unwrap_or_default();
        crate::session_host::encode_bytes_frame(&json)
    }
}

/// Fan each participant's [`Envelope`] frames out to the *other* participants.
/// A dumb multiplexer, exactly like the PTY broadcast: `cola` makes ordering
/// the client's job, so the relay never inspects an op. Runs until the socket
/// closes; one thread per client. Distinct socket from the PTY mux
/// (`<hash>.collab.sock`), so it never carries terminal bytes.
pub fn relay_serve(socket: &std::path::Path) -> anyhow::Result<()> {
    // Attach-or-create: a live relay already owns the socket; binding over
    // it would strand that relay's connected clients mid-session. The
    // liveness check here is only a fast path - creation itself (stale-file
    // removal included) is serialized inside the binder, so two creators
    // racing past this line cannot both publish: the loser is told the
    // winner is alive and attaches, which is exactly these semantics.
    if crate::session::is_alive(socket) {
        return Ok(());
    }
    if let Some(dir) = socket.parent() {
        std::fs::create_dir_all(dir)?;
    }
    let listener = match crate::session::bind_socket_0600(socket) {
        Ok(l) => l,
        Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => return Ok(()),
        Err(e) => return Err(e.into()),
    };

    let clients: std::sync::Arc<std::sync::Mutex<Vec<Peer>>> =
        std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    for stream in listener.incoming().flatten() {
        // Bounded writes: forwarding holds the global client mutex, so one
        // peer that stops draining (SIGSTOPped, wedged mid-write) used to
        // block its writer forever — starving every other peer AND their
        // reader threads queued on the same mutex, a cross-process
        // deadlock. A write that cannot complete inside the timeout fails,
        // and the failed peer is dropped (see relay_client). Setting the
        // timeout itself fails with EINVAL on macOS when the peer already
        // hung up (the liveness probe connects and drops instantly) — such
        // a socket cannot block a write, so serve it rather than let one
        // dead accept kill the loop for every later peer.
        let _ = stream.set_write_timeout(Some(RELAY_WRITE_TIMEOUT));
        let tx = std::sync::Arc::new(std::sync::Mutex::new(stream.try_clone()?));
        clients.lock().unwrap().push(std::sync::Arc::clone(&tx));
        let clients = std::sync::Arc::clone(&clients);
        std::thread::spawn(move || relay_client(stream, &tx, &clients));
    }
    Ok(())
}

/// The argv (after the croft binary itself) that serves a relay on `socket`.
/// Pure so it can be unit-tested.
fn detached_relay_argv(socket: &std::path::Path) -> Vec<String> {
    vec![
        String::from("collab-relay"),
        String::from("--socket"),
        socket.to_string_lossy().into_owned(),
    ]
}

/// Ensure a relay is serving `socket`: done if one is alive, otherwise spawn
/// one detached (same null-stdio + setsid pattern as
/// `session_host::spawn_detached_server`, so it outlives this participant's
/// terminal) and wait for it to bind.
pub fn ensure_relay(socket: &std::path::Path) -> anyhow::Result<()> {
    use anyhow::Context;
    if crate::session::is_alive(socket) {
        return Ok(());
    }
    let exe = std::env::current_exe().context("resolving croft binary path")?;
    let mut cmd = std::process::Command::new(exe);
    cmd.args(detached_relay_argv(socket));
    cmd.stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null());
    #[cfg(unix)]
    unsafe {
        use std::os::unix::process::CommandExt;
        cmd.pre_exec(|| {
            libc::setsid();
            Ok(())
        });
    }
    cmd.spawn().context("spawning collab relay")?;
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    while !crate::session::is_alive(socket) {
        if std::time::Instant::now() > deadline {
            anyhow::bail!("collab relay did not start on {}", socket.display());
        }
        std::thread::sleep(std::time::Duration::from_millis(25));
    }
    Ok(())
}

/// Which side of the collab session this process is (see docs/MULTIPLAYER.md):
/// the owner is the mux's inner croft — it answers bootstrap requests,
/// allocates site ids, and is the only participant that writes shared files
/// to disk; guests are the solo-viewport processes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CollabRole {
    Owner,
    Guest,
}

/// This process's handle on the collab relay: a non-blocking framed stream
/// of [`CollabMsg`]s, mirroring `session_host::InnerChannel` (the launch
/// side puts the socket and role in the environment; the app connects).
pub struct CollabChannel {
    stream: std::os::unix::net::UnixStream,
    reader: crate::session_host::FrameReader,
    pub role: CollabRole,
    /// Latched on EOF or a hard error: the relay hung up. Nothing clears
    /// it — the owner of the channel drops it and reconnects. Without the
    /// latch a dead relay read exactly like an idle one, and a guest kept
    /// typing into a buffer whose ops reached nobody, with saves still
    /// gated, so the work existed only in RAM.
    dead: bool,
}

impl CollabChannel {
    /// The socket and role the launch tail exported, if this croft was
    /// started as a collab participant. Separate from [`from_env`] so the
    /// app can keep retrying the connect while the relay comes up.
    ///
    /// [`from_env`]: Self::from_env
    pub fn env_config() -> Option<(std::path::PathBuf, CollabRole)> {
        // Hermetic under test: croft exports these vars into its child
        // shells, so a `cargo test` launched from a croft session handed
        // every test-built App a live Owner seat — skipping the single-host
        // lock gate and failing the pair/collab tests that exercise it
        // (#55). Same treatment as the theme registry's config read. Tests
        // that want a collab config inject it directly.
        if cfg!(test) {
            return None;
        }
        Self::env_config_from(
            std::env::var_os("CROFT_COLLAB_SOCKET"),
            std::env::var("CROFT_COLLAB_ROLE").ok(),
        )
    }

    /// The pure half of [`env_config`]: parse the launch-tail exports.
    /// Separate so the parsing contract stays testable without touching the
    /// process environment (in-process `set_var` races sibling test
    /// threads).
    ///
    /// [`env_config`]: Self::env_config
    fn env_config_from(
        socket: Option<std::ffi::OsString>,
        role: Option<String>,
    ) -> Option<(std::path::PathBuf, CollabRole)> {
        let socket = std::path::PathBuf::from(socket?);
        let role = match role?.as_str() {
            "owner" => CollabRole::Owner,
            "guest" => CollabRole::Guest,
            _ => return None,
        };
        Some((socket, role))
    }

    pub fn connect(socket: &std::path::Path, role: CollabRole) -> Option<Self> {
        let stream = std::os::unix::net::UnixStream::connect(socket).ok()?;
        // Non-blocking so the app's per-tick drain never stalls the render
        // loop, same as InnerChannel.
        stream.set_nonblocking(true).ok()?;
        Some(Self {
            stream,
            reader: crate::session_host::FrameReader::new(),
            role,
            dead: false,
        })
    }

    /// True once the relay hung up (EOF or a failed write): the channel is
    /// unusable and its owner should drop it and reconnect.
    pub fn is_dead(&self) -> bool {
        self.dead
    }

    /// Broadcast one message to the other participants. Returns false when
    /// the relay is gone (which also latches [`Self::is_dead`], so the
    /// session surfaces the loss even though callers fire-and-forget).
    pub fn send(&mut self, msg: &CollabMsg) -> bool {
        let sent = crate::session_host::write_frame_blocking(&mut self.stream, &msg.encode());
        if !sent {
            self.dead = true;
        }
        sent
    }

    /// Drain every message waiting on the channel, in arrival order.
    /// Non-blocking; malformed frames are skipped (a newer peer may speak a
    /// larger CollabMsg — ignoring what this side cannot parse beats dying).
    pub fn drain(&mut self) -> Vec<CollabMsg> {
        let mut msgs = Vec::new();
        let mut buf = [0u8; 16384];
        loop {
            match self.stream.read(&mut buf) {
                // EOF and hard errors are the relay hanging up — distinct
                // from WouldBlock (idle), which they used to be lumped with.
                Ok(0) => {
                    self.dead = true;
                    break;
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => break,
                Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(_) => {
                    self.dead = true;
                    break;
                }
                Ok(n) => {
                    for frame in self.reader.push(&buf[..n]) {
                        if let crate::session_host::Frame::Bytes(payload) = frame
                            && let Ok(msg) = serde_json::from_slice::<CollabMsg>(&payload)
                        {
                            msgs.push(msg);
                        }
                    }
                }
            }
        }
        msgs
    }
}

/// Resolve a wire-supplied file key against the workspace root. Keys arrive
/// from peers (snapshot requests, ops, carets) and the MCP collab agent
/// forwards caller input verbatim, so containment is enforced here, not by
/// the sender: every component must be a plain name — a traversing or
/// absolute key must never let a guest read or edit outside the workspace.
pub fn contained_path(root: &std::path::Path, file: &str) -> Option<std::path::PathBuf> {
    let rel = std::path::Path::new(file);
    let plain = !file.is_empty()
        && rel
            .components()
            .all(|c| matches!(c, std::path::Component::Normal(_)));
    if !plain {
        return None;
    }
    let joined = root.join(rel);
    // Plain components are not enough: a normal-looking key can name a
    // symlink inside the workspace whose target lies outside it, and the
    // later open follows the link. Resolve the deepest existing ancestor
    // (the file itself may not exist) and require it to stay under the
    // resolved root; a link resolving inside the workspace remains fine.
    let canon_root = root.canonicalize().ok()?;
    let mut probe = joined.as_path();
    loop {
        match probe.canonicalize() {
            Ok(real) => return real.starts_with(&canon_root).then_some(joined),
            // Nothing exists at this depth yet; check the parent instead.
            // The walk ends at `root` itself, which trivially resolves.
            Err(_) => probe = probe.parent()?,
        }
    }
}

/// The owner's fixed site id; joiners are allocated ids from 2 up.
const OWNER_SITE: u64 = 1;

/// How long a guest waits for the owner's snapshot before giving up. A
/// workspace with no live owner (nobody answers bootstrap) degrades to
/// plain local editing instead of staying read-only forever.
const BOOTSTRAP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);

/// How long the first unanswered SnapshotRequest waits before a re-send.
/// The relay has no replay: a request broadcast before the owner's
/// connection is registered is otherwise lost forever. Every further
/// unanswered resend doubles the wait, capped at [`SNAPSHOT_RESEND_CAP`]:
/// a guest cannot tell a lost request from a large reply still arriving,
/// and a fixed cadence made the owner re-serialize and blocking-write the
/// whole document every 500ms while a slow snapshot was already in flight.
const SNAPSHOT_RESEND: std::time::Duration = std::time::Duration::from_millis(500);

/// Ceiling on the resend backoff. Unbounded doubling scheduled the third
/// resend past [`BOOTSTRAP_TIMEOUT`] (0.5s, 1.5s, then 3.5s), so an owner
/// whose relay connection registered in the back half of the bootstrap
/// window was never re-asked and the guest silently degraded the file to
/// local-only. Capped at 1s the schedule is 0.5s, 1.5s, 2.5s: the same
/// late-owner coverage the pre-backoff fixed cadence had, at half the
/// duplicate-snapshot spam.
const SNAPSHOT_RESEND_CAP: std::time::Duration = std::time::Duration::from_secs(1);

/// How often the owner announces it is still there ([`CollabMsg::OwnerHere`]).
const OWNER_HEARTBEAT: std::time::Duration = std::time::Duration::from_secs(1);

/// How long a guest goes without the owner's heartbeat before treating the
/// owner as gone (a crash; a clean quit says [`CollabMsg::OwnerLeft`]).
/// Generous, so an owner busy for a few seconds isn't taken for gone.
const OWNER_GONE_AFTER: std::time::Duration = std::time::Duration::from_secs(15);

/// Per-file replication state on one participant.
enum DocState {
    /// Guest waiting for the owner's [`CollabMsg::SnapshotReply`]. Ops for
    /// the file arriving meanwhile are buffered and replayed after the
    /// snapshot lands (duplicates with ops already folded into the snapshot
    /// integrate as no-ops).
    Bootstrapping {
        nonce: u64,
        deadline: std::time::Instant,
        /// When to re-send the request if no reply has landed yet.
        resend_at: std::time::Instant,
        /// The wait after the next resend fires (doubles each time, capped:
        /// see [`SNAPSHOT_RESEND`] and [`SNAPSHOT_RESEND_CAP`]).
        resend_every: std::time::Duration,
        buffered: Vec<Envelope>,
    },
    // Boxed: CollabDoc is an order of magnitude larger than the bootstrap
    // variant, and per-file states live in a map for the session's life.
    Live(Box<CollabDoc>),
    /// The bootstrap gave up (nobody answered, or the snapshot was
    /// corrupt): the file is edited locally, by this guest alone. A latch,
    /// not an absence — forgetting the file instead made the app tick
    /// re-request it and re-arm the 3s input gate forever.
    LocalOnly,
}

/// What [`CollabSession::poll`] resolved this tick, for the app to apply to
/// its buffers. Everything is data: the session never touches an editor.
#[derive(Debug)]
pub enum CollabEvent {
    /// Remote edits resolved against the local replica; replay the spans
    /// sequentially onto the open buffer for `file`. `site` is the author's
    /// site id in that file, so the app can group one author's edits into a
    /// single undo step (#1207).
    RemoteEdit {
        file: String,
        site: u64,
        spans: Vec<ResolvedSpan>,
    },
    /// Bootstrap finished: swap the open buffer for `file` to `text` (the
    /// owner's canonical text with any buffered ops already folded in) and
    /// lift the input gate.
    Bootstrapped { file: String, text: String },
    /// No owner answered within the deadline: lift the input gate and treat
    /// the file as local-only.
    BootstrapTimedOut { file: String },
    /// A peer's caret moved in `file`.
    Caret {
        file: String,
        site: u64,
        row: usize,
        col: usize,
        name: String,
    },
    /// An AI pilot's stream into `file` started or ended.
    StreamState {
        file: String,
        site: u64,
        name: String,
        active: bool,
    },
    /// A participant asked the streaming pilot to stop and revert.
    StreamCancel,
    /// A peer's copy of a sticky note (#367).
    Note(crate::sticky_notes::Note),
    /// A joiner wants every note; the owner answers with [`Self::Note`]s.
    NotesRequested,
    /// Guest: the owner quit or went silent (#1147). Every file that was
    /// live is local-only now, so this guest saves it itself.
    OwnerLeft,
    /// Guest: an owner is back after [`Self::OwnerLeft`]. `files`, the ones
    /// that went local-only then, are forgotten, so the app re-requests them
    /// and they bootstrap from the new owner, merging the work done
    /// meanwhile.
    OwnerReturned { files: Vec<String> },
}

/// One participant's collab state machine: per-file replicated documents
/// over a [`CollabChannel`], with the bootstrap handshake and site-id
/// allocation (docs/MULTIPLAYER.md, Phase D). Editor-agnostic — the app
/// feeds it buffer text and applies the events it returns — so the whole
/// engine is testable headlessly through a relay socket pair.
pub struct CollabSession {
    pub role: CollabRole,
    channel: CollabChannel,
    docs: std::collections::HashMap<String, DocState>,
    /// Owner: next site id to hand a joiner (the owner itself is site 1).
    /// Only the owner allocates, so ids never collide (a collision would
    /// permanently break convergence).
    next_site: u64,
    /// Guest: pairs a SnapshotReply to this session's own request. Seeded
    /// from the process id so two guests' nonces never collide (replies are
    /// broadcast, and adopting another guest's reply would clone its site).
    next_nonce: u64,
    /// This participant's display name; rides every caret broadcast so
    /// peers can tag the ghost caret (site ids are per-file and carry no
    /// identity across files).
    name: String,
    /// Owner: when the next [`CollabMsg::OwnerHere`] is due.
    heartbeat_at: std::time::Instant,
    /// Guest: when the owner's heartbeat was last heard; None until the
    /// first one (an owner too old to send them is never taken for gone).
    owner_seen: Option<std::time::Instant>,
    /// Guest: the owner left and hasn't come back.
    owner_gone: bool,
    /// Guest: files that went local-only because the owner left, rejoined
    /// when an owner comes back.
    orphaned: std::collections::HashSet<String>,
}

impl CollabSession {
    pub fn new(channel: CollabChannel, name: String) -> Self {
        Self {
            role: channel.role,
            channel,
            docs: std::collections::HashMap::new(),
            // pid-seeded: a restarted owner allocating "2, 3, ..." again
            // would re-issue ids that guests surviving from the previous
            // owner already hold, permanently breaking convergence. Each
            // incarnation allocates from its own disjoint range instead.
            next_site: ((std::process::id() as u64) << 32) | (OWNER_SITE + 1),
            next_nonce: (std::process::id() as u64) << 32,
            name,
            heartbeat_at: std::time::Instant::now(),
            owner_seen: None,
            owner_gone: false,
            orphaned: std::collections::HashSet::new(),
        }
    }

    /// Guest: true while the owner is gone (quit, or silent for
    /// [`OWNER_GONE_AFTER`]) and no owner has come back.
    pub fn owner_gone(&self) -> bool {
        self.owner_gone
    }

    /// Owner: tell the guests this owner is quitting, so they stop
    /// deferring saves to it (#1147). A no-op for a guest.
    pub fn leave(&mut self) {
        if self.role == CollabRole::Owner && !self.channel.is_dead() {
            self.channel.send(&CollabMsg::OwnerLeft {});
        }
    }

    /// True when `file` is replicating (bootstrap finished).
    pub fn is_live(&self, file: &str) -> bool {
        matches!(self.docs.get(file), Some(DocState::Live(_)))
    }

    /// True once the relay hung up: every later send is lost, so the app
    /// drops the session and reconnects (files re-bootstrap on request).
    pub fn disconnected(&self) -> bool {
        self.channel.is_dead()
    }

    /// True when `file` gave up bootstrapping (no owner answered): the
    /// guest edits it locally and is its only author.
    pub fn is_local_only(&self, file: &str) -> bool {
        matches!(self.docs.get(file), Some(DocState::LocalOnly))
    }

    /// Explicitly retry sharing a file that gave up bootstrapping (the
    /// collab agent's `collab_open`). The app tick never rejoins — it calls
    /// [`Self::request_file`], which respects the local-only latch, or a
    /// guest whose owner is gone would re-enter the input gate every 3s.
    pub fn rejoin_file(&mut self, file: &str) {
        if matches!(self.docs.get(file), Some(DocState::LocalOnly)) {
            self.docs.remove(file);
        }
        self.request_file(file);
    }

    /// True while `file` waits for its snapshot (the app gates edit input).
    pub fn is_bootstrapping(&self, file: &str) -> bool {
        matches!(self.docs.get(file), Some(DocState::Bootstrapping { .. }))
    }

    /// The replicated text for `file`, when live. The collab agent serves
    /// reads through this (it has no editor buffers); the app reads its own.
    pub fn doc_text(&self, file: &str) -> Option<&str> {
        match self.docs.get(file) {
            Some(DocState::Live(doc)) => Some(doc.text()),
            _ => None,
        }
    }

    /// Every live file's current replicated text. Harvested as the offline
    /// merge base when the relay link is lost: it is the last text every
    /// participant agreed on, so a reconnect can replay only this side's
    /// delta instead of its whole (possibly stale) buffer.
    pub fn live_texts(&self) -> Vec<(String, String)> {
        self.docs
            .iter()
            .filter_map(|(f, d)| match d {
                DocState::Live(doc) => Some((f.clone(), doc.text().to_string())),
                _ => None,
            })
            .collect()
    }

    /// The live doc's text generation for `file` (see
    /// [`CollabDoc::text_gen`]): the editor wiring's staleness check.
    pub fn doc_gen(&self, file: &str) -> Option<u64> {
        match self.docs.get(file) {
            Some(DocState::Live(doc)) => Some(doc.text_gen()),
            _ => None,
        }
    }

    /// Every file this session tracks, with whether it is live yet (false =
    /// still bootstrapping). For status surfaces like `collab_status`.
    pub fn tracked_files(&self) -> Vec<(String, bool)> {
        self.docs
            .iter()
            .map(|(f, s)| (f.clone(), matches!(s, DocState::Live(_))))
            .collect()
    }

    /// Guest: start sharing `file` — ask the owner for its current state and
    /// buffer inbound ops until the snapshot lands. No-op if already tracked.
    pub fn request_file(&mut self, file: &str) {
        if self.role != CollabRole::Guest || self.docs.contains_key(file) {
            return;
        }
        let nonce = self.next_nonce;
        self.next_nonce += 1;
        self.channel.send(&CollabMsg::SnapshotRequest {
            file: file.to_string(),
            nonce,
        });
        let now = std::time::Instant::now();
        self.docs.insert(
            file.to_string(),
            DocState::Bootstrapping {
                nonce,
                deadline: now + BOOTSTRAP_TIMEOUT,
                resend_at: now + SNAPSHOT_RESEND,
                resend_every: SNAPSHOT_RESEND,
                buffered: Vec::new(),
            },
        );
    }

    /// The local buffer for `file` now reads `current`: diff it against the
    /// replica (invariant 1a, extract-before-apply) and broadcast the
    /// resulting ops. Returns whether anything was sent. Quiescent when the
    /// text is unchanged — an op emitted here for a remote edit the app just
    /// applied would echo between peers forever.
    pub fn local_change(&mut self, file: &str, current: &str) -> bool {
        let Some(DocState::Live(doc)) = self.docs.get_mut(file) else {
            return false;
        };
        if doc.text() == current {
            return false;
        }
        let site = doc.site_id();
        let ops = text_delta_ops(doc, current);
        let sent = !ops.is_empty();
        for op in ops {
            self.channel.send(&CollabMsg::Op(Envelope {
                file: file.to_string(),
                site,
                op,
            }));
        }
        sent
    }

    /// This participant's site id in every live file: its wire identity.
    /// The owner is always site 1; every guest file-join is allocated a
    /// fresh id from the owner's one counter, so a guest's ids are unique
    /// across the whole relay — unlike display names, which are neither
    /// unique nor length-stable.
    pub fn my_site_ids(&self) -> Vec<u64> {
        self.docs
            .values()
            .filter_map(|d| match d {
                DocState::Live(doc) => Some(doc.site_id()),
                _ => None,
            })
            .collect()
    }

    /// Broadcast this participant's caret position in a live file.
    pub fn send_caret(&mut self, file: &str, row: usize, col: usize) {
        let Some(DocState::Live(doc)) = self.docs.get(file) else {
            return;
        };
        let site = doc.site_id();
        self.channel.send(&CollabMsg::Caret {
            file: file.to_string(),
            site,
            row,
            col,
            name: self.name.clone(),
        });
    }

    /// Broadcast that this participant's AI stream into `file` started or
    /// ended. Not doc-gated (unlike carets): the pilot announces before the
    /// file may have bootstrapped; `site` is best-effort identity, `name` is
    /// the real one.
    pub fn send_stream_state(&mut self, file: &str, active: bool) {
        let site = match self.docs.get(file) {
            Some(DocState::Live(doc)) => doc.site_id(),
            _ => 0,
        };
        self.channel.send(&CollabMsg::StreamState {
            site,
            name: self.name.clone(),
            file: file.to_string(),
            active,
        });
    }

    /// Broadcast a sticky note's current copy (#367).
    pub fn send_note(&mut self, note: &crate::sticky_notes::Note) {
        self.channel.send(&CollabMsg::Note { note: note.clone() });
    }

    /// Ask the owner for every sticky note (a guest, on joining).
    pub fn send_notes_request(&mut self) {
        self.channel.send(&CollabMsg::NotesRequest {});
    }

    /// Ask whoever is streaming on this relay to stop and revert.
    pub fn send_stream_cancel(&mut self) {
        self.channel.send(&CollabMsg::StreamCancel {});
    }

    /// Drain the channel and resolve everything into [`CollabEvent`]s
    /// (invariant 1b: the app extracts local edits before calling this).
    /// `owner_text` is the owner's buffer lookup for a file a guest wants
    /// bootstrapped: return its current text (opening it if needed) or None
    /// to decline (unreadable, binary). Guests ignore the callback.
    pub fn poll(&mut self, mut owner_text: impl FnMut(&str) -> Option<String>) -> Vec<CollabEvent> {
        let mut events = Vec::new();
        for msg in self.channel.drain() {
            match msg {
                CollabMsg::Op(env) => match self.docs.get_mut(&env.file) {
                    Some(DocState::Live(doc)) => {
                        let spans = doc.apply_remote(&env.op);
                        if !spans.is_empty() {
                            events.push(CollabEvent::RemoteEdit {
                                file: env.file,
                                site: env.site,
                                spans,
                            });
                        }
                    }
                    Some(DocState::Bootstrapping { buffered, .. }) => buffered.push(env),
                    // Not open on this peer (or degraded to local-only):
                    // ignored until opened or rejoined, then the bootstrap
                    // snapshot carries this edit anyway.
                    None | Some(DocState::LocalOnly) => {}
                },
                CollabMsg::SnapshotRequest { file, nonce } => {
                    // Only the owner answers, so a request never draws
                    // competing replies (and site allocation stays single-
                    // writer).
                    if self.role != CollabRole::Owner {
                        continue;
                    }
                    if !self.docs.contains_key(&file) {
                        let Some(text) = owner_text(&file) else {
                            continue;
                        };
                        self.docs.insert(
                            file.clone(),
                            DocState::Live(Box::new(CollabDoc::new(OWNER_SITE, &text))),
                        );
                    }
                    let Some(DocState::Live(doc)) = self.docs.get(&file) else {
                        continue;
                    };
                    let assigned_site = self.next_site;
                    self.next_site += 1;
                    self.channel.send(&CollabMsg::SnapshotReply {
                        file,
                        nonce,
                        assigned_site,
                        text: doc.text().to_string(),
                        replica: doc.encode(),
                    });
                }
                CollabMsg::SnapshotReply {
                    file,
                    nonce,
                    assigned_site,
                    text,
                    replica,
                } => {
                    let Some(DocState::Bootstrapping {
                        nonce: want,
                        buffered,
                        ..
                    }) = self.docs.get_mut(&file)
                    else {
                        continue;
                    };
                    // Replies are broadcast; adopt only the answer to this
                    // session's own request (another guest's reply carries
                    // another guest's site id).
                    if *want != nonce {
                        continue;
                    }
                    let buffered = std::mem::take(buffered);
                    let Ok(mut doc) = CollabDoc::from_snapshot(assigned_site, &text, &replica)
                    else {
                        // Corrupt snapshot: give up as if nobody answered.
                        self.docs.insert(file.clone(), DocState::LocalOnly);
                        events.push(CollabEvent::BootstrapTimedOut { file });
                        continue;
                    };
                    // Ops that raced the reply fold into the bootstrap text;
                    // ones the snapshot already contained integrate as
                    // duplicates (no-ops).
                    for env in &buffered {
                        let _ = doc.apply_remote(&env.op);
                    }
                    let final_text = doc.text().to_string();
                    self.docs
                        .insert(file.clone(), DocState::Live(Box::new(doc)));
                    events.push(CollabEvent::Bootstrapped {
                        file,
                        text: final_text,
                    });
                }
                CollabMsg::Caret {
                    file,
                    site,
                    row,
                    col,
                    name,
                } => events.push(CollabEvent::Caret {
                    file,
                    site,
                    row,
                    col,
                    name,
                }),
                CollabMsg::StreamState {
                    site,
                    name,
                    file,
                    active,
                } => events.push(CollabEvent::StreamState {
                    file,
                    site,
                    name,
                    active,
                }),
                CollabMsg::StreamCancel {} => events.push(CollabEvent::StreamCancel),
                CollabMsg::Note { note } => events.push(CollabEvent::Note(note)),
                CollabMsg::NotesRequest {} => {
                    if self.role == CollabRole::Owner {
                        events.push(CollabEvent::NotesRequested);
                    }
                }
                CollabMsg::OwnerHere {} if self.role == CollabRole::Guest => {
                    self.owner_seen = Some(std::time::Instant::now());
                    if std::mem::take(&mut self.owner_gone) {
                        let files: Vec<String> = self
                            .orphaned
                            .drain()
                            .filter(|f| matches!(self.docs.get(f), Some(DocState::LocalOnly)))
                            .collect();
                        for file in &files {
                            self.docs.remove(file);
                        }
                        events.push(CollabEvent::OwnerReturned { files });
                    }
                }
                CollabMsg::OwnerLeft {} if self.role == CollabRole::Guest => {
                    self.orphan_live_files(&mut events);
                }
                CollabMsg::OwnerHere {} | CollabMsg::OwnerLeft {} => {}
            }
        }
        let now = std::time::Instant::now();
        if self.role == CollabRole::Owner && now >= self.heartbeat_at {
            self.heartbeat_at = now + OWNER_HEARTBEAT;
            self.channel.send(&CollabMsg::OwnerHere {});
        }
        if self
            .owner_seen
            .is_some_and(|seen| now.duration_since(seen) > OWNER_GONE_AFTER)
        {
            self.orphan_live_files(&mut events);
        }
        // Give up on bootstraps nobody answered (no owner running).
        let timed_out: Vec<String> = self
            .docs
            .iter()
            .filter_map(|(file, state)| match state {
                DocState::Bootstrapping { deadline, .. } if now > *deadline => Some(file.clone()),
                _ => None,
            })
            .collect();
        for file in timed_out {
            // A latch, not a removal: the app tick re-requests any open file
            // that is neither live nor bootstrapping, so a forgotten file
            // re-entered the input gate 16ms after every give-up.
            self.docs.insert(file.clone(), DocState::LocalOnly);
            events.push(CollabEvent::BootstrapTimedOut { file });
        }
        // Re-send unanswered requests: the relay has no replay, so the
        // original broadcast may have missed an owner whose connection was
        // not yet registered (or who connected moments later).
        let mut resend = Vec::new();
        for (file, state) in self.docs.iter_mut() {
            if let DocState::Bootstrapping {
                nonce,
                resend_at,
                resend_every,
                ..
            } = state
                && now >= *resend_at
            {
                *resend_every = (*resend_every * 2).min(SNAPSHOT_RESEND_CAP);
                *resend_at = now + *resend_every;
                resend.push((file.clone(), *nonce));
            }
        }
        for (file, nonce) in resend {
            self.channel
                .send(&CollabMsg::SnapshotRequest { file, nonce });
        }
        events
    }

    /// Guest: the owner is gone (#1147). Every live file goes local-only,
    /// so the app's save gate stands down and this guest writes it.
    fn orphan_live_files(&mut self, events: &mut Vec<CollabEvent>) {
        self.owner_seen = None;
        if self.owner_gone {
            return;
        }
        self.owner_gone = true;
        for (file, _) in self.live_texts() {
            self.docs.insert(file.clone(), DocState::LocalOnly);
            self.orphaned.insert(file);
        }
        events.push(CollabEvent::OwnerLeft);
    }
}

impl Drop for CollabSession {
    /// An owner says goodbye however it goes away (#1147), so its guests
    /// stop deferring saves to it at once.
    fn drop(&mut self) {
        self.leave();
    }
}

/// How long the relay lets one forwarding write block before treating the
/// peer as wedged and dropping it. Shorter than the clients' own
/// frame-write deadline, so the relay recovers (and traffic resumes for
/// healthy peers) before any client gives its connection up for dead.
const RELAY_WRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

// The ordering above is a recovery guarantee, not a coincidence: hold it
// against future edits to either constant.
const _: () = assert!(
    RELAY_WRITE_TIMEOUT.as_millis() < crate::session_host::WRITE_FRAME_DEADLINE.as_millis()
);

type Peer = std::sync::Arc<std::sync::Mutex<std::os::unix::net::UnixStream>>;

/// One connection: reassemble whole frames from this peer and forward each,
/// atomically, to every other peer. Reframing (not raw byte forwarding) is
/// what keeps two senders' frames from interleaving mid-message at a receiver.
fn relay_client(
    mut rx: std::os::unix::net::UnixStream,
    me: &Peer,
    clients: &std::sync::Arc<std::sync::Mutex<Vec<Peer>>>,
) {
    use crate::session_host::{Frame, FrameReader, encode_bytes_frame};
    let mut reader = FrameReader::new();
    let mut buf = [0u8; 16384];
    loop {
        let n = match rx.read(&mut buf) {
            Ok(0) | Err(_) => break,
            Ok(n) => n,
        };
        for frame in reader.push(&buf[..n]) {
            let Frame::Bytes(payload) = frame else {
                continue;
            };
            let out = encode_bytes_frame(&payload);
            let mut peers = clients.lock().unwrap();
            peers.retain(|c| {
                if std::sync::Arc::ptr_eq(c, me) {
                    return true;
                }
                let mut s = c.lock().unwrap();
                if s.write_all(&out).is_ok() {
                    return true;
                }
                // Timed out (wedged peer) or gone: shut the socket down so
                // the peer's reader thread sees EOF and cleans up — merely
                // forgetting the write clone left the connection half-alive.
                let _ = s.shutdown(std::net::Shutdown::Both);
                false
            });
        }
    }
    clients
        .lock()
        .unwrap()
        .retain(|c| !std::sync::Arc::ptr_eq(c, me));
}

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

    /// Tests must never inherit a live collab seat from the shell that ran
    /// the suite. Croft exports `CROFT_COLLAB_SOCKET`/`CROFT_COLLAB_ROLE`
    /// into its child shells, so a `cargo test` launched from a croft
    /// session (the dogfooding path) used to hand every test-built `App` a
    /// `Some((_, Owner))` collab config — skipping the single-host lock
    /// gate and deterministically failing five pair/collab tests (#55).
    /// Under `cfg(test)` the env read must be inert no matter what the
    /// environment holds. (Asserted through `env_config` itself rather
    /// than by mutating the environment: `set_var` races sibling test
    /// threads, #37.)
    #[test]
    fn env_config_is_hermetic_under_test() {
        assert_eq!(
            CollabChannel::env_config(),
            None,
            "a test-built App must not inherit the launching shell's collab seat"
        );
    }

    /// The launch-tail contract `env_config` enforces, pinned through the
    /// pure parser so the hermetic `cfg(test)` default above can't hide a
    /// parsing regression: both roles parse, an unknown role is refused
    /// (forward-compat: a newer launch tail must not seat an old binary in
    /// a role it doesn't understand), and a missing socket or role means
    /// "not a collab participant".
    #[test]
    fn env_config_parses_the_launch_tail_exports() {
        let sock = std::ffi::OsString::from("/tmp/collab.sock");
        assert_eq!(
            CollabChannel::env_config_from(Some(sock.clone()), Some("owner".into())),
            Some((
                std::path::PathBuf::from("/tmp/collab.sock"),
                CollabRole::Owner
            )),
        );
        assert_eq!(
            CollabChannel::env_config_from(Some(sock.clone()), Some("guest".into())),
            Some((
                std::path::PathBuf::from("/tmp/collab.sock"),
                CollabRole::Guest
            )),
        );
        assert_eq!(
            CollabChannel::env_config_from(Some(sock.clone()), Some("navigator".into())),
            None,
            "an unrecognized role must refuse the seat, not guess one"
        );
        assert_eq!(CollabChannel::env_config_from(Some(sock), None), None);
        assert_eq!(
            CollabChannel::env_config_from(None, Some("owner".into())),
            None
        );
    }

    /// The defining CRDT property: two replicas that make *concurrent* edits
    /// (each unaware of the other's) and then exchange ops must arrive at the
    /// identical text. A naive "apply the remote edit at its original offset"
    /// scheme diverges here (each side's earlier local edit shifted the other's
    /// intended position); cola resolving positions is what makes it converge.
    #[test]
    fn concurrent_edits_converge_on_both_replicas() {
        let mut a = CollabDoc::new(1, "abc");
        let mut b = a.fork(2);

        // Concurrent, position-conflicting inserts at opposite ends.
        let op_a = a.local_insert(0, "X"); // a: "Xabc"
        let op_b = b.local_insert(3, "Y"); // b: "abcY"

        a.apply_remote(&op_b);
        b.apply_remote(&op_a);

        assert_eq!(a.text(), b.text(), "replicas must converge");
        assert_eq!(a.text(), "XabcY");
    }

    /// Concurrent insert and delete over overlapping regions still converge.
    #[test]
    fn concurrent_insert_and_delete_converge() {
        let mut a = CollabDoc::new(1, "hello world");
        let mut b = a.fork(2);

        let op_a = a.local_insert(5, " dear"); // a: "hello dear world"
        let op_b = b.local_delete(6, 5); // b deletes "world" -> "hello "

        a.apply_remote(&op_b);
        b.apply_remote(&op_a);

        assert_eq!(a.text(), b.text(), "replicas must converge");
    }

    /// Causally dependent ops delivered out of order must still converge:
    /// cola backlogs an insertion whose context has not arrived, and the
    /// backlog must be drained (with the stashed text) once the context lands.
    /// Dropping the op instead permanently diverges the replicas.
    #[test]
    fn out_of_order_dependent_inserts_converge_via_the_backlog() {
        let mut a = CollabDoc::new(1, "ab");
        let mut b = a.fork(2);

        let op_c = a.local_insert(2, "c");
        let op_d = a.local_insert(3, "d");
        let op_e = a.local_insert(4, "e");
        assert_eq!(a.text(), "abcde");

        // The network reorders: e and d arrive before their prerequisite c.
        b.apply_remote(&op_e);
        b.apply_remote(&op_d);
        b.apply_remote(&op_c);

        assert_eq!(b.text(), a.text(), "backlogged inserts must drain");
    }

    /// A deletion arriving before the insertion it deletes from is backlogged
    /// and applied once the insertion lands (cola's own canonical example).
    #[test]
    fn deletion_arriving_before_its_insertion_converges_via_the_backlog() {
        let mut a = CollabDoc::new(1, "Hello");
        let mut b = a.fork(2);
        let mut c = a.fork(3);

        let ins = a.local_insert(5, " world!");
        b.apply_remote(&ins);
        let del = b.local_delete(5, 6); // b: "Hello!"

        // c receives the deletion first, without its context.
        c.apply_remote(&del);
        c.apply_remote(&ins);

        assert_eq!(c.text(), b.text(), "backlogged deletion must drain");
        assert_eq!(c.text(), "Hello!");
    }

    /// Replay every span a batch returns onto a shadow string, in order.
    /// Keeping the shadow equal to the doc pins the sequential replay
    /// contract the editor wiring depends on.
    fn replay(shadow: &mut String, spans: &[ResolvedSpan]) {
        for s in spans {
            shadow.replace_range(s.at..s.at + s.deleted, &s.inserted);
        }
    }

    /// `apply_remote` reports exactly what changed, as sequentially
    /// replayable spans — including the backlogged ops a drain applies.
    #[test]
    fn apply_remote_returns_sequentially_replayable_spans() {
        let mut a = CollabDoc::new(1, "ab");
        let mut b = a.fork(2);
        let mut shadow = String::from("ab");

        let op_c = a.local_insert(2, "c");
        let op_d = a.local_insert(3, "d");
        let del = a.local_delete(0, 1); // a: "bcd"

        // Out of order: d backlogs, then c's arrival drains it in one batch.
        replay(&mut shadow, &b.apply_remote(&op_d));
        replay(&mut shadow, &b.apply_remote(&op_c));
        replay(&mut shadow, &b.apply_remote(&del));

        assert_eq!(b.text(), a.text());
        assert_eq!(shadow, b.text(), "spans must replay the doc's changes");
    }

    /// The bootstrap round-trip: a joiner rebuilt from `encode` + text
    /// integrates ops both ways with the peer it joined.
    #[test]
    fn snapshot_bootstraps_a_new_peer_that_then_converges() {
        let mut a = CollabDoc::new(1, "fn main() {}\n");
        let _ = a.local_insert(0, "// header\n");

        let mut b = CollabDoc::from_snapshot(2, a.text(), &a.encode()).expect("decode snapshot");
        assert_eq!(b.text(), a.text());

        // Concurrent edits after the join still converge.
        let op_a = a.local_insert(0, "A");
        let at = b.text().len();
        let op_b = b.local_insert(at, "B");
        a.apply_remote(&op_b);
        b.apply_remote(&op_a);
        assert_eq!(a.text(), b.text());
    }

    /// Corrupt snapshot bytes fail loudly instead of building a replica that
    /// would silently diverge.
    #[test]
    fn snapshot_decode_rejects_corrupt_bytes() {
        let a = CollabDoc::new(1, "abc");
        let mut bytes = a.encode();
        if let Some(last) = bytes.last_mut() {
            *last ^= 0xff;
        }
        assert!(CollabDoc::from_snapshot(2, a.text(), &bytes).is_err());
    }

    /// The bootstrap handshake messages round-trip through the wire encoding.
    #[test]
    fn collab_msg_round_trips_through_serde() {
        let mut a = CollabDoc::new(1, "abc");
        let op = a.local_insert(0, "X");
        for msg in [
            CollabMsg::Op(Envelope {
                file: "src/f.rs".into(),
                site: 1,
                op,
            }),
            CollabMsg::SnapshotRequest {
                file: "src/f.rs".into(),
                nonce: 7,
            },
            CollabMsg::SnapshotReply {
                file: "src/f.rs".into(),
                nonce: 7,
                assigned_site: 2,
                text: a.text().to_string(),
                replica: a.encode(),
            },
        ] {
            let bytes = serde_json::to_vec(&msg).expect("serialize");
            let decoded: CollabMsg = serde_json::from_slice(&bytes).expect("deserialize");
            assert_eq!(
                std::mem::discriminant(&decoded),
                std::mem::discriminant(&msg)
            );
        }
    }

    /// A 0.1.632 peer's Caret (no `name` field on the wire) still parses —
    /// the name defaults to empty — and a named caret round-trips.
    #[test]
    fn caret_without_name_parses_and_name_round_trips() {
        let old = br#"{"Caret":{"file":"f","site":2,"row":0,"col":0}}"#;
        let decoded: CollabMsg = serde_json::from_slice(old).expect("old caret parses");
        match decoded {
            CollabMsg::Caret { name, .. } => assert_eq!(name, ""),
            other => panic!("expected caret, got {other:?}"),
        }
        let named = CollabMsg::Caret {
            file: "f".into(),
            site: 2,
            row: 1,
            col: 3,
            name: "claude".into(),
        };
        let bytes = serde_json::to_vec(&named).expect("serialize");
        match serde_json::from_slice::<CollabMsg>(&bytes).expect("deserialize") {
            CollabMsg::Caret { name, row, col, .. } => {
                assert_eq!((name.as_str(), row, col), ("claude", 1, 3));
            }
            other => panic!("expected caret, got {other:?}"),
        }
    }

    /// The AI-stream wire messages round-trip: StreamState carries the
    /// pilot's identity and target file, StreamCancel is a bare request any
    /// participant may broadcast.
    #[test]
    fn stream_state_and_cancel_round_trip_through_serde() {
        let state = CollabMsg::StreamState {
            site: 2,
            name: "claude".into(),
            file: "src/f.rs".into(),
            active: true,
        };
        let bytes = serde_json::to_vec(&state).expect("serialize");
        match serde_json::from_slice::<CollabMsg>(&bytes).expect("deserialize") {
            CollabMsg::StreamState {
                site,
                name,
                file,
                active,
            } => {
                assert_eq!(
                    (site, name.as_str(), file.as_str(), active),
                    (2, "claude", "src/f.rs", true)
                );
            }
            other => panic!("expected stream state, got {other:?}"),
        }
        let cancel = CollabMsg::StreamCancel {};
        let bytes = serde_json::to_vec(&cancel).expect("serialize");
        assert!(matches!(
            serde_json::from_slice::<CollabMsg>(&bytes).expect("deserialize"),
            CollabMsg::StreamCancel {}
        ));
    }

    /// A frame carrying a CollabMsg variant this build does not know (a newer
    /// peer on the same relay) is skipped by drain, never an error — this is
    /// the interop guarantee the new stream messages rely on against 0.1.633
    /// peers.
    #[test]
    fn drain_skips_unknown_wire_variants() {
        use std::io::Write;
        let (mut tx, rx) = std::os::unix::net::UnixStream::pair().unwrap();
        rx.set_nonblocking(true).unwrap();
        let mut channel = CollabChannel {
            stream: rx,
            reader: crate::session_host::FrameReader::new(),
            role: CollabRole::Guest,
            dead: false,
        };
        let bogus = crate::session_host::encode_bytes_frame(br#"{"FutureVariant":{"whatever":1}}"#);
        tx.write_all(&bogus).unwrap();
        let known = CollabMsg::StreamCancel {};
        tx.write_all(&known.encode()).unwrap();
        tx.flush().unwrap();
        // Both frames are already in the socketpair buffer; drain sees them.
        let msgs = channel.drain();
        assert_eq!(msgs.len(), 1, "bogus variant skipped, known one kept");
        assert!(matches!(msgs[0], CollabMsg::StreamCancel {}));
    }

    /// An op serializes and deserializes across the wire (the control channel
    /// will carry these), and integrating the decoded op matches integrating
    /// the original.
    #[test]
    fn ops_round_trip_through_serde() {
        let mut a = CollabDoc::new(1, "abc");
        let mut b = a.fork(2);

        let op = a.local_insert(1, "ZZ"); // a: "aZZbc"
        let bytes = serde_json::to_vec(&op).expect("serialize op");
        let decoded: Op = serde_json::from_slice(&bytes).expect("deserialize op");

        b.apply_remote(&decoded);
        assert_eq!(b.text(), a.text());
        assert_eq!(b.text(), "aZZbc");
    }

    /// Disjoint offline-era edits from both sides of a dead link must both
    /// survive the reconnect merge.
    #[test]
    fn merge_offline_texts_keeps_disjoint_edits_from_both_sides() {
        assert_eq!(
            merge_offline_texts(
                "alpha\nbeta\ngamma",
                "OFFLINE alpha\nbeta\ngamma",
                "alpha\nbeta\nOWNER gamma",
            ),
            "OFFLINE alpha\nbeta\nOWNER gamma"
        );
        // Insertions at different points both land.
        assert_eq!(
            merge_offline_texts("a\nb\nc", "x\na\nb\nc", "a\nb\nc\ny"),
            "x\na\nb\nc\ny"
        );
        // Their deletion coexists with our disjoint edit.
        assert_eq!(
            merge_offline_texts("a\nb\nc", "a EDIT\nb\nc", "a\nc"),
            "a EDIT\nc"
        );
    }

    /// A genuine conflict (both sides touched the same line) keeps ours: the
    /// offline buffer is the only home of that work, while their side still
    /// lives in the replicas' history.
    #[test]
    fn merge_offline_texts_prefers_ours_on_a_conflicting_line() {
        assert_eq!(
            merge_offline_texts("alpha\nbeta", "OURS\nbeta", "THEIRS\nbeta"),
            "OURS\nbeta"
        );
        // Same-point insertions collide: ours wins, theirs is dropped.
        assert_eq!(merge_offline_texts("a\nb", "a\nX\nb", "a\nY\nb"), "a\nX\nb");
    }

    /// Touching is not conflicting: an insertion that merely shares its
    /// start offset with the other side's replacement coexists with it —
    /// dropping either side would silently lose retainable work.
    #[test]
    fn merge_offline_texts_keeps_touching_insertion_and_replacement() {
        // Our insertion sits right before the line they replaced.
        assert_eq!(merge_offline_texts("a\nb", "X\na\nb", "A\nb"), "X\nA\nb");
        // The mirror image: our replacement, their adjacent insertion.
        // (Order at the shared boundary is ours-first; nothing is lost.)
        assert_eq!(merge_offline_texts("a\nb", "A\nb", "X\na\nb"), "A\nX\nb");
    }

    /// One quiet side means no merge at all: the other side's text is the
    /// result verbatim.
    #[test]
    fn merge_offline_texts_with_one_quiet_side_is_the_other_text() {
        assert_eq!(merge_offline_texts("base", "base", "theirs"), "theirs");
        assert_eq!(merge_offline_texts("base", "ours", "base"), "ours");
    }

    /// The slice-4 extraction path: an arbitrary text-state transition on one
    /// replica, expressed only as (old text, new text), produces ops that make
    /// a fork converge to the new text.
    #[test]
    fn text_delta_ops_converge_a_fork_to_the_new_text() {
        let mut a = CollabDoc::new(1, "hello world");
        let mut b = a.fork(2);

        let ops = text_delta_ops(&mut a, "hello brave new world");
        assert!(!ops.is_empty(), "a real edit must emit ops");
        assert_eq!(a.text(), "hello brave new world");
        for op in &ops {
            b.apply_remote(op);
        }
        assert_eq!(b.text(), a.text());
    }

    /// Multiple disjoint change runs (a delete at the front, a replace in the
    /// middle, an insert at the end) all extract in one pass.
    #[test]
    fn text_delta_ops_handle_multiple_change_runs() {
        let mut a = CollabDoc::new(1, "aaa bbb ccc ddd");
        let mut b = a.fork(2);

        let ops = text_delta_ops(&mut a, "bbb XYZ ddd eee");
        assert_eq!(a.text(), "bbb XYZ ddd eee");
        for op in &ops {
            b.apply_remote(op);
        }
        assert_eq!(b.text(), a.text());
    }

    /// Multibyte chars keep the byte cursor honest: the diff walks chars but
    /// ops address bytes.
    #[test]
    fn text_delta_ops_handle_multibyte_text() {
        let mut a = CollabDoc::new(1, "héllo wörld");
        let mut b = a.fork(2);

        let ops = text_delta_ops(&mut a, "héllo, schöne Wörld");
        assert_eq!(a.text(), "héllo, schöne Wörld");
        for op in &ops {
            b.apply_remote(op);
        }
        assert_eq!(b.text(), a.text());
    }

    /// No change, no ops: the tick-time extraction must be quiescent when the
    /// buffer has not moved (an op here would echo forever between peers).
    #[test]
    fn text_delta_ops_emit_nothing_when_unchanged() {
        let mut a = CollabDoc::new(1, "same text");
        let ops = text_delta_ops(&mut a, "same text");
        assert!(ops.is_empty());
        assert_eq!(a.text(), "same text");
    }

    /// A wholesale buffer swap (the owner's disk-reload path in slice 4) is
    /// just one big transition and still converges a fork.
    #[test]
    fn text_delta_ops_handle_wholesale_replacement() {
        let mut a = CollabDoc::new(1, "the quick brown fox\njumps over\n");
        let mut b = a.fork(2);

        let ops = text_delta_ops(&mut a, "an entirely different\nbuffer\nnow\n");
        assert_eq!(a.text(), "an entirely different\nbuffer\nnow\n");
        for op in &ops {
            b.apply_remote(op);
        }
        assert_eq!(b.text(), a.text());
    }

    /// Extraction composes with concurrency: both replicas diff-extract
    /// concurrent local edits, exchange, and converge.
    #[test]
    fn concurrent_text_delta_ops_converge() {
        let mut a = CollabDoc::new(1, "shared base line");
        let mut b = a.fork(2);

        let ops_a = text_delta_ops(&mut a, "shared MODIFIED base line");
        let ops_b = text_delta_ops(&mut b, "shared base line plus tail");

        for op in &ops_b {
            a.apply_remote(op);
        }
        for op in &ops_a {
            b.apply_remote(op);
        }
        assert_eq!(a.text(), b.text(), "replicas must converge");
    }

    #[test]
    fn char_column_maps_to_byte_offset_across_lines_and_multibyte() {
        // "héllo" is 5 chars / 6 bytes (é is 2 bytes); "wörld" likewise.
        let lines = vec![String::from("héllo"), String::from("wörld")];

        // Within the first line: char col 3 is the second 'l', at byte 4.
        assert_eq!(byte_offset(&lines, 0, 3), 4);
        // End of the first line: byte 6 (before the '\n').
        assert_eq!(byte_offset(&lines, 0, 5), 6);
        // Second line, char col 2 ('r'): 6 bytes + '\n' + "wö" (3 bytes) = 10.
        assert_eq!(byte_offset(&lines, 1, 2), 10);

        // Round-trips both directions for every valid position.
        for (row, line) in lines.iter().enumerate() {
            for col in 0..=line.chars().count() {
                let off = byte_offset(&lines, row, col);
                assert_eq!(position(&lines, off), (row, col), "row {row} col {col}");
            }
        }
    }

    /// The join text `byte_offset` addresses is exactly what `CollabDoc` holds,
    /// so an editor edit expressed in (row, col) integrates at the right place.
    #[test]
    fn editor_position_edit_integrates_into_collabdoc() {
        let lines = vec![String::from("foo"), String::from("bar")];
        let joined = lines.join("\n");
        let mut a = CollabDoc::new(1, &joined);
        let mut b = a.fork(2);

        // Insert "X" at editor position (row 1, col 0) = start of "bar".
        let at = byte_offset(&lines, 1, 0);
        let op = a.local_insert(at, "X");
        b.apply_remote(&op);

        assert_eq!(a.text(), "foo\nXbar");
        assert_eq!(b.text(), a.text());
    }

    #[test]
    fn detached_relay_argv_serves_the_socket() {
        assert_eq!(
            detached_relay_argv(std::path::Path::new("/x/abc.collab.sock")),
            vec!["collab-relay", "--socket", "/x/abc.collab.sock"]
        );
    }

    /// `ensure_relay` and `relay_serve` are attach-or-create: a live relay on
    /// the socket short-circuits both instead of being stolen from (a second
    /// bind would strand the first relay's clients mid-session).
    ///
    /// The invariant is asserted DIRECTLY — a fresh connect after both calls
    /// must still land on THIS listener's accept queue (#30). The old proxy
    /// assert (`!is_alive` after dropping the listener) claimed a global
    /// property instead: that no process anywhere holds a listening fd for
    /// the path. On macOS `bind` cannot set CLOEXEC atomically, so a
    /// concurrent test thread's fork/spawn can inherit the listener fd in
    /// that window and keep the socket connectable after the drop — a
    /// hygiene accident of the parallel suite, not a steal, and the flake
    /// this test was known for. Routing-through-accept is immune: an
    /// inherited duplicate shares OUR queue, while a thief that rebound the
    /// path would swallow the fresh connect and accept() would come up dry.
    #[test]
    fn a_live_relay_is_not_stolen_from() {
        use std::os::unix::net::UnixListener;
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("c.collab.sock");
        let listener = UnixListener::bind(&socket).unwrap();
        listener.set_nonblocking(true).unwrap();

        ensure_relay(&socket).expect("alive socket short-circuits");
        relay_serve(&socket).expect("alive socket short-circuits");

        // Drain the probe connections the two calls queued on us, then
        // prove a fresh connect still routes here: the path was not rebound.
        while listener.accept().is_ok() {}
        let _probe = std::os::unix::net::UnixStream::connect(&socket)
            .expect("the listener still owns the path");
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        loop {
            match listener.accept() {
                Ok(_) => break,
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    assert!(
                        std::time::Instant::now() < deadline,
                        "the fresh connect never reached this listener: the \
                         socket path was rebound out from under it"
                    );
                    std::thread::sleep(std::time::Duration::from_millis(5));
                }
                Err(e) => panic!("accept failed: {e}"),
            }
        }
    }

    /// Start a relay on a temp socket and connect a session to it in `role`.
    fn session_pair() -> (tempfile::TempDir, CollabSession, CollabSession) {
        use std::time::{Duration, Instant};
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("s.collab.sock");
        {
            let s = socket.clone();
            std::thread::spawn(move || {
                let _ = relay_serve(&s);
            });
        }
        let deadline = Instant::now() + Duration::from_secs(5);
        let owner = loop {
            if let Some(ch) = CollabChannel::connect(&socket, CollabRole::Owner) {
                break CollabSession::new(ch, "owner".into());
            }
            assert!(Instant::now() < deadline, "relay never came up");
            std::thread::sleep(Duration::from_millis(10));
        };
        let guest = CollabSession::new(
            CollabChannel::connect(&socket, CollabRole::Guest).expect("guest connects"),
            "guest".into(),
        );
        (dir, owner, guest)
    }

    /// Pump both sessions until `done` says so or the deadline passes,
    /// collecting every event per side. The owner serves one file.
    fn pump(
        owner: &mut CollabSession,
        guest: &mut CollabSession,
        owner_text: &str,
        done: impl Fn(&[CollabEvent], &[CollabEvent]) -> bool,
    ) -> (Vec<CollabEvent>, Vec<CollabEvent>) {
        use std::time::{Duration, Instant};
        let deadline = Instant::now() + Duration::from_secs(5);
        let (mut oe, mut ge) = (Vec::new(), Vec::new());
        while !done(&oe, &ge) {
            assert!(Instant::now() < deadline, "sessions never settled");
            oe.extend(owner.poll(|_| Some(owner_text.to_string())));
            ge.extend(guest.poll(|_| None));
            std::thread::sleep(Duration::from_millis(5));
        }
        (oe, ge)
    }

    /// #1147: an owner that stops heartbeating (a crash, no goodbye) is
    /// taken for gone once [`OWNER_GONE_AFTER`] lapses, and the guest's live
    /// files go local-only so it can save them.
    #[test]
    fn a_silent_owner_is_taken_for_gone_after_the_heartbeat_lapses() {
        let (_dir, mut owner, mut guest) = session_pair();
        guest.request_file("plan.txt");
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while !(guest.is_live("plan.txt") && guest.owner_seen.is_some()) {
            assert!(std::time::Instant::now() < deadline, "never bootstrapped");
            owner.poll(|_| Some("Due: Friday".to_string()));
            guest.poll(|_| None);
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        guest.owner_seen = Some(std::time::Instant::now() - OWNER_GONE_AFTER * 2);
        let events = guest.poll(|_| None);
        assert!(events.iter().any(|e| matches!(e, CollabEvent::OwnerLeft)));
        assert!(guest.owner_gone() && guest.is_local_only("plan.txt"));
        // Its heartbeat coming back rejoins the file.
        let (_, ge) = pump(&mut owner, &mut guest, "Due: Friday", |_, ge| {
            ge.iter()
                .any(|e| matches!(e, CollabEvent::OwnerReturned { .. }))
        });
        assert!(ge.iter().any(|e| matches!(
            e,
            CollabEvent::OwnerReturned { files } if files == &vec!["plan.txt".to_string()]
        )));
        assert!(!guest.owner_gone() && !guest.is_local_only("plan.txt"));
    }

    /// A guest that never heard a heartbeat (an owner too old to send one)
    /// never decides the owner left, and an owner's own session never does.
    #[test]
    fn no_heartbeat_heard_means_no_owner_left() {
        let (_dir, mut owner, mut guest) = session_pair();
        guest.request_file("plan.txt");
        // Bootstrap with the owner answering but its heartbeat dropped.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while !guest.is_live("plan.txt") {
            assert!(std::time::Instant::now() < deadline);
            owner.heartbeat_at = std::time::Instant::now() + OWNER_GONE_AFTER * 4;
            owner.poll(|_| Some("Due: Friday".to_string()));
            guest.poll(|_| None);
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        assert!(guest.owner_seen.is_none());
        for _ in 0..20 {
            let ev = guest.poll(|_| None);
            assert!(!ev.iter().any(|e| matches!(e, CollabEvent::OwnerLeft)));
            let ev = owner.poll(|_| None);
            assert!(!ev.iter().any(|e| matches!(e, CollabEvent::OwnerLeft)));
        }
        assert!(!guest.owner_gone() && guest.is_live("plan.txt"));
    }

    /// The full slice-4 handshake headlessly: a guest bootstraps a file from
    /// the owner through the relay, edits it, and the owner's replica
    /// converges; carets travel too.
    #[test]
    fn collab_sessions_bootstrap_and_converge_through_the_relay() {
        let (_dir, mut owner, mut guest) = session_pair();

        guest.request_file("src/f.rs");
        assert!(guest.is_bootstrapping("src/f.rs"));
        let (_, ge) = pump(&mut owner, &mut guest, "hello world", |_, ge| {
            ge.iter()
                .any(|e| matches!(e, CollabEvent::Bootstrapped { .. }))
        });
        let text = ge
            .iter()
            .find_map(|e| match e {
                CollabEvent::Bootstrapped { text, .. } => Some(text.clone()),
                _ => None,
            })
            .unwrap();
        assert_eq!(text, "hello world");
        assert!(guest.is_live("src/f.rs"));
        assert!(owner.is_live("src/f.rs"), "answering seeds the owner doc");

        // Guest edits; the owner's replica converges through the relay.
        assert!(guest.local_change("src/f.rs", "hello brave world"));
        guest.send_caret("src/f.rs", 0, 5);
        let (oe, _) = pump(&mut owner, &mut guest, "hello world", |oe, _| {
            oe.iter()
                .any(|e| matches!(e, CollabEvent::RemoteEdit { .. }))
                && oe.iter().any(|e| matches!(e, CollabEvent::Caret { .. }))
        });
        assert_eq!(owner.doc_text("src/f.rs"), Some("hello brave world"));
        assert!(oe.iter().any(
            |e| matches!(e, CollabEvent::Caret { row: 0, col: 5, name, .. } if name == "guest")
        ));
    }

    /// Sticky notes (#367) travel between sessions, and a joiner's request
    /// reaches only the owner.
    #[test]
    fn collab_sessions_carry_sticky_notes_and_the_joiners_request() {
        let (_dir, mut owner, mut guest) = session_pair();
        let mut notes = crate::sticky_notes::Notes::default();
        let note = notes.add("guest", "src/f.rs", 2, "let x = 1;", "why 1?");
        guest.send_note(&note);
        guest.send_notes_request();
        let (oe, _) = pump(&mut owner, &mut guest, "unused", |oe, _| {
            oe.iter().any(|e| matches!(e, CollabEvent::Note(_)))
                && oe.iter().any(|e| matches!(e, CollabEvent::NotesRequested))
        });
        assert!(
            oe.iter()
                .any(|e| matches!(e, CollabEvent::Note(n) if n == &note))
        );

        owner.send_notes_request();
        owner.send_note(&note);
        let (_, ge) = pump(&mut owner, &mut guest, "unused", |_, ge| {
            ge.iter().any(|e| matches!(e, CollabEvent::Note(_)))
        });
        assert!(
            !ge.iter().any(|e| matches!(e, CollabEvent::NotesRequested)),
            "only the owner answers for the notes"
        );
    }

    /// Stream state and cancel travel between sessions without any doc being
    /// live (they are session-level, not doc-gated: the pilot may broadcast
    /// before the file bootstraps, and anyone may cancel).
    #[test]
    fn collab_sessions_carry_stream_state_and_cancel() {
        let (_dir, mut owner, mut guest) = session_pair();

        guest.send_stream_state("src/f.rs", true);
        let (oe, _) = pump(&mut owner, &mut guest, "unused", |oe, _| {
            oe.iter()
                .any(|e| matches!(e, CollabEvent::StreamState { .. }))
        });
        assert!(oe.iter().any(|e| matches!(
            e,
            CollabEvent::StreamState { file, name, active: true, .. }
                if file == "src/f.rs" && name == "guest"
        )));

        owner.send_stream_cancel();
        let (_, ge) = pump(&mut owner, &mut guest, "unused", |_, ge| {
            ge.iter().any(|e| matches!(e, CollabEvent::StreamCancel))
        });
        assert!(ge.iter().any(|e| matches!(e, CollabEvent::StreamCancel)));
    }

    /// Concurrent edits on both sides converge to the identical text.
    #[test]
    fn collab_sessions_concurrent_edits_converge() {
        let (_dir, mut owner, mut guest) = session_pair();
        guest.request_file("src/f.rs");
        pump(&mut owner, &mut guest, "shared base", |_, ge| {
            ge.iter()
                .any(|e| matches!(e, CollabEvent::Bootstrapped { .. }))
        });

        owner.local_change("src/f.rs", "MODIFIED shared base");
        guest.local_change("src/f.rs", "shared base plus tail");
        pump(&mut owner, &mut guest, "shared base", |oe, ge| {
            oe.iter()
                .any(|e| matches!(e, CollabEvent::RemoteEdit { .. }))
                && ge
                    .iter()
                    .any(|e| matches!(e, CollabEvent::RemoteEdit { .. }))
        });
        assert_eq!(owner.doc_text("src/f.rs"), guest.doc_text("src/f.rs"));
    }

    /// No echo: once both sides converge and re-extract their (unchanged)
    /// buffers, the wire goes quiet — an op re-emitted for a remote edit
    /// would bounce between peers forever.
    #[test]
    fn collab_sessions_do_not_echo_applied_remote_edits() {
        let (_dir, mut owner, mut guest) = session_pair();
        guest.request_file("src/f.rs");
        pump(&mut owner, &mut guest, "abc", |_, ge| {
            ge.iter()
                .any(|e| matches!(e, CollabEvent::Bootstrapped { .. }))
        });

        owner.local_change("src/f.rs", "abcX");
        pump(&mut owner, &mut guest, "abc", |_, ge| {
            ge.iter()
                .any(|e| matches!(e, CollabEvent::RemoteEdit { .. }))
        });
        assert_eq!(guest.doc_text("src/f.rs"), Some("abcX"));

        // The app's tick re-extracts each side's buffer, which now equals
        // the replica text: nothing may be sent or received after that.
        assert!(!owner.local_change("src/f.rs", "abcX"));
        assert!(!guest.local_change("src/f.rs", "abcX"));
        for _ in 0..20 {
            assert!(owner.poll(|_| None).is_empty(), "owner must stay quiet");
            assert!(guest.poll(|_| None).is_empty(), "guest must stay quiet");
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
    }

    /// A guest with no owner on the relay stops waiting after the deadline
    /// instead of gating input forever.
    #[test]
    fn bootstrap_times_out_without_an_owner() {
        let (_dir, _owner, mut guest) = session_pair();
        // The owner exists but never polls (never answers).
        guest.request_file("src/f.rs");
        let deadline =
            std::time::Instant::now() + BOOTSTRAP_TIMEOUT + std::time::Duration::from_secs(3);
        loop {
            let events = guest.poll(|_| None);
            if events
                .iter()
                .any(|e| matches!(e, CollabEvent::BootstrapTimedOut { .. }))
            {
                break;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "bootstrap never timed out"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        assert!(!guest.is_bootstrapping("src/f.rs"));
        assert!(!guest.is_live("src/f.rs"));
    }

    /// One peer that stops reading (SIGSTOPped, or wedged mid-write) must
    /// not take the whole session down: the relay used to blocking-write to
    /// every peer while holding the global client list mutex, so a full
    /// send buffer wedged the forwarding thread, which starved every other
    /// peer's writes AND blocked their reader threads on the same mutex —
    /// a three-process deadlock. A bounded write drops the wedged peer and
    /// traffic keeps flowing to the rest.
    #[test]
    fn a_wedged_peer_cannot_deadlock_the_relay() {
        use std::io::Write;
        use std::time::{Duration, Instant};
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("w.collab.sock");
        {
            let s = socket.clone();
            std::thread::spawn(move || {
                let _ = relay_serve(&s);
            });
        }
        let deadline = Instant::now() + Duration::from_secs(5);
        while !crate::session::is_alive(&socket) {
            assert!(Instant::now() < deadline, "relay never came up");
            std::thread::sleep(Duration::from_millis(10));
        }
        // A connects and never reads a byte.
        let _a = std::os::unix::net::UnixStream::connect(&socket).unwrap();
        // C drains everything, watching for the marker frame.
        let mut c = std::os::unix::net::UnixStream::connect(&socket).unwrap();
        let (found_tx, found_rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            use crate::session_host::{Frame, FrameReader};
            let mut reader = FrameReader::new();
            let mut buf = [0u8; 16384];
            loop {
                let n = match c.read(&mut buf) {
                    Ok(0) | Err(_) => return,
                    Ok(n) => n,
                };
                for frame in reader.push(&buf[..n]) {
                    if matches!(&frame, Frame::Bytes(p) if p.as_slice() == b"MARKER") {
                        let _ = found_tx.send(());
                        return;
                    }
                }
            }
        });
        // B floods well past every kernel buffer (wedging the relay's
        // writes to A), then sends the marker.
        let mut b = std::os::unix::net::UnixStream::connect(&socket).unwrap();
        b.set_nonblocking(true).unwrap();
        let mut push = |bytes: &[u8]| {
            let mut written = 0;
            let deadline = Instant::now() + Duration::from_secs(20);
            while written < bytes.len() {
                assert!(
                    Instant::now() < deadline,
                    "sender starved: the relay is wedged on the peer that never reads"
                );
                match b.write(&bytes[written..]) {
                    Ok(n) => written += n,
                    Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                        std::thread::sleep(Duration::from_millis(2));
                    }
                    Err(e) => panic!("sender failed: {e}"),
                }
            }
        };
        let frame = crate::session_host::encode_bytes_frame(&[0u8; 4096]);
        for _ in 0..256 {
            push(&frame);
        }
        push(&crate::session_host::encode_bytes_frame(b"MARKER"));
        assert!(
            found_rx.recv_timeout(Duration::from_secs(10)).is_ok(),
            "the marker never reached the healthy peer: the relay is wedged"
        );
    }

    /// A relay that hangs up must be visible: EOF on the drain marks the
    /// channel dead and the session disconnected, so the app can drop it
    /// and reconnect. EOF used to read exactly like an idle socket, so a
    /// guest kept typing into a buffer whose ops reached nobody — with
    /// saves still gated, the work existed only in RAM.
    #[test]
    fn a_dead_relay_marks_the_session_disconnected() {
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("dead.collab.sock");
        let listener = std::os::unix::net::UnixListener::bind(&socket).unwrap();
        let mut session = CollabSession::new(
            CollabChannel::connect(&socket, CollabRole::Guest).expect("connects"),
            String::from("guest"),
        );
        let (peer, _) = listener.accept().unwrap();
        let _ = session.poll(|_| None);
        assert!(
            !session.disconnected(),
            "a healthy idle channel must not read as dead"
        );
        drop(peer); // the relay dies
        // The hangup is the KERNEL's to deliver: on a loaded box a single
        // nonblocking poll can land before the EOF is readable and observe
        // nothing (#125, twice on CI). Poll until the latch flips or a real
        // deadline passes — the state-gated wait #109/#110 established.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        while !session.disconnected() && std::time::Instant::now() < deadline {
            let _ = session.poll(|_| None);
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert!(
            session.disconnected(),
            "EOF from the relay must mark the session disconnected"
        );
    }

    /// Site ids are identity: a restarted owner re-allocating from the same
    /// fixed counter re-issues ids that surviving guests already hold,
    /// which permanently breaks convergence. Seeding the counter from the
    /// owner's process id keeps every owner incarnation's allocations
    /// disjoint.
    #[test]
    fn an_owner_seeds_site_ids_from_its_process_id() {
        let (_dir, mut owner, mut guest) = session_pair();
        guest.request_file("src/f.rs");
        pump(&mut owner, &mut guest, "abc", |_, ge| {
            ge.iter()
                .any(|e| matches!(e, CollabEvent::Bootstrapped { .. }))
        });
        let expected = ((std::process::id() as u64) << 32) | (OWNER_SITE + 1);
        assert_eq!(
            guest.my_site_ids(),
            vec![expected],
            "the first allocated site id must come from the pid-seeded range"
        );
    }

    /// A timed-out bootstrap is a latch, not a moment: the app's tick
    /// re-requests any open file that is neither live nor bootstrapping, so
    /// a timeout that merely forgot the file sent the guest straight back
    /// into the 3s input gate, forever — unable to ever type or save. After
    /// the give-up, request_file must be a no-op; only an explicit rejoin
    /// (the collab agent's collab_open retry) re-arms the bootstrap.
    #[test]
    fn a_timed_out_file_stays_local_only_through_re_requests() {
        let (_dir, _owner, mut guest) = session_pair();
        guest.request_file("src/f.rs");
        let deadline =
            std::time::Instant::now() + BOOTSTRAP_TIMEOUT + std::time::Duration::from_secs(3);
        loop {
            let events = guest.poll(|_| None);
            if events
                .iter()
                .any(|e| matches!(e, CollabEvent::BootstrapTimedOut { .. }))
            {
                break;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "bootstrap never timed out"
            );
            std::thread::sleep(std::time::Duration::from_millis(20));
        }
        // The app tick re-requests unshared open files: a no-op now.
        guest.request_file("src/f.rs");
        assert!(
            !guest.is_bootstrapping("src/f.rs"),
            "a re-request after the give-up must not re-arm the input gate"
        );
        assert!(guest.is_local_only("src/f.rs"));
        // An explicit rejoin starts a fresh bootstrap.
        guest.rejoin_file("src/f.rs");
        assert!(guest.is_bootstrapping("src/f.rs"));
    }

    /// An unanswered resend backs off (a guest cannot tell a lost request
    /// from a large reply still arriving, and a fixed 500ms cadence made
    /// the owner re-serialize the whole document while a slow snapshot was
    /// already in flight) - but the backoff is capped so the schedule still
    /// fits inside [`BOOTSTRAP_TIMEOUT`]. Unbounded doubling put the third
    /// resend past the deadline: an owner whose relay connection registered
    /// between 1.5s and 3s was never re-asked, and the guest silently
    /// degraded that file to local-only editing.
    #[test]
    fn snapshot_resend_backs_off_but_stays_inside_the_bootstrap_window() {
        use std::time::{Duration, Instant};
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("s.collab.sock");
        {
            let s = socket.clone();
            std::thread::spawn(move || {
                let _ = relay_serve(&s);
            });
        }
        let deadline = Instant::now() + Duration::from_secs(5);
        let mut guest = loop {
            if let Some(ch) = CollabChannel::connect(&socket, CollabRole::Guest) {
                break CollabSession::new(ch, "guest".into());
            }
            assert!(Instant::now() < deadline, "relay never came up");
            std::thread::sleep(Duration::from_millis(10));
        };
        guest.request_file("src/f.rs");
        // Fire three resends back to back (pulling the timer into the past
        // each time) and read how far out each one rescheduled itself.
        let mut waits: Vec<Duration> = Vec::new();
        for _ in 0..3 {
            {
                let Some(DocState::Bootstrapping {
                    resend_at,
                    deadline,
                    ..
                }) = guest.docs.get_mut("src/f.rs")
                else {
                    panic!("guest must still be bootstrapping");
                };
                *resend_at = Instant::now() - Duration::from_millis(1);
                *deadline = Instant::now() + Duration::from_secs(60);
            }
            let _ = guest.poll(|_| None);
            let Some(DocState::Bootstrapping { resend_at, .. }) = guest.docs.get("src/f.rs") else {
                panic!("guest must still be bootstrapping");
            };
            waits.push(resend_at.saturating_duration_since(Instant::now()));
        }
        assert!(
            waits[0] > SNAPSHOT_RESEND,
            "an unanswered resend must back off past the initial cadence, got {waits:?}"
        );
        for w in &waits {
            assert!(
                *w <= Duration::from_secs(1),
                "the backoff must cap at 1s so every resend fits inside the \
                 bootstrap window, got {waits:?}"
            );
        }
        // And the capped schedule provably fits: initial wait plus two
        // capped waits still lands the third resend before the deadline.
        assert!(
            SNAPSHOT_RESEND + Duration::from_secs(2) < BOOTSTRAP_TIMEOUT,
            "the resend schedule no longer fits inside BOOTSTRAP_TIMEOUT"
        );
    }

    /// A SnapshotRequest broadcast before the owner is reachable is not
    /// lost for good: the relay has no replay, so the guest must re-send
    /// while bootstrapping and an owner that appears moments later still
    /// answers.
    #[test]
    fn guest_resends_snapshot_request_until_an_owner_answers() {
        use std::time::{Duration, Instant};
        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("s.collab.sock");
        {
            let s = socket.clone();
            std::thread::spawn(move || {
                let _ = relay_serve(&s);
            });
        }
        // A registered observer proves when the relay has actually
        // broadcast the request (frames broadcast when the relay reads
        // them, not when the guest writes them).
        let deadline = Instant::now() + Duration::from_secs(5);
        let mut observer = loop {
            if let Some(ch) = CollabChannel::connect(&socket, CollabRole::Guest) {
                break ch;
            }
            assert!(Instant::now() < deadline, "relay never came up");
            std::thread::sleep(Duration::from_millis(10));
        };
        let mut guest = CollabSession::new(
            CollabChannel::connect(&socket, CollabRole::Guest).expect("guest connects"),
            "guest".into(),
        );
        guest.request_file("src/f.rs");
        // Once the observer sees the request, the broadcast is over — and
        // no owner was connected to receive it. That copy is gone forever.
        let deadline = Instant::now() + Duration::from_secs(5);
        while !observer
            .drain()
            .iter()
            .any(|m| matches!(m, CollabMsg::SnapshotRequest { .. }))
        {
            assert!(Instant::now() < deadline, "relay never broadcast");
            std::thread::sleep(Duration::from_millis(5));
        }
        let mut owner = CollabSession::new(
            CollabChannel::connect(&socket, CollabRole::Owner).expect("owner connects"),
            "owner".into(),
        );
        let (_, ge) = pump(&mut owner, &mut guest, "hello world", |_, ge| {
            ge.iter().any(|e| {
                matches!(
                    e,
                    CollabEvent::Bootstrapped { .. } | CollabEvent::BootstrapTimedOut { .. }
                )
            })
        });
        assert!(
            ge.iter()
                .any(|e| matches!(e, CollabEvent::Bootstrapped { .. })),
            "guest gave up instead of re-sending: {ge:?}"
        );
    }

    /// End-to-end transport: two participants connected through the relay
    /// exchange an op and converge, with the relay never inspecting it.
    #[test]
    fn ops_converge_through_the_relay() {
        use crate::session_host::{Frame, FrameReader};
        use std::io::{Read, Write};
        use std::os::unix::net::UnixStream;
        use std::time::{Duration, Instant};

        let dir = tempfile::tempdir().unwrap();
        let socket = dir.path().join("c.collab.sock");
        {
            let s = socket.clone();
            std::thread::spawn(move || {
                let _ = relay_serve(&s);
            });
        }
        // Wait for the relay to bind.
        let deadline = Instant::now() + Duration::from_secs(5);
        let mut ca = loop {
            if let Ok(s) = UnixStream::connect(&socket) {
                break s;
            }
            assert!(Instant::now() < deadline, "relay never came up");
            std::thread::sleep(Duration::from_millis(10));
        };
        let mut cb = UnixStream::connect(&socket).expect("second client connects");
        ca.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
        cb.set_read_timeout(Some(Duration::from_secs(5))).unwrap();

        let mut a = CollabDoc::new(1, "abc");
        let mut b = a.fork(2);

        // Read framed envelopes off a stream until one arrives.
        fn read_envelope(stream: &mut UnixStream, reader: &mut FrameReader) -> Envelope {
            let mut buf = [0u8; 4096];
            loop {
                let n = stream.read(&mut buf).expect("relay delivers a frame");
                for frame in reader.push(&buf[..n]) {
                    if let Frame::Bytes(payload) = frame {
                        return serde_json::from_slice(&payload).unwrap();
                    }
                }
            }
        }
        let mut reader_a = FrameReader::new();
        let mut reader_b = FrameReader::new();

        // B edits first and A waits for the forwarded frame: `connect`
        // returning does not mean the accept loop has registered a client
        // yet, but A *receiving* B's envelope proves both ends are
        // registered (B to be forwarded from, A to be forwarded to), so
        // A's own send below cannot fall into the registration window.
        // (Live participants tolerate that window by design: joining the
        // relay only promises messages sent after the join completes, and
        // the bootstrap handshake is what synchronizes real sessions.)
        let op_b = b.local_insert(0, "Y"); // b: "Yabc"
        cb.write_all(
            &Envelope {
                file: "f.rs".into(),
                site: 2,
                op: op_b,
            }
            .encode(),
        )
        .unwrap();
        a.apply_remote(&read_envelope(&mut ca, &mut reader_a).op);
        assert_eq!(a.text(), "Yabc");

        // Now the reverse direction: A edits, B integrates, both converge.
        let op_a = a.local_insert(4, "Z"); // a: "YabcZ"
        ca.write_all(
            &Envelope {
                file: "f.rs".into(),
                site: 1,
                op: op_a,
            }
            .encode(),
        )
        .unwrap();
        let got = read_envelope(&mut cb, &mut reader_b);
        b.apply_remote(&got.op);

        assert_eq!(got.file, "f.rs");
        assert_eq!(b.text(), a.text());
        assert_eq!(b.text(), "YabcZ");
    }
}