bcode_server 0.0.1-alpha.0

Local bcode daemon runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
//! Unified non-blocking session catalog snapshots.

use crate::ServerState;
use bcode_session::SessionCatalogEntry;
use bcode_session_import::ImportableSessionStatus;
use bcode_session_models::{SessionCatalogSourceStatus, SessionCatalogStatus};
use bcode_session_models::{SessionId, SessionImportSummary, SessionSummary, SessionTitleSource};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::{Mutex, Notify, OnceCell, watch};

const NATIVE_SOURCE_ID: &str = "native";
const NATIVE_DISPLAY_NAME: &str = "Native Bcode sessions";

/// Server-owned session catalog cache.
#[derive(Debug)]
pub struct SessionCatalog {
    inner: Mutex<SessionCatalogInner>,
    revision_tx: watch::Sender<u64>,
    revision_rx: watch::Receiver<u64>,
    notify: Notify,
    import_sources: Mutex<BTreeMap<String, Arc<OnceCell<Vec<String>>>>>,
    #[cfg(test)]
    discovery_gate: Mutex<Option<Arc<tokio::sync::Semaphore>>>,
}

#[derive(Debug, Default)]
struct SessionCatalogInner {
    revision: u64,
    sources: BTreeMap<CatalogSourceKey, SourceCache>,
    import_plans: BTreeMap<PathBuf, Option<Vec<CatalogSourcePlan>>>,
    planning_generation: u64,
    retry_import_plans: BTreeMap<PathBuf, std::time::Instant>,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct CatalogSourceKey {
    source_id: String,
    scope: CatalogSourceScope,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum CatalogSourceScope {
    Global,
    WorkingDirectory(PathBuf),
}

#[derive(Debug, Clone)]
struct SourceMetadata {
    display_name: String,
}

#[derive(Debug, Clone)]
struct SourceCache {
    metadata: SourceMetadata,
    state: SourceCacheState,
    updated_at_ms: u64,
    generation: u64,
}

#[derive(Debug, Clone)]
enum SourceCacheState {
    Empty,
    Loading {
        sessions: Vec<SessionSummary>,
    },
    Loaded {
        sessions: Vec<SessionSummary>,
        diagnostics: SourceDiagnostics,
    },
    Failed {
        retry_at: std::time::Instant,
        message: String,
        sessions: Vec<SessionSummary>,
        diagnostics: SourceDiagnostics,
    },
}

#[derive(Debug, Clone, Default)]
struct SourceDiagnostics {}

#[derive(Debug, Clone)]
enum CatalogSourcePlan {
    /// Sessions owned by an in-memory manager, with no durable location claim.
    InMemory,
    /// Canonical sessions owned by one resolved state location.
    ///
    /// The primary location is loaded through the owning `SessionManager`. Additional
    /// readable locations are discovered read-only: no canonical database is opened, no
    /// lease or lock is taken, and nothing is migrated or repaired. Aggregated discovery
    /// confers no authority.
    Native { location: NativeLocation },
    Import {
        plugin_id: String,
        source_id: String,
        working_directory: PathBuf,
    },
}

/// One state location participating in aggregated native discovery.
#[derive(Debug, Clone, PartialEq, Eq)]
struct NativeLocation {
    location_id: String,
    profile: Option<String>,
    sessions_root: PathBuf,
    primary: bool,
}

impl NativeLocation {
    fn source_id(&self) -> String {
        if self.primary {
            NATIVE_SOURCE_ID.to_owned()
        } else {
            format!("{NATIVE_SOURCE_ID}:{}", self.location_id)
        }
    }

    fn display_name(&self) -> String {
        match (&self.profile, self.primary) {
            (Some(profile), true) => format!("{NATIVE_DISPLAY_NAME} [{profile}]"),
            (Some(profile), false) => format!("Bcode sessions [{profile}]"),
            (None, true) => NATIVE_DISPLAY_NAME.to_owned(),
            (None, false) => format!("Bcode sessions [{}]", self.location_id),
        }
    }

    fn summary(&self) -> bcode_session_models::SessionLocationSummary {
        bcode_session_models::SessionLocationSummary {
            location_id: self.location_id.clone(),
            profile: self.profile.clone(),
            primary: self.primary,
            ambiguous: false,
        }
    }
}

/// Point-in-time catalog response for one working directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionCatalogSnapshot {
    pub sessions: Vec<SessionSummary>,
    pub status: SessionCatalogStatus,
    pub sources: Vec<SessionCatalogSourceStatus>,
    pub revision: u64,
}

impl Default for SessionCatalog {
    fn default() -> Self {
        let (revision_tx, revision_rx) = watch::channel(0);
        Self {
            inner: Mutex::default(),
            revision_tx,
            revision_rx,
            notify: Notify::new(),
            import_sources: Mutex::default(),
            #[cfg(test)]
            discovery_gate: Mutex::default(),
        }
    }
}

impl SessionCatalog {
    /// Subscribe to catalog revision changes.
    pub fn subscribe(&self) -> watch::Receiver<u64> {
        self.revision_rx.clone()
    }

    /// Return the current catalog revision without starting discovery or loading storage.
    #[must_use]
    pub fn revision(&self) -> u64 {
        *self.revision_rx.borrow()
    }

    /// Read native candidates directly, without starting full catalog discovery.
    /// Empty filtered windows may carry a continuation; each location contributes at most
    /// 256 candidates and only one bounded merged window is returned.
    ///
    /// # Errors
    /// Returns an error for invalid limits, oversized queries, relative directory scopes,
    /// changed cursor selections and unavailable cursor locations. Revision updates are
    /// permitted because pages are live keyset windows rather than coherent snapshots.
    pub async fn page_with_scope(
        &self,
        state: &Arc<ServerState>,
        scope: bcode_session_models::SessionDiscoveryScope,
        query: bcode_session_models::SessionCatalogQuery,
        cursor: Option<bcode_session_models::SessionCatalogCursor>,
        limit: usize,
    ) -> Result<bcode_session_models::SessionCatalogPage, String> {
        use bcode_session_models::{
            SessionCatalogCursor, SessionCatalogPage, SessionDiscoveryScope,
        };
        validate_catalog_selection(&scope, &query, limit)?;
        let revision = *self.revision_rx.borrow();
        // Activity keysets are live windows, not revision-pinned snapshots. Unrelated
        // discovery completion or session updates must not make ordinary browsing fail.
        let local_import_gap = matches!(scope, SessionDiscoveryScope::WorkingDirectory(_));
        if let Some(cursor) = &cursor
            && (cursor.scope != scope || cursor.query != query)
        {
            return Err("catalog cursor selection changed; restart from the first page".into());
        }
        let locations = native_locations(state);
        if cursor
            .as_ref()
            .is_some_and(|cursor| cursor.location_index >= locations.len().max(1))
        {
            return Err("catalog cursor location is no longer available; restart".into());
        }
        let after = cursor.as_ref().and_then(|cursor| cursor.after);
        let mut candidates = Vec::new();
        let mut sources = Vec::new();
        let mut degraded = false;
        for (index, location) in locations.iter().enumerate() {
            let include_boundary = cursor
                .as_ref()
                .is_some_and(|cursor| index > cursor.location_index);
            let result = bcode_session::SessionStore::new(&location.sessions_root)
                .discovery_activity_page(after, include_boundary, limit)
                .await;
            let damaged = result.map_or(true, |page| {
                let damaged = page.iter().any(|candidate| candidate.summary.is_none());
                candidates.extend(page.into_iter().map(|candidate| (index, candidate)));
                damaged
            });
            degraded |= damaged;
            sources.push(SessionCatalogSourceStatus {
                source_id: location.source_id(), display_name: location.display_name(),
                updated_at_ms: 0,
                status: if damaged { SessionCatalogStatus::Degraded("native catalog metadata missing or unsupported; explicit maintenance required".into()) } else { SessionCatalogStatus::Loaded },
            });
        }
        if locations.is_empty() {
            candidates.extend(
                state
                    .sessions
                    .loaded_catalog_activity_page(after, limit)
                    .await
                    .into_iter()
                    .map(|candidate| (0, candidate)),
            );
        }
        candidates.sort_by_key(|(index, candidate)| (candidate.position.sort_key(), *index));
        candidates.truncate(limit);
        let next_cursor =
            candidates
                .last()
                .filter(|_| candidates.len() == limit)
                .map(|(index, candidate)| SessionCatalogCursor {
                    scope: scope.clone(),
                    query: query.clone(),
                    revision,
                    location_index: *index,
                    after: Some(candidate.position),
                });
        let mut sessions = Vec::new();
        for (index, candidate) in candidates {
            if let Some(mut session) = candidate.summary {
                if let Some(location) = locations.get(index) {
                    session.location = Some(location.summary());
                    let claims = exact_location_claims(state, session.id);
                    if let Some(location) = &mut session.location {
                        location.ambiguous =
                            claims.as_ref().map_or(true, |claims| claims.len() > 1);
                    }
                }
                sessions.push(session);
            }
        }
        let text = query.text.as_ref().map(|text| text.to_lowercase());
        sessions.retain(|session| catalog_summary_matches(session, &scope, text.as_deref()));
        Ok(SessionCatalogPage {
            sessions,
            catalog_status: if degraded || local_import_gap {
                SessionCatalogStatus::Degraded("native catalog requires maintenance or local imports require the compatibility listing API".into())
            } else {
                SessionCatalogStatus::Loaded
            },
            catalog_sources: sources,
            catalog_revision: revision,
            next_cursor,
        })
    }

    /// Return the current coherent catalog snapshot for a working directory.
    pub async fn snapshot(
        &self,
        state: &Arc<ServerState>,
        working_directory: &Path,
    ) -> SessionCatalogSnapshot {
        let working_directory = normalize_path(working_directory);
        self.ensure_sources(state, &working_directory).await;
        let hide_imported = if state.locations.is_some() {
            state.startup_config.session_import.hide_already_imported
        } else {
            bcode_config::load_config()
                .map_or(true, |config| config.session_import.hide_already_imported)
        };
        let inner = self.inner.lock().await;
        snapshot_locked(&inner, &working_directory, hide_imported)
    }

    /// Return whether more than one readable state location claims this session ID.
    ///
    /// Ambiguity is reported from already-loaded catalog state only; this never triggers
    /// discovery, opens canonical storage, or takes a lease. Callers must refuse to open an
    /// ambiguous session as authoritative until explicit maintenance resolves the conflict.
    pub async fn ambiguous_location_ids(&self, session_id: SessionId) -> Vec<String> {
        let mut locations = BTreeSet::new();
        {
            let inner = self.inner.lock().await;
            for source in inner.sources.values() {
                for session in source.sessions() {
                    if session.id == session_id
                        && let Some(location) = &session.location
                    {
                        locations.insert(location.location_id.clone());
                    }
                }
            }
        }
        if locations.len() > 1 {
            locations.into_iter().collect()
        } else {
            Vec::new()
        }
    }

    /// Replace the primary native source with a fresh view from the session manager.
    pub async fn refresh_native_now(&self, state: &ServerState) {
        let generation = {
            let mut inner = self.inner.lock().await;
            let source = inner
                .sources
                .entry(native_source_key())
                .or_insert_with(|| SourceCache {
                    metadata: native_metadata(),
                    state: SourceCacheState::Empty,
                    updated_at_ms: 0,
                    generation: 0,
                });
            source.generation += 1;
            let generation = source.generation;
            drop(inner);
            generation
        };
        if state.sessions.session_store_root().is_none() {
            self.publish_source_result(
                native_source_key(),
                native_metadata(),
                load_in_memory_source(state).await,
                Some(generation),
            )
            .await;
            return;
        }
        let Some(location) = native_locations(state)
            .into_iter()
            .find(|location| location.primary)
        else {
            return;
        };
        let result = load_native_source(state, &location).await;
        self.publish_source_result(
            native_source_key(),
            native_metadata(),
            result,
            Some(generation),
        )
        .await;
    }

    /// Mark native sessions dirty so the next snapshot reloads them.
    pub async fn invalidate_native(&self) {
        self.invalidate_source_id(NATIVE_SOURCE_ID).await;
    }

    #[allow(clippy::significant_drop_tightening)]
    /// Update a materialized native session cache after a native session mutation.
    pub async fn upsert_native_session(&self, session: SessionSummary) {
        let mut inner = self.inner.lock().await;
        let Some(source) = inner.sources.get_mut(&native_source_key()) else {
            return;
        };
        let sessions = match &mut source.state {
            SourceCacheState::Loaded { sessions, .. }
            | SourceCacheState::Failed { sessions, .. } => sessions,
            SourceCacheState::Empty | SourceCacheState::Loading { .. } => {
                source.generation += 1;
                source.state = SourceCacheState::Empty;
                source.updated_at_ms = current_unix_millis();
                self.bump_revision(&mut inner);
                return;
            }
        };
        if upsert_session(sessions, session) {
            source.generation += 1;
            source.updated_at_ms = current_unix_millis();
            self.bump_revision(&mut inner);
        }
    }

    #[allow(clippy::significant_drop_tightening)]
    /// Remove a native session from a materialized native session cache.
    pub async fn remove_native_session(&self, session_id: SessionId) {
        let mut inner = self.inner.lock().await;
        let Some(source) = inner.sources.get_mut(&native_source_key()) else {
            return;
        };
        let sessions = match &mut source.state {
            SourceCacheState::Loaded { sessions, .. }
            | SourceCacheState::Failed { sessions, .. } => sessions,
            SourceCacheState::Empty | SourceCacheState::Loading { .. } => {
                source.generation += 1;
                source.state = SourceCacheState::Empty;
                source.updated_at_ms = current_unix_millis();
                self.bump_revision(&mut inner);
                return;
            }
        };
        let original_len = sessions.len();
        sessions.retain(|session| session.id != session_id);
        if sessions.len() != original_len {
            source.generation += 1;
            source.updated_at_ms = current_unix_millis();
            self.bump_revision(&mut inner);
        }
    }

    /// Force a catalog refresh for the selected sources.
    pub async fn refresh(
        &self,
        state: &Arc<ServerState>,
        working_directory: &Path,
        sources: Option<&[String]>,
    ) -> SessionCatalogSnapshot {
        let working_directory = normalize_path(working_directory);
        // Source enumeration is cached independently of per-directory session discovery.
        // A refresh must discover newly available sources too. In-flight readers retain
        // their old cell, but cannot repopulate the invalidated cache.
        {
            let mut inner = self.inner.lock().await;
            inner.planning_generation += 1;
            inner.import_plans.clear();
            inner.retry_import_plans.clear();
            self.bump_revision(&mut inner);
            drop(inner);
        }
        self.import_sources.lock().await.clear();
        self.invalidate_sources(&working_directory, sources).await;
        self.snapshot(state, &working_directory).await
    }

    async fn import_source_ids(
        &self,
        plugin_id: &str,
        load: impl std::future::Future<Output = Result<Vec<String>, String>>,
    ) -> Vec<String> {
        let cell = {
            let mut sources = self.import_sources.lock().await;
            Arc::clone(sources.entry(plugin_id.to_owned()).or_default())
        };
        // OnceCell coalesces concurrent enumeration, releases initialization on
        // cancellation, and retains only successes so transient failures can retry.
        cell.get_or_try_init(|| load)
            .await
            .cloned()
            .unwrap_or_default()
    }

    async fn ensure_sources(&self, state: &Arc<ServerState>, working_directory: &Path) {
        let directory = working_directory.to_path_buf();
        let load_state = Arc::clone(state);
        let load_directory = directory.clone();
        self.ensure_sources_with_imports(state, directory, async move {
            source_plans(&load_state, &load_directory).await
        })
        .await;
    }

    async fn ensure_sources_with_imports(
        &self,
        state: &Arc<ServerState>,
        working_directory: PathBuf,
        imports: impl std::future::Future<Output = Vec<CatalogSourcePlan>> + Send + 'static,
    ) {
        for plan in native_source_plans(state) {
            self.ensure_source(state, plan).await;
        }
        let mut inner = self.inner.lock().await;
        let retry = inner
            .retry_import_plans
            .get(&working_directory)
            .is_some_and(|deadline| std::time::Instant::now() >= *deadline);
        if retry {
            inner.retry_import_plans.remove(&working_directory);
        }
        if let Some(plans) = inner.import_plans.get(&working_directory) {
            let plans = plans.clone().unwrap_or_default();
            let generation = inner.planning_generation;
            drop(inner);
            for plan in plans {
                self.ensure_source_for_generation(state, plan, Some(generation))
                    .await;
            }
            if !retry {
                return;
            }
            inner = self.inner.lock().await;
            // Another observer may already have started the retry.
            if inner
                .import_plans
                .get(&working_directory)
                .is_some_and(Option::is_none)
            {
                return;
            }
        }
        let generation = inner.planning_generation;
        inner.import_plans.insert(working_directory.clone(), None);
        self.bump_revision(&mut inner);
        drop(inner);
        let state = Arc::clone(state);
        tokio::spawn(async move {
            let plans = imports.await;
            let catalog = &state.session_catalog;
            let enumeration_complete = catalog
                .import_sources
                .lock()
                .await
                .values()
                .all(|cell| cell.initialized());
            let mut inner = catalog.inner.lock().await;
            let mut retry_deadline = None;
            if inner.planning_generation == generation {
                if !enumeration_complete {
                    // Install successful providers' plans before retrying failed enumeration.
                    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
                    inner
                        .retry_import_plans
                        .insert(working_directory.clone(), deadline);
                    retry_deadline = Some(deadline);
                }
                inner
                    .import_plans
                    .insert(working_directory.clone(), Some(plans));
                catalog.bump_revision(&mut inner);
            }
            drop(inner);
            let weak_state = Arc::downgrade(&state);
            drop(state);
            if let Some(deadline) = retry_deadline {
                notify_planning_retry(&weak_state, working_directory, generation, deadline).await;
            }
            drop(weak_state);
        });
    }

    async fn ensure_source(&self, state: &Arc<ServerState>, plan: CatalogSourcePlan) {
        self.ensure_source_for_generation(state, plan, None).await;
    }

    #[allow(clippy::significant_drop_tightening)]
    async fn ensure_source_for_generation(
        &self,
        state: &Arc<ServerState>,
        plan: CatalogSourcePlan,
        planning_generation: Option<u64>,
    ) {
        let key = plan.key();
        let metadata = plan.metadata();
        let generation = {
            let mut inner = self.inner.lock().await;
            if planning_generation.is_some_and(|generation| generation != inner.planning_generation)
            {
                return;
            }
            let source = inner
                .sources
                .entry(key.clone())
                .or_insert_with(|| SourceCache {
                    metadata: metadata.clone(),
                    state: SourceCacheState::Empty,
                    updated_at_ms: 0,
                    generation: 0,
                });
            source.metadata = metadata.clone();
            match source.state {
                SourceCacheState::Failed { retry_at, .. }
                    if std::time::Instant::now() < retry_at =>
                {
                    None
                }
                SourceCacheState::Empty | SourceCacheState::Failed { .. } => {
                    source.state = SourceCacheState::Loading {
                        sessions: source.sessions().to_vec(),
                    };
                    source.updated_at_ms = current_unix_millis();
                    source.generation += 1;
                    let generation = source.generation;
                    self.bump_revision(&mut inner);
                    Some(generation)
                }
                SourceCacheState::Loading { .. } | SourceCacheState::Loaded { .. } => None,
            }
        };
        let Some(generation) = generation else {
            return;
        };
        let state = Arc::clone(state);
        let catalog = Arc::clone(&state.session_catalog);
        tokio::spawn(async move {
            let key = plan.key();
            let metadata = plan.metadata();
            let labels = catalog_source_metric_labels(&key);
            if let CatalogSourcePlan::Native { location } = &plan
                && location.primary
                && !state.sessions.catalog_loaded()
            {
                let store = bcode_session::SessionStore::new(&location.sessions_root);
                let (mut pages, completion) = store.stream_catalog_pages();
                while let Some(mut page) = pages.recv().await {
                    for summary in &mut page {
                        summary.location = Some(location.summary());
                    }
                    let mut inner = catalog.inner.lock().await;
                    let Some(source) = inner.sources.get_mut(&key) else {
                        break;
                    };
                    if source.generation != generation {
                        break;
                    }
                    let SourceCacheState::Loading { sessions } = &mut source.state else {
                        break;
                    };
                    if !page.is_empty() {
                        merge_catalog_page(sessions, page);
                        source.updated_at_ms = current_unix_millis();
                        catalog.bump_revision(&mut inner);
                    }
                }
                drop(pages);
                // Missing or damaged disposable catalogs fall back to normal discovery.
                if let Err(error) = completion.await {
                    tracing::warn!(%error, "catalog page reader task failed");
                }
            }
            let result = state
                .metrics
                .time_result_async(
                    "session.catalog.source_load",
                    labels.clone(),
                    load_source(&state, &plan),
                )
                .await;
            if let Ok(source) = &result {
                state.metrics.record_histogram_with_labels(
                    "session.catalog.source_load.sessions",
                    source.sessions.len() as u64,
                    labels,
                );
            }
            catalog
                .publish_source_result(key, metadata, result, Some(generation))
                .await;
        });
    }

    async fn invalidate_sources(&self, working_directory: &Path, sources: Option<&[String]>) {
        let refresh_all = sources.is_none_or(<[String]>::is_empty);
        let should_refresh = |source_id: &str| {
            refresh_all
                || sources.is_some_and(|sources| sources.iter().any(|source| source == source_id))
        };
        let mut changed = false;
        {
            let mut inner = self.inner.lock().await;
            for (key, source) in &mut inner.sources {
                let in_scope = matches!(key.scope, CatalogSourceScope::Global)
                    || matches!(&key.scope, CatalogSourceScope::WorkingDirectory(path) if path == working_directory);
                if in_scope && should_refresh(&key.source_id) {
                    source.generation += 1;
                    source.state = SourceCacheState::Empty;
                    source.updated_at_ms = current_unix_millis();
                    changed = true;
                }
            }
            if changed {
                self.bump_revision(&mut inner);
            }
            drop(inner);
        }
    }

    async fn invalidate_source_id(&self, source_id: &str) {
        let mut changed = false;
        {
            let mut inner = self.inner.lock().await;
            for (key, source) in &mut inner.sources {
                if key.source_id == source_id {
                    source.generation += 1;
                    source.state = SourceCacheState::Empty;
                    source.updated_at_ms = current_unix_millis();
                    changed = true;
                }
            }
            if changed {
                self.bump_revision(&mut inner);
            }
            drop(inner);
        }
    }

    #[cfg(test)]
    async fn apply_source_result(
        &self,
        key: CatalogSourceKey,
        metadata: SourceMetadata,
        result: Result<SourceLoadResult, String>,
    ) {
        self.publish_source_result(key, metadata, result, None)
            .await;
    }

    async fn publish_source_result(
        &self,
        key: CatalogSourceKey,
        metadata: SourceMetadata,
        result: Result<SourceLoadResult, String>,
        expected_generation: Option<u64>,
    ) {
        {
            let mut inner = self.inner.lock().await;
            if let Some(expected) = expected_generation
                && inner
                    .sources
                    .get(&key)
                    .is_none_or(|source| source.generation != expected)
            {
                return;
            }
            let source = inner.sources.entry(key).or_insert_with(|| SourceCache {
                metadata: metadata.clone(),
                state: SourceCacheState::Empty,
                updated_at_ms: 0,
                generation: 0,
            });
            source.generation += 1;
            source.metadata = metadata;
            source.updated_at_ms = current_unix_millis();
            source.state = match result {
                Ok(result) => SourceCacheState::Loaded {
                    sessions: result.sessions,
                    diagnostics: result.diagnostics,
                },
                Err(message) => SourceCacheState::Failed {
                    retry_at: std::time::Instant::now() + std::time::Duration::from_secs(5),
                    message,
                    // A late discovery error does not invalidate already published
                    // display metadata. Mutations fence and clear it separately.
                    sessions: source.sessions().to_vec(),
                    diagnostics: SourceDiagnostics::default(),
                },
            };
            self.bump_revision(&mut inner);
            drop(inner);
        }
    }

    fn bump_revision(&self, inner: &mut SessionCatalogInner) {
        inner.revision = inner.revision.saturating_add(1);
        self.revision_tx.send_replace(inner.revision);
        self.notify.notify_waiters();
    }
}

// Retry pages replace matching retained rows; successful completion replaces the
// entire source, so rows absent from the final discovery do not survive forever.
fn merge_catalog_page(sessions: &mut Vec<SessionSummary>, page: Vec<SessionSummary>) {
    let incoming_ids = page
        .iter()
        .map(|summary| summary.id)
        .collect::<BTreeSet<_>>();
    sessions.retain(|summary| !incoming_ids.contains(&summary.id));
    sessions.extend(page);
}

#[derive(Debug, Clone)]
struct SourceLoadResult {
    sessions: Vec<SessionSummary>,
    diagnostics: SourceDiagnostics,
}

impl CatalogSourcePlan {
    fn key(&self) -> CatalogSourceKey {
        match self {
            Self::InMemory => native_source_key(),
            Self::Native { location } => CatalogSourceKey {
                source_id: location.source_id(),
                scope: CatalogSourceScope::Global,
            },
            Self::Import {
                source_id,
                working_directory,
                ..
            } => CatalogSourceKey {
                source_id: source_id.clone(),
                scope: CatalogSourceScope::WorkingDirectory(normalize_path(working_directory)),
            },
        }
    }

    fn metadata(&self) -> SourceMetadata {
        match self {
            Self::InMemory => native_metadata(),
            Self::Native { location } => SourceMetadata {
                display_name: location.display_name(),
            },
            Self::Import { source_id, .. } => SourceMetadata {
                display_name: format!("Imported [{source_id}] sessions"),
            },
        }
    }
}

fn catalog_source_metric_labels(key: &CatalogSourceKey) -> bcode_metrics::MetricLabels {
    let mut labels = bcode_metrics::MetricLabels::new();
    labels.insert("source_id".to_owned(), key.source_id.clone());
    labels.insert(
        "scope".to_owned(),
        match &key.scope {
            CatalogSourceScope::Global => "global".to_owned(),
            CatalogSourceScope::WorkingDirectory(_) => "working_directory".to_owned(),
        },
    );
    labels
}

fn native_source_key() -> CatalogSourceKey {
    CatalogSourceKey {
        source_id: NATIVE_SOURCE_ID.to_owned(),
        scope: CatalogSourceScope::Global,
    }
}

fn native_metadata() -> SourceMetadata {
    SourceMetadata {
        display_name: NATIVE_DISPLAY_NAME.to_owned(),
    }
}

/// Resolve the state locations that participate in aggregated native discovery.
///
/// The primary location always participates. Additional readable locations come from
/// `[state] readable_profiles`. Resolution failures are skipped rather than propagated: a
/// location that cannot be resolved must not prevent the rest of the catalog from loading
/// (`Domain-local durable failures remain isolated`).
fn native_locations(state: &ServerState) -> Vec<NativeLocation> {
    let Some(primary_sessions_root) = state.sessions.session_store_root() else {
        return Vec::new();
    };
    let Some(primary_id) = state.daemon_status.state_location_id.clone() else {
        return Vec::new();
    };
    let mut locations = vec![NativeLocation {
        location_id: primary_id.clone(),
        profile: None,
        sessions_root: primary_sessions_root,
        primary: true,
    }];

    let resolved = if let Some(locations) = &state.locations {
        locations.clone()
    } else {
        let Ok(config) = bcode_config::load_config() else {
            return locations;
        };
        if config.state.readable_profiles.is_empty() {
            return locations;
        }
        let Ok(resolved) = bcode_config::resolve_state_location_set(
            &config.state,
            &bcode_config::StateLocationSelection::default(),
        ) else {
            return locations;
        };
        resolved
    };
    for location in resolved.readable() {
        let location_id = location.id().as_str().to_owned();
        if location_id == primary_id
            || locations
                .iter()
                .any(|existing| existing.location_id == location_id)
        {
            continue;
        }
        locations.push(NativeLocation {
            location_id,
            profile: location.profile().map(str::to_owned),
            sessions_root: location.sessions_root().to_path_buf(),
            primary: false,
        });
    }
    locations
}

/// Exact, non-discovering canonical-directory claims across the configured readable roots.
/// Unavailable roots fail closed: they are not evidence of an absent claim.
pub(crate) fn exact_location_claims(state: &ServerState, id: SessionId) -> Result<Vec<String>, ()> {
    let mut claims = Vec::new();
    for location in native_locations(state) {
        std::fs::metadata(&location.sessions_root).map_err(|_| ())?;
        match std::fs::symlink_metadata(location.sessions_root.join(id.to_string())) {
            Ok(_) => claims.push(location.location_id),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(_) => return Err(()),
        }
    }
    Ok(claims)
}

async fn load_in_memory_source(state: &ServerState) -> Result<SourceLoadResult, String> {
    let entries = state.sessions.all_session_catalog_entries().await;
    Ok(SourceLoadResult {
        diagnostics: native_source_diagnostics(&entries),
        sessions: entries
            .into_iter()
            .map(|entry| {
                let mut summary = entry.summary;
                summary.location = None;
                summary
            })
            .collect(),
    })
}

fn native_source_plans(state: &ServerState) -> Vec<CatalogSourcePlan> {
    let mut plans = native_locations(state)
        .into_iter()
        .map(|location| CatalogSourcePlan::Native { location })
        .collect::<Vec<_>>();
    if state.sessions.session_store_root().is_none() {
        plans.push(CatalogSourcePlan::InMemory);
    }
    plans
}

async fn source_plans(state: &ServerState, working_directory: &Path) -> Vec<CatalogSourcePlan> {
    let mut plans = Vec::new();
    let imports_enabled = if state.locations.is_some() {
        state.startup_config.session_import.enabled
    } else {
        bcode_config::load_config().map_or(true, |config| config.session_import.enabled)
    };
    if !imports_enabled {
        return plans;
    }
    let providers = state
        .plugins
        .registry()
        .service_registry()
        .providers_for(bcode_session_import::SESSION_IMPORT_INTERFACE_ID)
        .cloned()
        .unwrap_or_default();
    for plugin_id in providers {
        for source_id in state
            .session_catalog
            .import_source_ids(&plugin_id, Box::pin(import_source_ids(state, &plugin_id)))
            .await
        {
            plans.push(CatalogSourcePlan::Import {
                plugin_id: plugin_id.clone(),
                source_id,
                working_directory: working_directory.to_path_buf(),
            });
        }
    }
    plans
}

async fn load_source(
    state: &ServerState,
    plan: &CatalogSourcePlan,
) -> Result<SourceLoadResult, String> {
    #[cfg(test)]
    {
        let gate = state.session_catalog.discovery_gate.lock().await.clone();
        if let Some(gate) = gate {
            // Release opens discovery for subsequent generations too. Backfill or a
            // concurrent mutation can invalidate the first load without consuming
            // the test's only release and stranding its replacement.
            drop(gate.acquire().await.expect("discovery gate open"));
        }
    }
    match plan {
        CatalogSourcePlan::InMemory => load_in_memory_source(state).await,
        CatalogSourcePlan::Native { location } => {
            if location.primary {
                load_native_source(state, location).await
            } else {
                load_foreign_native_source(location).await
            }
        }
        CatalogSourcePlan::Import {
            plugin_id,
            source_id,
            working_directory,
        } => discover_import_source(state, plugin_id, source_id, working_directory).await,
    }
}

/// Discover sessions in a state location this daemon does not own.
///
/// Bounded and non-mutating by construction: it reads derived manifests plus canonical
/// directory presence through `SessionStore::discover_readable_session_summaries`, so it
/// opens no canonical database and takes no lease. An unavailable root (for example an
/// unmounted volume) yields a degraded source rather than failing the whole catalog.
async fn load_foreign_native_source(location: &NativeLocation) -> Result<SourceLoadResult, String> {
    let sessions_root = location.sessions_root.clone();
    let location_summary = location.summary();
    tokio::task::spawn_blocking(move || {
        let store = bcode_session::SessionStore::new(&sessions_root);
        let sessions = store
            .discover_readable_session_summaries()
            .map_err(|error| error.to_string())?;
        Ok(SourceLoadResult {
            sessions: sessions
                .into_iter()
                .map(|mut summary| {
                    summary.location = Some(location_summary.clone());
                    summary
                })
                .collect(),
            diagnostics: SourceDiagnostics::default(),
        })
    })
    .await
    .map_err(|error| format!("foreign session discovery task failed: {error}"))?
}

async fn load_native_source(
    state: &ServerState,
    location: &NativeLocation,
) -> Result<SourceLoadResult, String> {
    state
        .sessions
        .wait_catalog_loaded()
        .await
        .map_err(|error| error.to_string())?;
    let entries = state.sessions.all_session_catalog_entries().await;
    let diagnostics = native_source_diagnostics(&entries);
    let location_summary = location.summary();
    Ok(SourceLoadResult {
        sessions: entries
            .into_iter()
            .map(|entry| {
                let mut summary = entry.summary;
                summary.location = Some(location_summary.clone());
                summary
            })
            .collect(),
        diagnostics,
    })
}

fn import_source_result(sessions: Vec<SessionSummary>) -> SourceLoadResult {
    SourceLoadResult {
        sessions,
        diagnostics: SourceDiagnostics::default(),
    }
}

fn native_source_diagnostics(_entries: &[SessionCatalogEntry]) -> SourceDiagnostics {
    SourceDiagnostics::default()
}

fn snapshot_locked(
    inner: &SessionCatalogInner,
    working_directory: &Path,
    hide_imported: bool,
) -> SessionCatalogSnapshot {
    let native_sessions = inner
        .sources
        .get(&native_source_key())
        .map_or(&[][..], SourceCache::sessions);
    let native_imports = native_import_identities(native_sessions);
    let mut sessions = Vec::new();
    let mut sources = Vec::new();
    // Resolve each distinct directory once per snapshot, not once per session.
    // Keep this cache local so symlink changes are observed on subsequent reads.
    let mut normalized_directories = BTreeMap::new();

    for (key, source) in &inner.sources {
        if !source_relevant_to_working_directory(key, working_directory) {
            continue;
        }
        sources.push(source_status(key, source));
        match &key.scope {
            // Native/global sources are filtered to the caller's working directory. Foreign
            // readable locations are discovered from derived manifests, where a session
            // without manifest metadata falls back to the store root as its working
            // directory, so those entries cannot be working-directory filtered without
            // hiding them entirely. Retain foreign sessions that carry no usable working
            // directory, and filter the ones that do.
            CatalogSourceScope::Global => sessions.extend(
                source
                    .sessions()
                    .iter()
                    .filter(|session| {
                        let is_foreign = session
                            .location
                            .as_ref()
                            .is_some_and(|location| !location.primary);
                        if is_foreign && session.updated_at_ms == 0 {
                            return true;
                        }
                        normalized_directories
                            .entry(session.working_directory.clone())
                            .or_insert_with(|| normalize_path(&session.working_directory))
                            .as_path()
                            == working_directory
                    })
                    .cloned(),
            ),
            CatalogSourceScope::WorkingDirectory(_) => sessions.extend(
                source
                    .sessions()
                    .iter()
                    .filter(|session| {
                        session.import.as_ref().is_none_or(|import| {
                            !hide_imported
                                || !native_imports.contains(&(
                                    import.source_id.clone(),
                                    import.external_session_id.clone(),
                                ))
                        })
                    })
                    .cloned(),
            ),
        }
    }

    sort_sessions(&mut sessions);
    mark_ambiguous_locations(&mut sessions);
    SessionCatalogSnapshot {
        status: if inner
            .import_plans
            .get(working_directory)
            .is_some_and(|plans| {
                plans.as_ref().is_none_or(|plans| {
                    plans
                        .iter()
                        .any(|plan| !inner.sources.contains_key(&plan.key()))
                })
            }) {
            SessionCatalogStatus::Loading
        } else if inner.retry_import_plans.contains_key(working_directory) {
            SessionCatalogStatus::Degraded(
                "Some import sources could not be enumerated; discovery will retry.".to_owned(),
            )
        } else {
            aggregate_status(sources.iter().map(|source| &source.status))
        },
        sessions,
        sources,
        revision: inner.revision,
    }
}

/// Flag sessions whose ID is claimed by more than one readable state location.
///
/// Duplicate canonical roots are never merged automatically. Every claim is retained and
/// marked ambiguous so the conflict is visible; callers must refuse to open an ambiguous
/// session as authoritative until an explicit maintenance operation resolves it
/// (`Canonical history is never silently merged`, `Sensitive ambiguity fails closed`).
fn mark_ambiguous_locations(sessions: &mut [SessionSummary]) {
    let mut claims: BTreeMap<SessionId, BTreeSet<String>> = BTreeMap::new();
    for session in sessions.iter() {
        if let Some(location) = &session.location {
            claims
                .entry(session.id)
                .or_default()
                .insert(location.location_id.clone());
        }
    }
    for session in sessions.iter_mut() {
        let ambiguous = claims
            .get(&session.id)
            .is_some_and(|locations| locations.len() > 1);
        if ambiguous && let Some(location) = session.location.as_mut() {
            location.ambiguous = true;
        }
    }
}

impl SourceCache {
    fn status(&self) -> SessionCatalogStatus {
        match &self.state {
            SourceCacheState::Empty => SessionCatalogStatus::NotStarted,
            SourceCacheState::Loading { .. } => SessionCatalogStatus::Loading,
            SourceCacheState::Loaded { .. } => {
                let status = diagnostic_status(&self.metadata.display_name, self.diagnostics());
                status.unwrap_or(SessionCatalogStatus::Loaded)
            }
            SourceCacheState::Failed { message, .. } => {
                SessionCatalogStatus::Failed(message.clone())
            }
        }
    }

    fn sessions(&self) -> &[SessionSummary] {
        match &self.state {
            SourceCacheState::Loaded { sessions, .. }
            | SourceCacheState::Loading { sessions }
            | SourceCacheState::Failed { sessions, .. } => sessions,
            SourceCacheState::Empty => &[],
        }
    }

    fn diagnostics(&self) -> &SourceDiagnostics {
        static EMPTY: SourceDiagnostics = SourceDiagnostics {};
        match &self.state {
            SourceCacheState::Loaded { diagnostics, .. }
            | SourceCacheState::Failed { diagnostics, .. } => diagnostics,
            SourceCacheState::Empty | SourceCacheState::Loading { .. } => &EMPTY,
        }
    }
}

const fn diagnostic_status(
    _display_name: &str,
    _diagnostics: &SourceDiagnostics,
) -> Option<SessionCatalogStatus> {
    None
}

fn source_relevant_to_working_directory(key: &CatalogSourceKey, working_directory: &Path) -> bool {
    match &key.scope {
        CatalogSourceScope::Global => true,
        CatalogSourceScope::WorkingDirectory(path) => path == working_directory,
    }
}

fn native_import_identities(sessions: &[SessionSummary]) -> BTreeSet<(String, String)> {
    sessions
        .iter()
        .filter_map(|session| {
            session.import.as_ref().and_then(|import| {
                (import.imported_at_ms != 0)
                    .then(|| (import.source_id.clone(), import.external_session_id.clone()))
            })
        })
        .collect()
}

fn source_status(key: &CatalogSourceKey, source: &SourceCache) -> SessionCatalogSourceStatus {
    SessionCatalogSourceStatus {
        source_id: key.source_id.clone(),
        display_name: source.metadata.display_name.clone(),
        status: source.status(),
        updated_at_ms: source.updated_at_ms,
    }
}

fn aggregate_status<'a>(
    statuses: impl IntoIterator<Item = &'a SessionCatalogStatus>,
) -> SessionCatalogStatus {
    let mut has_loading = false;
    let mut failures = Vec::new();
    let mut saw_status = false;
    for status in statuses {
        saw_status = true;
        match status {
            SessionCatalogStatus::NotStarted | SessionCatalogStatus::Loading => has_loading = true,
            SessionCatalogStatus::Failed(message) | SessionCatalogStatus::Degraded(message) => {
                failures.push(message.clone());
            }
            SessionCatalogStatus::Loaded => {}
        }
    }
    if has_loading || !saw_status {
        SessionCatalogStatus::Loading
    } else if failures.is_empty() {
        SessionCatalogStatus::Loaded
    } else {
        SessionCatalogStatus::Failed(failures.join("; "))
    }
}

async fn import_source_ids(state: &ServerState, plugin_id: &str) -> Result<Vec<String>, String> {
    state
        .plugins
        .invoke_service_json::<_, bcode_session_import::ListImportSourcesResponse>(
            plugin_id,
            bcode_session_import::SESSION_IMPORT_INTERFACE_ID,
            bcode_session_import::OP_LIST_IMPORT_SOURCES,
            &serde_json::json!({}),
        )
        .await
        .map(|response| {
            response
                .sources
                .into_iter()
                .map(|source| source.source_id)
                .collect()
        })
        .map_err(|error| error.to_string())
}

async fn discover_import_source(
    state: &ServerState,
    plugin_id: &str,
    source_id: &str,
    working_directory: &Path,
) -> Result<SourceLoadResult, String> {
    let response = state
        .plugins
        .invoke_service_json::<_, bcode_session_import::DiscoverImportableSessionsResponse>(
            plugin_id,
            bcode_session_import::SESSION_IMPORT_INTERFACE_ID,
            bcode_session_import::OP_DISCOVER_IMPORTABLE_SESSIONS,
            &bcode_session_import::DiscoverImportableSessionsRequest {
                source_id: None,
                working_directory: Some(working_directory.to_path_buf()),
                include_diagnostics: false,
            },
        )
        .await
        .map_err(|error| error.to_string())?;
    let sessions = response
        .sessions
        .into_iter()
        .filter(|summary| {
            summary.status == ImportableSessionStatus::Available && summary.source_id == source_id
        })
        .map(importable_to_summary)
        .collect();
    Ok(import_source_result(sessions))
}

fn importable_to_summary(
    summary: bcode_session_import::ImportableSessionSummary,
) -> SessionSummary {
    let id = crate::session_import::external_session_id(
        &summary.source_id,
        &summary.external_session_id,
    );
    let name = Some(
        summary
            .title
            .clone()
            .filter(|title| !title.trim().is_empty())
            .unwrap_or_else(|| summary.external_session_id.clone()),
    );
    SessionSummary {
        automatic_title: None,
        automatic_title_source_sequence: None,
        parent_id: None,
        id,
        name: name.clone(),
        explicit_name: name,
        derived_title: None,
        title_source: SessionTitleSource::Imported,
        client_count: 0,
        created_at_ms: summary.created_at_ms.unwrap_or(0),
        updated_at_ms: summary.updated_at_ms.or(summary.created_at_ms).unwrap_or(0),
        working_directory: summary.working_directory.unwrap_or_default(),
        import: Some(SessionImportSummary {
            source_id: summary.source_id,
            source_display_name: summary.source_display_name,
            external_session_id: summary.external_session_id,
            imported_at_ms: 0,
        }),
        execution: None,
        // Importable external sessions are not owned by a Bcode state location until they
        // are imported, so they carry no owning-location label.
        location: None,
    }
}

fn upsert_session(sessions: &mut Vec<SessionSummary>, session: SessionSummary) -> bool {
    if let Some(existing) = sessions
        .iter_mut()
        .find(|existing| existing.id == session.id)
    {
        if *existing == session {
            false
        } else {
            *existing = session;
            true
        }
    } else {
        sessions.push(session);
        true
    }
}

fn sort_sessions(sessions: &mut [SessionSummary]) {
    sessions.sort_by(|left, right| {
        right
            .updated_at_ms
            .cmp(&left.updated_at_ms)
            .then_with(|| right.created_at_ms.cmp(&left.created_at_ms))
            .then_with(|| left.id.cmp(&right.id))
    });
}

async fn notify_planning_retry(
    state: &std::sync::Weak<ServerState>,
    working_directory: PathBuf,
    generation: u64,
    deadline: std::time::Instant,
) {
    tokio::time::sleep_until(deadline.into()).await;
    if let Some(state) = state.upgrade() {
        let catalog = &state.session_catalog;
        let mut inner = catalog.inner.lock().await;
        if inner.planning_generation == generation
            && inner.retry_import_plans.get(&working_directory) == Some(&deadline)
        {
            // Observers perform the retry through normal source planning. No provider
            // work is started here when the catalog has no active observers.
            catalog.bump_revision(&mut inner);
        }
    }
}

fn catalog_summary_matches(
    session: &SessionSummary,
    scope: &bcode_session_models::SessionDiscoveryScope,
    text: Option<&str>,
) -> bool {
    session.is_picker_visible()
        && match scope {
            bcode_session_models::SessionDiscoveryScope::AllWorkingDirectories => true,
            bcode_session_models::SessionDiscoveryScope::WorkingDirectory(path) => {
                normalize_path(&session.working_directory) == normalize_path(path)
            }
        }
        && text.is_none_or(|text| {
            session.id.to_string().contains(text)
                || session
                    .title()
                    .is_some_and(|name| name.to_lowercase().contains(text))
                || session
                    .working_directory
                    .to_string_lossy()
                    .to_lowercase()
                    .contains(text)
        })
}

fn validate_catalog_selection(
    scope: &bcode_session_models::SessionDiscoveryScope,
    query: &bcode_session_models::SessionCatalogQuery,
    limit: usize,
) -> Result<(), String> {
    if !(1..=256).contains(&limit) || query.text.as_ref().is_some_and(|text| text.len() > 4096) {
        return Err("catalog page limit must be 1..=256 and query at most 4096 bytes".into());
    }
    if let bcode_session_models::SessionDiscoveryScope::WorkingDirectory(path) = scope
        && !path.is_absolute()
    {
        return Err("catalog working directory must be absolute".into());
    }
    Ok(())
}

fn normalize_path(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

fn current_unix_millis() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |duration| {
            u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
        })
}

#[cfg(test)]
mod tests {
    #[tokio::test]
    async fn activity_pages_survive_catalog_revision_updates() {
        use bcode_session_models::{SessionCatalogQuery, SessionDiscoveryScope};
        let manager = bcode_session::SessionManager::default();
        for _ in 0..3 {
            manager
                .create_session(None, "/project".into())
                .await
                .unwrap();
        }
        let state = std::sync::Arc::new(crate::tests::test_server_state(manager));
        let catalog = &state.session_catalog;
        let first = catalog
            .page_with_scope(
                &state,
                SessionDiscoveryScope::AllWorkingDirectories,
                SessionCatalogQuery::default(),
                None,
                1,
            )
            .await
            .unwrap();
        let updater = {
            let state = state.clone();
            tokio::spawn(async move {
                for _ in 0..8 {
                    let mut inner = state.session_catalog.inner.lock().await;
                    state.session_catalog.bump_revision(&mut inner);
                    drop(inner);
                    tokio::task::yield_now().await;
                }
            })
        };
        let next = catalog
            .page_with_scope(
                &state,
                SessionDiscoveryScope::AllWorkingDirectories,
                SessionCatalogQuery::default(),
                first.next_cursor,
                1,
            )
            .await
            .unwrap();
        updater.await.unwrap();
        assert_ne!(first.sessions[0].id, next.sessions[0].id);
        assert!(catalog.revision() > first.catalog_revision);
        let last = catalog
            .page_with_scope(
                &state,
                SessionDiscoveryScope::AllWorkingDirectories,
                SessionCatalogQuery::default(),
                next.next_cursor,
                1,
            )
            .await
            .unwrap();
        assert_ne!(next.sessions[0].id, last.sessions[0].id);
        drop(state);
    }

    #[tokio::test]
    async fn global_activity_pages_merge_readable_locations() {
        use bcode_session_models::{SessionCatalogQuery, SessionDiscoveryScope};
        let primary = tempfile::tempdir().unwrap();
        let foreign = tempfile::tempdir().unwrap();
        let mut expected = Vec::new();
        for (root, activity) in [
            (primary.path(), 10),
            (foreign.path(), 40),
            (primary.path(), 30),
            (foreign.path(), 20),
        ] {
            let manager = bcode_session::SessionManager::persistent(root).unwrap();
            let mut session = manager
                .create_session(None, root.to_path_buf())
                .await
                .unwrap();
            drop(manager);
            session.updated_at_ms = 4_000_000_000_000 + activity;
            session.created_at_ms = 1;
            let manifest_path = root.join(session.id.to_string()).join("manifest.json");
            let mut manifest: serde_json::Value =
                serde_json::from_slice(&std::fs::read(&manifest_path).unwrap()).unwrap();
            manifest["summary"] = serde_json::to_value(&session).unwrap();
            std::fs::write(&manifest_path, serde_json::to_vec(&manifest).unwrap()).unwrap();
            let catalog = bcode_session::db::GlobalSessionDb::open_turso_in_root(root)
                .await
                .unwrap();
            catalog
                .upsert_sessions(root, std::slice::from_ref(&session))
                .await
                .unwrap();
            catalog.close().await.unwrap();
            expected.push(session);
        }
        expected.sort_by_key(|s| {
            (
                std::cmp::Reverse(s.updated_at_ms),
                std::cmp::Reverse(s.created_at_ms),
                s.id,
            )
        });
        let config = bcode_config::StateConfig {
            root: Some(primary.path().to_path_buf()),
            sessions_root: Some(primary.path().to_path_buf()),
            profile: std::collections::BTreeMap::from([(
                "foreign".into(),
                bcode_config::StateProfileConfig {
                    root: Some(foreign.path().to_path_buf()),
                    sessions_root: Some(foreign.path().to_path_buf()),
                },
            )]),
            readable_profiles: vec!["foreign".into()],
            ..Default::default()
        };
        let state = std::sync::Arc::new({
            let mut raw = crate::tests::test_server_state(
                bcode_session::SessionManager::persistent_lazy(primary.path()),
            );
            raw.locations = Some(
                bcode_config::resolve_state_location_set(
                    &config,
                    &bcode_config::StateLocationSelection::default(),
                )
                .unwrap(),
            );
            raw.daemon_status.state_location_id = raw
                .locations
                .as_ref()
                .map(|locations| locations.primary().id().as_str().to_owned());
            raw
        });
        let mut cursor = None;
        let mut found = Vec::new();
        loop {
            let page = state
                .session_catalog
                .page_with_scope(
                    &state,
                    SessionDiscoveryScope::AllWorkingDirectories,
                    SessionCatalogQuery::default(),
                    cursor,
                    2,
                )
                .await
                .unwrap();
            assert!(page.sessions.len() <= 2);
            found.extend(page.sessions.into_iter().map(|summary| summary.id));
            cursor = page.next_cursor;
            if cursor.is_none() {
                break;
            }
        }
        assert_eq!(
            found,
            expected
                .iter()
                .map(|summary| summary.id)
                .collect::<Vec<_>>()
        );
        drop(state);
    }

    #[tokio::test]
    async fn native_pages_continue_empty_filters_and_reject_changed_selection() {
        use bcode_session_models::{SessionCatalogQuery, SessionDiscoveryScope};
        let manager = bcode_session::SessionManager::default();
        let first = manager
            .create_session(None, std::path::PathBuf::from("/project-b"))
            .await
            .unwrap();
        let second = manager
            .create_session(None, std::path::PathBuf::from("/project-b"))
            .await
            .unwrap();
        let state = std::sync::Arc::new(crate::tests::test_server_state(manager));
        let scope = SessionDiscoveryScope::AllWorkingDirectories;
        let query = SessionCatalogQuery {
            text: Some("not-a-session-title".into()),
        };
        let page = state
            .session_catalog
            .page_with_scope(&state, scope.clone(), query.clone(), None, 1)
            .await
            .unwrap();
        assert!(page.sessions.is_empty());
        let cursor = page.next_cursor.unwrap();
        assert!(
            state
                .session_catalog
                .page_with_scope(
                    &state,
                    scope.clone(),
                    SessionCatalogQuery::default(),
                    Some(cursor.clone()),
                    1
                )
                .await
                .is_err()
        );
        assert!(
            state
                .session_catalog
                .page_with_scope(
                    &state,
                    SessionDiscoveryScope::WorkingDirectory("/project-b".into()),
                    query.clone(),
                    Some(cursor.clone()),
                    1
                )
                .await
                .is_err()
        );
        let next = state
            .session_catalog
            .page_with_scope(&state, scope.clone(), query, Some(cursor), 1)
            .await
            .unwrap();
        assert!(next.sessions.is_empty());
        let one = state
            .session_catalog
            .page_with_scope(
                &state,
                scope.clone(),
                SessionCatalogQuery::default(),
                None,
                1,
            )
            .await
            .unwrap();
        let two = state
            .session_catalog
            .page_with_scope(
                &state,
                scope,
                SessionCatalogQuery::default(),
                one.next_cursor,
                1,
            )
            .await
            .unwrap();
        let mut ids = vec![one.sessions[0].id, two.sessions[0].id];
        ids.sort();
        let mut expected = vec![first.id, second.id];
        expected.sort();
        assert_eq!(ids, expected);
        assert!(
            two.sessions
                .iter()
                .all(|session| session.working_directory == std::path::Path::new("/project-b"))
        );
        drop(state);
    }

    #[tokio::test]
    async fn global_discovery_attach_preserves_cwd_and_history() {
        use bcode_session_models::{SessionCatalogQuery, SessionDiscoveryScope};
        let manager = bcode_session::SessionManager::default();
        let first = manager
            .create_session(None, "/project-b".into())
            .await
            .unwrap();
        let missing_root = tempfile::tempdir().unwrap();
        let missing_cwd = missing_root.path().join("unavailable-project-b");
        let missing = manager
            .create_session(None, missing_cwd.clone())
            .await
            .unwrap();
        let missing_attachment = manager
            .attach_session(missing.id, bcode_session_models::ClientId::new())
            .await
            .unwrap();
        assert_eq!(missing_attachment.session.working_directory, missing_cwd);
        assert!(!missing_attachment.session.working_directory.exists());
        drop(missing_attachment);
        drop(missing_root);
        let state = std::sync::Arc::new(crate::tests::test_server_state(manager));
        let before = state.sessions.session_history(first.id).await.unwrap();
        let attached = state
            .sessions
            .attach_session(first.id, bcode_session_models::ClientId::new())
            .await
            .unwrap();
        assert_eq!(
            attached.session.working_directory,
            std::path::Path::new("/project-b")
        );
        assert_eq!(
            state.sessions.session_history(first.id).await.unwrap(),
            before
        );
        assert!(
            state
                .session_catalog
                .page_with_scope(
                    &state,
                    SessionDiscoveryScope::AllWorkingDirectories,
                    SessionCatalogQuery {
                        text: Some(first.id.to_string())
                    },
                    None,
                    256
                )
                .await
                .unwrap()
                .sessions
                .iter()
                .any(|summary| summary.id == first.id)
        );
        drop(attached);
        drop(state);
    }

    #[tokio::test]
    async fn direct_page_claim_checks_reject_duplicate_and_unavailable_locations() {
        let primary = tempfile::tempdir().unwrap();
        let foreign = tempfile::tempdir().unwrap();
        let config = bcode_config::StateConfig {
            root: Some(primary.path().to_path_buf()),
            sessions_root: Some(primary.path().to_path_buf()),
            profile: std::collections::BTreeMap::from([(
                "foreign".into(),
                bcode_config::StateProfileConfig {
                    root: Some(foreign.path().to_path_buf()),
                    sessions_root: Some(foreign.path().to_path_buf()),
                },
            )]),
            readable_profiles: vec!["foreign".into()],
            ..Default::default()
        };
        let state = crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(primary.path()),
        );
        let resolved = bcode_config::resolve_state_location_set(
            &config,
            &bcode_config::StateLocationSelection::default(),
        )
        .unwrap();
        let state = std::sync::Arc::new({
            let mut state = state;
            state.daemon_status.state_location_id =
                Some(resolved.primary().id().as_str().to_owned());
            state.locations = Some(resolved);
            state
        });
        let id = SessionId::new();
        std::fs::create_dir(primary.path().join(id.to_string())).unwrap();
        std::fs::create_dir(foreign.path().join(id.to_string())).unwrap();
        let page = state
            .session_catalog
            .page_with_scope(
                &state,
                bcode_session_models::SessionDiscoveryScope::AllWorkingDirectories,
                bcode_session_models::SessionCatalogQuery::default(),
                None,
                1,
            )
            .await
            .unwrap();
        assert!(matches!(
            page.catalog_status,
            bcode_session_models::SessionCatalogStatus::Degraded(_)
        ));
        assert!(
            state
                .session_catalog
                .ambiguous_location_ids(id)
                .await
                .is_empty()
        );
        assert_eq!(super::exact_location_claims(&state, id).unwrap().len(), 2);
        assert!(
            matches!(crate::ambiguous_session_location_response(&state, id).await, Some(bcode_ipc::Response::Err(error)) if error.code == "session_location_ambiguous")
        );
        std::fs::remove_dir(foreign.path().join(id.to_string())).unwrap();
        assert!(super::exact_location_claims(&state, id).is_ok());
        drop(foreign);
        assert!(
            matches!(crate::ambiguous_session_location_response(&state, id).await, Some(bcode_ipc::Response::Err(error)) if error.code == "session_location_unverifiable")
        );
        drop(state);
    }

    #[test]
    fn retry_pages_replace_matching_rows_without_losing_other_results() {
        let first = summary(SessionId::new(), None);
        let second = summary(SessionId::new(), None);
        let mut updated = first.clone();
        updated.name = Some("updated".to_owned());
        let mut sessions = vec![first, second.clone()];
        super::merge_catalog_page(&mut sessions, vec![updated.clone()]);
        assert_eq!(sessions, vec![second.clone(), updated.clone()]);
        super::merge_catalog_page(&mut sessions, vec![updated.clone()]);
        assert_eq!(sessions, vec![second, updated]);
    }

    #[tokio::test]
    async fn failed_source_is_observable_and_explicit_refresh_bypasses_backoff() {
        let root = tempfile::tempdir().unwrap();
        let state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        ));
        let catalog = &state.session_catalog;
        let session = summary(SessionId::new(), None);
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Err("unavailable".to_owned()),
            )
            .await;
        let revision = catalog.revision();
        catalog
            .ensure_source(&state, super::CatalogSourcePlan::InMemory)
            .await;
        assert_eq!(catalog.revision(), revision);
        let snapshot = {
            let inner = catalog.inner.lock().await;
            super::snapshot_locked(&inner, root.path(), true)
        };
        assert!(matches!(
            snapshot.status,
            bcode_session_models::SessionCatalogStatus::Failed(_)
        ));
        // Display timestamps cannot delay a retry after its monotonic deadline.
        {
            let mut inner = catalog.inner.lock().await;
            let source = inner.sources.get_mut(&super::native_source_key()).unwrap();
            source.updated_at_ms = u64::MAX;
            let super::SourceCacheState::Failed { retry_at, .. } = &mut source.state else {
                panic!("failure must remain visible during backoff");
            };
            *retry_at = std::time::Instant::now();
            drop(inner);
        }
        catalog
            .ensure_source(&state, super::CatalogSourcePlan::InMemory)
            .await;
        let inner = catalog.inner.lock().await;
        assert_eq!(
            inner.sources[&super::native_source_key()].sessions(),
            &[session]
        );
        assert!(matches!(
            inner.sources[&super::native_source_key()].state,
            super::SourceCacheState::Loading { .. }
        ));
        drop(inner);
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Err("still unavailable".to_owned()),
            )
            .await;
        catalog.invalidate_native().await;
        catalog
            .ensure_source(&state, super::CatalogSourcePlan::InMemory)
            .await;
        let inner = catalog.inner.lock().await;
        let source = inner.sources[&super::native_source_key()].clone();
        drop(inner);
        assert!(matches!(
            source.state,
            super::SourceCacheState::Loading { .. }
        ));
        drop(state);
    }

    #[tokio::test]
    async fn loading_snapshot_retains_partial_results_and_mutations_invalidate_them() {
        let catalog = SessionCatalog::default();
        let session = summary(SessionId::new(), None);
        let directory = super::normalize_path(&session.working_directory);
        {
            let mut inner = catalog.inner.lock().await;
            inner.sources.insert(
                super::native_source_key(),
                super::SourceCache {
                    metadata: super::native_metadata(),
                    state: super::SourceCacheState::Loading {
                        sessions: vec![session.clone()],
                    },
                    generation: 1,
                    updated_at_ms: 1,
                },
            );
            let snapshot = super::snapshot_locked(&inner, &directory, true);
            drop(inner);
            assert_eq!(snapshot.sessions, vec![session.clone()]);
            assert!(matches!(
                snapshot.status,
                bcode_session_models::SessionCatalogStatus::Loading
            ));
        }
        catalog
            .publish_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Err("discovery unavailable".to_owned()),
                Some(1),
            )
            .await;
        {
            let inner = catalog.inner.lock().await;
            let snapshot = super::snapshot_locked(&inner, &directory, true);
            drop(inner);
            assert_eq!(snapshot.sessions, vec![session.clone()]);
            assert!(!matches!(
                snapshot.status,
                bcode_session_models::SessionCatalogStatus::Loaded
                    | bcode_session_models::SessionCatalogStatus::Loading
            ));
        }
        catalog.remove_native_session(session.id).await;
        let inner = catalog.inner.lock().await;
        let source = inner.sources[&super::native_source_key()].clone();
        drop(inner);
        assert_eq!(source.generation, 3);
        assert!(source.sessions().is_empty());
        assert!(matches!(
            source.state,
            super::SourceCacheState::Failed { .. }
        ));
        catalog
            .publish_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session],
                    diagnostics: SourceDiagnostics::default(),
                }),
                Some(1),
            )
            .await;
        let inner = catalog.inner.lock().await;
        assert!(
            inner.sources[&super::native_source_key()]
                .sessions()
                .is_empty()
        );
        drop(inner);
    }

    #[tokio::test]
    async fn failed_planning_is_degraded_without_hiding_native_results() {
        let catalog = SessionCatalog::default();
        let session = summary(SessionId::new(), None);
        let directory = super::normalize_path(&session.working_directory);
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        let mut inner = catalog.inner.lock().await;
        inner
            .import_plans
            .insert(directory.clone(), Some(Vec::new()));
        inner
            .retry_import_plans
            .insert(directory.clone(), std::time::Instant::now());
        let snapshot = super::snapshot_locked(&inner, &directory, true);
        assert!(matches!(
            snapshot.status,
            bcode_session_models::SessionCatalogStatus::Degraded(_)
        ));
        assert_eq!(snapshot.sessions, vec![session.clone()]);
        inner.import_plans.insert(directory.clone(), None);
        assert!(matches!(
            super::snapshot_locked(&inner, &directory, true).status,
            bcode_session_models::SessionCatalogStatus::Loading
        ));
        inner
            .import_plans
            .insert(directory.clone(), Some(Vec::new()));
        inner.retry_import_plans.remove(&directory);
        let snapshot = super::snapshot_locked(&inner, &directory, true);
        drop(inner);
        assert!(matches!(
            snapshot.status,
            bcode_session_models::SessionCatalogStatus::Loaded
        ));
        assert_eq!(snapshot.sessions, vec![session]);
    }

    #[tokio::test]
    async fn retry_deadline_notifies_observers_but_rejects_obsolete_generation() {
        let root = tempfile::tempdir().unwrap();
        let state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        ));
        let catalog = &state.session_catalog;
        let deadline = std::time::Instant::now();
        catalog
            .inner
            .lock()
            .await
            .retry_import_plans
            .insert(root.path().to_path_buf(), deadline);
        let mut revisions = catalog.subscribe();
        revisions.borrow_and_update();
        super::notify_planning_retry(
            &std::sync::Arc::downgrade(&state),
            root.path().to_path_buf(),
            0,
            deadline,
        )
        .await;
        assert!(revisions.has_changed().unwrap());
        revisions.borrow_and_update();
        catalog.inner.lock().await.planning_generation = 1;
        super::notify_planning_retry(
            &std::sync::Arc::downgrade(&state),
            root.path().to_path_buf(),
            0,
            deadline,
        )
        .await;
        assert!(!revisions.has_changed().unwrap());
        super::notify_planning_retry(
            &std::sync::Arc::downgrade(&state),
            root.path().to_path_buf(),
            1,
            deadline + std::time::Duration::from_millis(1),
        )
        .await;
        assert!(!revisions.has_changed().unwrap());
        let weak = std::sync::Arc::downgrade(&state);
        drop(state);
        assert!(weak.upgrade().is_none());
        super::notify_planning_retry(&weak, root.path().to_path_buf(), 1, deadline).await;
        drop(weak);
    }

    #[tokio::test]
    async fn stale_planning_generation_cannot_install_source() {
        let root = tempfile::tempdir().unwrap();
        let state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        ));
        let catalog = &state.session_catalog;
        catalog.inner.lock().await.planning_generation = 1;
        let revision = catalog.revision();
        catalog
            .ensure_source_for_generation(&state, super::CatalogSourcePlan::InMemory, Some(0))
            .await;
        assert_eq!(catalog.revision(), revision);
        assert!(catalog.inner.lock().await.sources.is_empty());
        catalog
            .ensure_source_for_generation(&state, super::CatalogSourcePlan::InMemory, Some(1))
            .await;
        assert!(catalog.revision() > revision);
        assert!(
            catalog
                .inner
                .lock()
                .await
                .sources
                .contains_key(&super::native_source_key())
        );
        drop(state);
    }
    #[tokio::test]
    async fn partial_enumeration_retains_successful_plans_for_retry() {
        let root = tempfile::tempdir().unwrap();
        let state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        ));
        let catalog = &state.session_catalog;
        catalog
            .import_source_ids("failed", async { Err("unavailable".to_owned()) })
            .await;
        let mut revisions = catalog.subscribe();
        catalog
            .ensure_sources_with_imports(&state, root.path().to_path_buf(), async {
                vec![super::CatalogSourcePlan::InMemory]
            })
            .await;
        tokio::time::timeout(std::time::Duration::from_secs(5), async {
            loop {
                let complete = {
                    let inner = catalog.inner.lock().await;
                    inner.retry_import_plans.contains_key(root.path())
                };
                if complete {
                    break;
                }
                revisions.changed().await.unwrap();
            }
        })
        .await
        .unwrap();
        let inner = catalog.inner.lock().await;
        let plans = inner.import_plans[root.path()].as_ref().unwrap();
        assert_eq!(plans.len(), 1);
        assert!(matches!(plans[0], super::CatalogSourcePlan::InMemory));
        drop(inner);
        catalog
            .ensure_sources_with_imports(&state, root.path().to_path_buf(), async {
                panic!("observation must not retry before backoff expires")
            })
            .await;
        tokio::task::yield_now().await;
        assert!(catalog.inner.lock().await.import_plans[root.path()].is_some());
        catalog
            .inner
            .lock()
            .await
            .retry_import_plans
            .insert(root.path().to_path_buf(), std::time::Instant::now());
        let (started, received) = tokio::sync::oneshot::channel();
        catalog
            .ensure_sources_with_imports(&state, root.path().to_path_buf(), async move {
                started.send(()).unwrap();
                Vec::new()
            })
            .await;
        tokio::time::timeout(std::time::Duration::from_secs(5), received)
            .await
            .unwrap()
            .unwrap();
        drop(state);
    }
    #[tokio::test]
    async fn native_discovery_starts_before_blocked_import_enumeration() {
        let root = tempfile::tempdir().unwrap();
        let state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        ));
        {
            let (release, blocked) = tokio::sync::oneshot::channel();
            let planning = state.session_catalog.ensure_sources_with_imports(
                &state,
                root.path().to_path_buf(),
                async move {
                    blocked.await.unwrap();
                    Vec::new()
                },
            );
            tokio::pin!(planning);
            assert!(futures::poll!(&mut planning).is_ready());
            let inner = state.session_catalog.inner.lock().await;
            assert!(matches!(
                inner.sources[&super::native_source_key()].state,
                super::SourceCacheState::Loading { .. }
            ));
            assert_eq!(
                super::snapshot_locked(&inner, root.path(), true).status,
                bcode_session_models::SessionCatalogStatus::Loading
            );
            drop(inner);
            let mut session = summary(SessionId::new(), None);
            session.working_directory = root.path().canonicalize().unwrap();
            // Seed useful metadata while provider planning is deliberately blocked.
            state
                .session_catalog
                .apply_source_result(
                    super::native_source_key(),
                    super::native_metadata(),
                    Ok(SourceLoadResult {
                        sessions: vec![session.clone()],
                        diagnostics: SourceDiagnostics::default(),
                    }),
                )
                .await;
            // Use the same normalized scope as the public listing operation.
            {
                let mut inner = state.session_catalog.inner.lock().await;
                let pending = inner.import_plans.remove(root.path()).unwrap();
                inner
                    .import_plans
                    .insert(session.working_directory.clone(), pending);
            }
            {
                let listing = crate::session_operations::list(&state, &session.working_directory);
                tokio::pin!(listing);
                let std::task::Poll::Ready(result) = futures::poll!(&mut listing) else {
                    panic!("useful application results waited for import enumeration");
                };
                let snapshot = result.unwrap();
                assert_eq!(snapshot.sessions, vec![session.clone()]);
                assert_eq!(
                    snapshot.status,
                    bcode_session_models::SessionCatalogStatus::Loading
                );
            }
            release.send(()).unwrap();
        }
        drop(state);
    }
    #[tokio::test]
    async fn native_mutations_during_discovery_require_fresh_load() {
        for delete in [false, true] {
            let root = tempfile::tempdir().unwrap();
            let state = std::sync::Arc::new(crate::tests::test_server_state(
                bcode_session::SessionManager::persistent_lazy(root.path()),
            ));
            let catalog = &state.session_catalog;
            let session = summary(SessionId::new(), None);
            catalog.inner.lock().await.sources.insert(
                super::native_source_key(),
                super::SourceCache {
                    metadata: super::native_metadata(),
                    state: super::SourceCacheState::Loading {
                        sessions: Vec::new(),
                    },
                    updated_at_ms: 0,
                    generation: 1,
                },
            );
            let revision = catalog.revision();
            if delete {
                catalog.remove_native_session(session.id).await;
            } else {
                catalog.upsert_native_session(session.clone()).await;
            }
            assert!(catalog.revision() > revision);
            catalog
                .publish_source_result(
                    super::native_source_key(),
                    super::native_metadata(),
                    Ok(SourceLoadResult {
                        sessions: vec![session],
                        diagnostics: SourceDiagnostics::default(),
                    }),
                    Some(1),
                )
                .await;
            let inner = catalog.inner.lock().await;
            assert!(matches!(
                inner.sources[&super::native_source_key()].state,
                super::SourceCacheState::Empty
            ));
            assert!(
                inner.sources[&super::native_source_key()]
                    .sessions()
                    .is_empty()
            );
            drop(inner);
            let mut revisions = catalog.subscribe();
            catalog
                .ensure_source(&state, super::CatalogSourcePlan::InMemory)
                .await;
            tokio::time::timeout(std::time::Duration::from_secs(5), async {
                loop {
                    let loaded = {
                        let inner = catalog.inner.lock().await;
                        matches!(
                            inner.sources[&super::native_source_key()].state,
                            super::SourceCacheState::Loaded { .. }
                        )
                    };
                    if loaded {
                        break;
                    }
                    revisions.changed().await.unwrap();
                }
            })
            .await
            .expect("invalidated discovery must complete a fresh load");
            let inner = catalog.inner.lock().await;
            assert!(
                inner.sources[&super::native_source_key()]
                    .sessions()
                    .is_empty()
            );
            drop(inner);
            drop(state);
        }
    }
    #[tokio::test]
    async fn native_mutations_fence_pending_refresh_publication() {
        let catalog = SessionCatalog::default();
        let original = summary(SessionId::new(), None);
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![original.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        let generation = catalog.inner.lock().await.sources[&super::native_source_key()].generation;
        let mut renamed = original.clone();
        renamed.explicit_name = Some("renamed".to_owned());
        catalog.upsert_native_session(renamed.clone()).await;
        catalog
            .publish_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![original.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
                Some(generation),
            )
            .await;
        assert_eq!(
            catalog.inner.lock().await.sources[&super::native_source_key()].sessions(),
            &[renamed]
        );
        let generation = catalog.inner.lock().await.sources[&super::native_source_key()].generation;
        catalog.remove_native_session(original.id).await;
        catalog
            .publish_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![original],
                    diagnostics: SourceDiagnostics::default(),
                }),
                Some(generation),
            )
            .await;
        assert!(
            catalog.inner.lock().await.sources[&super::native_source_key()]
                .sessions()
                .is_empty()
        );
    }
    #[tokio::test]
    async fn invalidated_source_load_cannot_publish_over_fresh_results() {
        let catalog = SessionCatalog::default();
        let session = summary(SessionId::new(), None);
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        let generation = catalog.inner.lock().await.sources[&super::native_source_key()].generation;
        catalog.invalidate_source_id(super::NATIVE_SOURCE_ID).await;
        let revision = catalog.revision();
        catalog
            .publish_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Err("stale failure".to_owned()),
                Some(generation),
            )
            .await;
        assert_eq!(catalog.revision(), revision);
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        let revision = catalog.revision();
        catalog
            .publish_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: Vec::new(),
                    diagnostics: SourceDiagnostics::default(),
                }),
                Some(generation),
            )
            .await;
        assert_eq!(catalog.revision(), revision);
        assert_eq!(
            catalog.inner.lock().await.sources[&super::native_source_key()].sessions(),
            &[session]
        );
    }
    #[tokio::test]
    async fn import_enumeration_coalesces_and_warm_reads_skip_provider_work() {
        let catalog = SessionCatalog::default();
        let (release, blocked) = tokio::sync::oneshot::channel();
        let first = catalog.import_source_ids("provider", async {
            blocked.await.unwrap();
            Ok(vec!["source".to_owned()])
        });
        tokio::pin!(first);
        assert!(futures::poll!(&mut first).is_pending());
        let second = catalog.import_source_ids("provider", async {
            panic!("concurrent enumeration must share initialization")
        });
        tokio::pin!(second);
        assert!(futures::poll!(&mut second).is_pending());
        release.send(()).unwrap();
        assert_eq!(first.await, vec!["source"]);
        assert_eq!(second.await, vec!["source"]);
        assert_eq!(
            catalog
                .import_source_ids("provider", async {
                    panic!("warm observation must not poll provider")
                })
                .await,
            vec!["source"]
        );
    }

    #[tokio::test]
    async fn import_enumeration_retries_errors_and_cancelled_initialization() {
        let catalog = SessionCatalog::default();
        assert!(
            catalog
                .import_source_ids("provider", async { Err("offline".to_owned()) })
                .await
                .is_empty()
        );
        {
            let pending = catalog.import_source_ids("provider", std::future::pending());
            tokio::pin!(pending);
            assert!(futures::poll!(&mut pending).is_pending());
        }
        assert_eq!(
            catalog
                .import_source_ids("provider", async { Ok(vec!["recovered".to_owned()]) })
                .await,
            vec!["recovered"]
        );
        catalog.import_sources.lock().await.clear();
        assert_eq!(
            catalog
                .import_source_ids("provider", async { Ok(vec!["new source".to_owned()]) })
                .await,
            vec!["new source"]
        );
    }

    #[tokio::test]
    async fn import_refresh_does_not_restore_an_in_flight_old_enumeration() {
        let catalog = SessionCatalog::default();
        let (release, blocked) = tokio::sync::oneshot::channel();
        let old = catalog.import_source_ids("provider", async {
            blocked.await.unwrap();
            Ok(vec!["old".to_owned()])
        });
        tokio::pin!(old);
        assert!(futures::poll!(&mut old).is_pending());
        catalog.import_sources.lock().await.clear();
        assert_eq!(
            catalog
                .import_source_ids("provider", async { Ok(vec!["new".to_owned()]) })
                .await,
            vec!["new"]
        );
        release.send(()).unwrap();
        assert_eq!(old.await, vec!["old"]);
        assert_eq!(
            catalog
                .import_source_ids("provider", async {
                    panic!("fresh cache must survive old completion")
                })
                .await,
            vec!["new"]
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn discovery_gate_release_allows_invalidated_generation_to_finish() {
        let state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::default(),
        ));
        let directory = std::env::current_dir().unwrap();
        let expected = state
            .sessions
            .create_session(Some("replacement generation".into()), directory.clone())
            .await
            .unwrap();
        let gate = std::sync::Arc::new(tokio::sync::Semaphore::new(0));
        *state.session_catalog.discovery_gate.lock().await = Some(gate.clone());
        state
            .session_catalog
            .ensure_source(&state, super::CatalogSourcePlan::InMemory)
            .await;
        // Fence the blocked load exactly as a concurrent native mutation does.
        state
            .session_catalog
            .upsert_native_session(expected.clone())
            .await;
        state
            .session_catalog
            .ensure_source(&state, super::CatalogSourcePlan::InMemory)
            .await;
        gate.add_permits(1);
        let mut revisions = state.session_catalog.subscribe();
        let snapshot = tokio::time::timeout(std::time::Duration::from_secs(5), async {
            loop {
                revisions.borrow_and_update();
                let snapshot = state.session_catalog.snapshot(&state, &directory).await;
                if snapshot.status == bcode_session_models::SessionCatalogStatus::Loaded {
                    break snapshot;
                }
                revisions.changed().await.unwrap();
            }
        })
        .await
        .expect("one release must unblock replacement discovery too");
        assert_eq!(snapshot.sessions.len(), 1);
        assert_eq!(snapshot.sessions[0].id, expected.id);
        drop(state);
    }

    #[tokio::test]
    async fn public_watcher_receives_cold_rows_and_discovery_completion_over_ipc() {
        let root = tempfile::tempdir().unwrap();
        let directory = std::env::current_dir().unwrap();
        let writer = bcode_session::SessionManager::persistent_lazy(root.path());
        let expected = writer
            .create_session(Some("IPC cold row".to_owned()), directory)
            .await
            .unwrap();
        writer.shutdown_catalog_updates().await;
        drop(writer);
        let mut state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        ));
        std::sync::Arc::get_mut(&mut state)
            .unwrap()
            .daemon_status
            .state_location_id = Some(bcode_ipc::state_location_id());
        let gate = std::sync::Arc::new(tokio::sync::Semaphore::new(0));
        *state.session_catalog.discovery_gate.lock().await = Some(gate.clone());
        state.start_catalog_event_forwarder().await;
        let socket_dir = tempfile::tempdir().unwrap();
        let endpoint = bcode_ipc::IpcEndpoint::unix_socket(socket_dir.path().join("catalog.sock"));
        let listener = bcode_ipc::LocalIpcListener::bind(&endpoint).unwrap();
        let server_state = state.clone();
        let server = tokio::spawn(async move {
            let stream = listener.accept().await.unwrap();
            crate::handle_client(stream, server_state).await.unwrap();
        });
        let client = bcode_client::BcodeClient::new(endpoint);
        let mut watcher = client.watch_session_catalog().await.unwrap();
        let initial = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            watcher.initial_snapshot(),
        )
        .await
        .unwrap()
        .unwrap();
        assert_eq!(initial.sessions.len(), 1);
        assert_eq!(initial.sessions[0].id, expected.id);
        assert_eq!(
            initial.catalog_status,
            bcode_session_models::SessionCatalogStatus::Loading
        );
        gate.add_permits(1);
        drop(gate);
        tokio::time::timeout(std::time::Duration::from_secs(5), async {
            loop {
                let next = watcher.next_snapshot().await.unwrap();
                assert_eq!(next.sessions.len(), 1);
                assert_eq!(next.sessions[0].id, expected.id);
                if next.catalog_status == bcode_session_models::SessionCatalogStatus::Loaded {
                    break;
                }
            }
        })
        .await
        .unwrap();
        drop(watcher);
        tokio::time::timeout(std::time::Duration::from_secs(5), server)
            .await
            .unwrap()
            .unwrap();
        state.request_shutdown();
        state.stop_catalog_workers().await.unwrap();
        drop(state);
    }

    #[tokio::test]
    async fn cold_catalog_round_trip_preserves_persisted_metadata() {
        let root = tempfile::tempdir().unwrap();
        let writer = bcode_session::SessionManager::persistent_lazy(root.path());
        let mut expected = std::collections::BTreeMap::new();
        for index in 0..259 {
            let session = writer
                .create_session(
                    Some(format!("cold catalog row {index}")),
                    root.path().to_owned(),
                )
                .await
                .unwrap();
            expected.insert(session.id, session.name);
        }
        writer.flush_catalog_updates().await;
        drop(writer);
        let mut state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        ));
        std::sync::Arc::get_mut(&mut state)
            .unwrap()
            .daemon_status
            .state_location_id = Some("cold-location".to_owned());
        let gate = std::sync::Arc::new(tokio::sync::Semaphore::new(0));
        *state.session_catalog.discovery_gate.lock().await = Some(gate.clone());
        let mut revisions = state.session_catalog.subscribe();
        let started = std::time::Instant::now();
        let snapshot = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            crate::session_operations::list(&state, root.path()),
        )
        .await
        .expect("cold catalog listing must complete")
        .unwrap();
        let first_useful = started.elapsed();
        assert!(!snapshot.sessions.is_empty());
        assert!(snapshot.sessions.len() <= expected.len());
        for session in &snapshot.sessions {
            assert_eq!(expected.get(&session.id), Some(&session.name));
        }
        assert_eq!(
            snapshot.status,
            bcode_session_models::SessionCatalogStatus::Loading
        );
        assert!(matches!(
            state.sessions.catalog_status(),
            bcode_session::CatalogLoadStatus::NotStarted
        ));
        gate.add_permits(1);
        drop(gate);
        let completed = tokio::time::timeout(std::time::Duration::from_secs(5), async {
            loop {
                revisions.borrow_and_update();
                let snapshot = state.session_catalog.snapshot(&state, root.path()).await;
                if snapshot.status == bcode_session_models::SessionCatalogStatus::Loaded {
                    break snapshot;
                }
                revisions.changed().await.unwrap();
            }
        })
        .await
        .expect("discovery must finish after release");
        let completion = started.elapsed();
        assert_eq!(completed.sessions.len(), expected.len());
        assert_eq!(
            completed
                .sessions
                .iter()
                .map(|session| (session.id, session.name.clone()))
                .collect::<std::collections::BTreeMap<_, _>>(),
            expected
        );
        let warm_started = std::time::Instant::now();
        let reopened = crate::session_operations::list(&state, root.path())
            .await
            .unwrap();
        let warm = warm_started.elapsed();
        assert_eq!(reopened.sessions, completed.sessions);
        eprintln!(
            "catalog server rows={} first_rows={} first_useful={first_useful:?} completed={completion:?} warm={warm:?}",
            expected.len(),
            snapshot.sessions.len()
        );
        drop(state);
    }

    #[tokio::test]
    async fn available_catalog_results_do_not_wait_for_unstarted_native_discovery() {
        let root = tempfile::tempdir().unwrap();
        let state = std::sync::Arc::new(crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        ));
        let session = summary(SessionId::new(), None);
        state
            .session_catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        // Keep an additional relevant source loading so aggregate status cannot be
        // mistaken for complete. No task is responsible for completing this source.
        let key = super::CatalogSourceKey {
            source_id: "slow".to_owned(),
            scope: super::CatalogSourceScope::Global,
        };
        state.session_catalog.inner.lock().await.sources.insert(
            key,
            super::SourceCache {
                metadata: super::SourceMetadata {
                    display_name: "Slow source".to_owned(),
                },
                state: super::SourceCacheState::Loading {
                    sessions: Vec::new(),
                },
                updated_at_ms: 0,
                generation: 0,
            },
        );
        let snapshot = {
            let listing = crate::session_operations::list(&state, &session.working_directory);
            tokio::pin!(listing);
            match futures::poll!(&mut listing) {
                std::task::Poll::Ready(result) => result.unwrap(),
                std::task::Poll::Pending => panic!("available results waited for discovery"),
            }
        };
        assert_eq!(snapshot.sessions, vec![session.clone()]);
        assert_eq!(
            snapshot.status,
            bcode_session_models::SessionCatalogStatus::Loading
        );
        assert!(matches!(
            state.sessions.catalog_status(),
            bcode_session::CatalogLoadStatus::NotStarted
        ));
        drop(state);
    }

    #[tokio::test]
    #[ignore = "diagnostic timing run; no machine-dependent latency threshold"]
    async fn available_catalog_listing_timing() {
        for count in [100, 1_000, 10_000] {
            let root = tempfile::tempdir().unwrap();
            let state = std::sync::Arc::new(crate::tests::test_server_state(
                bcode_session::SessionManager::persistent_lazy(root.path()),
            ));
            let sessions = (0..count)
                .map(|_| summary(SessionId::new(), None))
                .collect::<Vec<_>>();
            let directory = sessions[0].working_directory.clone();
            state
                .session_catalog
                .apply_source_result(
                    super::native_source_key(),
                    super::native_metadata(),
                    Ok(SourceLoadResult {
                        sessions,
                        diagnostics: SourceDiagnostics::default(),
                    }),
                )
                .await;
            let start = std::time::Instant::now();
            let initial = crate::session_operations::list(&state, &directory)
                .await
                .unwrap();
            let initial_elapsed = start.elapsed();
            assert_eq!(initial.sessions.len(), count);
            let start = std::time::Instant::now();
            for _ in 0..10 {
                assert_eq!(
                    crate::session_operations::list(&state, &directory)
                        .await
                        .unwrap()
                        .sessions
                        .len(),
                    count
                );
            }
            eprintln!(
                "available catalog count={count} first={initial_elapsed:?} warm_mean={:?}",
                start.elapsed() / 10
            );
            drop(state);
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn snapshot_directory_resolution_observes_symlink_changes() {
        let root = tempfile::tempdir().unwrap();
        let first = root.path().join("first");
        let second = root.path().join("second");
        std::fs::create_dir(&first).unwrap();
        std::fs::create_dir(&second).unwrap();
        let alias = root.path().join("alias");
        std::os::unix::fs::symlink(&first, &alias).unwrap();
        let catalog = SessionCatalog::default();
        let mut session = summary(SessionId::new(), None);
        session.working_directory = alias.clone();
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        {
            let inner = catalog.inner.lock().await;
            assert_eq!(
                super::snapshot_locked(&inner, &first.canonicalize().unwrap(), true)
                    .sessions
                    .len(),
                1
            );
        }
        std::fs::remove_file(&alias).unwrap();
        std::os::unix::fs::symlink(&second, &alias).unwrap();
        let inner = catalog.inner.lock().await;
        assert!(
            super::snapshot_locked(&inner, &first.canonicalize().unwrap(), true)
                .sessions
                .is_empty()
        );
        assert_eq!(
            super::snapshot_locked(&inner, &second.canonicalize().unwrap(), true)
                .sessions
                .len(),
            1
        );
    }

    #[test]
    fn native_primary_uses_retained_store_and_identity() {
        let root = tempfile::tempdir().expect("store root");
        let mut state = crate::tests::test_server_state(
            bcode_session::SessionManager::persistent_lazy(root.path()),
        );
        state.daemon_status.state_location_id = Some("retained-location".to_owned());
        let locations = super::native_locations(&state);
        let primary = locations
            .iter()
            .find(|location| location.primary)
            .expect("primary");
        assert_eq!(primary.sessions_root, root.path());
        assert_eq!(primary.location_id, "retained-location");
        state.daemon_status.state_location_id = None;
        assert!(super::native_locations(&state).is_empty());
        drop(state);
    }
    use super::{
        CatalogSourcePlan, NativeLocation, SessionCatalog, SourceDiagnostics, SourceLoadResult,
        mark_ambiguous_locations,
    };
    use bcode_session_models::{
        SessionId, SessionLocationSummary, SessionSummary, SessionTitleSource,
    };
    use std::path::PathBuf;

    fn location(location_id: &str, profile: Option<&str>, primary: bool) -> NativeLocation {
        NativeLocation {
            location_id: location_id.to_owned(),
            profile: profile.map(str::to_owned),
            sessions_root: PathBuf::from("/tmp").join(location_id),
            primary,
        }
    }

    fn summary(id: SessionId, location: Option<SessionLocationSummary>) -> SessionSummary {
        SessionSummary {
            automatic_title: None,
            automatic_title_source_sequence: None,
            parent_id: None,
            id,
            name: None,
            explicit_name: None,
            derived_title: None,
            title_source: SessionTitleSource::EmptyDraft,
            client_count: 0,
            created_at_ms: 0,
            updated_at_ms: 0,
            working_directory: PathBuf::from("/tmp/workspace"),
            import: None,
            execution: None,
            location,
        }
    }

    #[tokio::test]
    async fn catalog_mutations_publish_matching_revisions() {
        let catalog = SessionCatalog::default();
        let mut revisions = catalog.subscribe();
        let session = summary(SessionId::new(), None);
        catalog
            .apply_source_result(
                super::native_source_key(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        assert_eq!(*revisions.borrow_and_update(), 1);
        catalog.upsert_native_session(session.clone()).await;
        assert!(!revisions.has_changed().unwrap());
        let mut renamed = session.clone();
        renamed.name = Some("renamed".into());
        catalog.upsert_native_session(renamed).await;
        let inner = catalog.inner.lock().await;
        let snapshot = super::snapshot_locked(&inner, &session.working_directory, true);
        drop(inner);
        assert_eq!(snapshot.revision, 2);
        assert_eq!(snapshot.sessions[0].name.as_deref(), Some("renamed"));
        assert_eq!(*revisions.borrow_and_update(), snapshot.revision);
        catalog.remove_native_session(session.id).await;
        assert_eq!(*revisions.borrow_and_update(), 3);
        catalog.invalidate_native().await;
        assert_eq!(*revisions.borrow_and_update(), 4);
        let inner = catalog.inner.lock().await;
        let snapshot = super::snapshot_locked(&inner, &session.working_directory, true);
        drop(inner);
        assert_eq!(snapshot.revision, 4);
        assert!(snapshot.sessions.is_empty());
    }

    #[tokio::test]
    async fn source_timestamps_change_on_updates_not_observation() {
        let catalog = SessionCatalog::default();
        let key = super::native_source_key();
        let session = summary(SessionId::new(), None);
        catalog
            .apply_source_result(
                key.clone(),
                super::native_metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![session.clone()],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
        {
            let mut inner = catalog.inner.lock().await;
            let source = inner.sources.get_mut(&key).unwrap();
            source.updated_at_ms = 42;
            let first = super::source_status(&key, source);
            let second = super::source_status(&key, source);
            drop(inner);
            assert_eq!(first.updated_at_ms, 42);
            assert_eq!(first, second);
        }
        catalog.upsert_native_session(session.clone()).await;
        catalog.remove_native_session(SessionId::new()).await;
        assert_eq!(catalog.inner.lock().await.sources[&key].updated_at_ms, 42);
        let mut renamed = session.clone();
        renamed.name = Some("renamed".into());
        catalog.upsert_native_session(renamed).await;
        assert!(catalog.inner.lock().await.sources[&key].updated_at_ms > 42);
        catalog
            .inner
            .lock()
            .await
            .sources
            .get_mut(&key)
            .unwrap()
            .updated_at_ms = 42;
        catalog.remove_native_session(session.id).await;
        assert!(catalog.inner.lock().await.sources[&key].updated_at_ms > 42);
        catalog
            .inner
            .lock()
            .await
            .sources
            .get_mut(&key)
            .unwrap()
            .updated_at_ms = 42;
        catalog.invalidate_native().await;
        assert!(catalog.inner.lock().await.sources[&key].updated_at_ms > 42);
        catalog
            .inner
            .lock()
            .await
            .sources
            .get_mut(&key)
            .unwrap()
            .updated_at_ms = 42;
        catalog
            .apply_source_result(
                key.clone(),
                super::native_metadata(),
                Err("unavailable".into()),
            )
            .await;
        assert!(catalog.inner.lock().await.sources[&key].updated_at_ms > 42);
    }

    #[test]
    fn primary_location_keeps_the_stable_native_source_identity() {
        let primary = location("aaaa", None, true);
        let foreign = location("bbbb", Some("big"), false);

        assert_eq!(primary.source_id(), "native");
        assert_eq!(foreign.source_id(), "native:bbbb");
        assert_ne!(primary.source_id(), foreign.source_id());
    }

    #[test]
    fn location_display_names_prefer_profile_labels_without_leaking_paths() {
        assert_eq!(
            location("aaaa", None, true).display_name(),
            "Native Bcode sessions"
        );
        assert_eq!(
            location("bbbb", Some("big"), false).display_name(),
            "Bcode sessions [big]"
        );

        // An unnamed foreign location falls back to its opaque identity, never its root path.
        let unnamed = location("cccc", None, false);
        let display = unnamed.display_name();
        assert!(display.contains("cccc"), "{display}");
        assert!(!display.contains("/tmp"), "{display}");
    }

    #[test]
    fn duplicate_session_ids_across_locations_are_marked_ambiguous_not_merged() {
        let shared = SessionId::new();
        let unique = SessionId::new();
        let mut sessions = vec![
            summary(shared, Some(location("aaaa", None, true).summary())),
            summary(shared, Some(location("bbbb", Some("big"), false).summary())),
            summary(unique, Some(location("aaaa", None, true).summary())),
        ];

        mark_ambiguous_locations(&mut sessions);

        assert_eq!(
            sessions.len(),
            3,
            "duplicate claims must be retained rather than merged"
        );
        let ambiguous = sessions
            .iter()
            .filter(|session| session.id == shared)
            .collect::<Vec<_>>();
        assert_eq!(ambiguous.len(), 2);
        assert!(
            ambiguous
                .iter()
                .all(|session| session.location.as_ref().is_some_and(|l| l.ambiguous)),
            "every claim on a duplicated session ID must be flagged ambiguous"
        );
        let unaffected = sessions
            .iter()
            .find(|session| session.id == unique)
            .expect("unique session");
        assert!(
            !unaffected.location.as_ref().expect("location").ambiguous,
            "an unambiguous session must not be flagged"
        );
    }

    #[test]
    fn one_location_claiming_a_session_is_never_ambiguous() {
        let id = SessionId::new();
        let mut sessions = vec![summary(id, Some(location("aaaa", None, true).summary()))];

        mark_ambiguous_locations(&mut sessions);

        assert!(!sessions[0].location.as_ref().expect("location").ambiguous);
    }

    #[test]
    fn sessions_without_location_metadata_are_left_untouched() {
        let id = SessionId::new();
        let mut sessions = vec![summary(id, None), summary(id, None)];

        mark_ambiguous_locations(&mut sessions);

        assert!(sessions.iter().all(|session| session.location.is_none()));
    }

    /// Populate one loaded catalog source directly, without discovery or storage access.
    ///
    /// Keys and metadata come from the production `CatalogSourcePlan`, so the seeded state
    /// is identical in shape to what real per-location discovery produces.
    async fn seed_source(catalog: &SessionCatalog, location: &NativeLocation, id: SessionId) {
        let plan = CatalogSourcePlan::Native {
            location: location.clone(),
        };
        catalog
            .apply_source_result(
                plan.key(),
                plan.metadata(),
                Ok(SourceLoadResult {
                    sessions: vec![summary(id, Some(location.summary()))],
                    diagnostics: SourceDiagnostics::default(),
                }),
            )
            .await;
    }

    /// The refusal the attach handlers consult must report every claiming location once
    /// more than one readable location claims the same session ID, and must report
    /// nothing when the session is unambiguous.
    #[tokio::test]
    async fn ambiguous_location_ids_reports_conflicting_claims_from_loaded_sources() {
        let catalog = SessionCatalog::default();
        let primary = location("aaaa", None, true);
        let foreign = location("bbbb", Some("big"), false);

        let unique = SessionId::new();
        seed_source(&catalog, &primary, unique).await;
        assert!(
            catalog.ambiguous_location_ids(unique).await.is_empty(),
            "a session claimed by exactly one location must not be reported ambiguous"
        );

        let shared = SessionId::new();
        seed_source(&catalog, &primary, shared).await;
        seed_source(&catalog, &foreign, shared).await;

        let claims = catalog.ambiguous_location_ids(shared).await;
        assert_eq!(
            claims,
            vec!["aaaa".to_owned(), "bbbb".to_owned()],
            "every claiming location must be surfaced so the conflict is actionable"
        );
        assert!(
            catalog.ambiguous_location_ids(unique).await.is_empty(),
            "ambiguity must not leak across session IDs"
        );
    }
}