symforge 11.10.1

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

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Condvar};
use std::time::Duration;

use super::registry::ProjectKey;
use crate::domain::{FreshnessStatus, RootBinding, StatePlacement};

const EMBED_OBSERVER_POLL: Duration = Duration::from_millis(200);
const REFRESHING_VISIBILITY_WINDOW: Duration = Duration::from_millis(25);

/// Identity of one embedded open. Never reused, including across reopen.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EmbeddedIdentity(std::num::NonZeroU64);

static NEXT_EMBEDDED: AtomicU64 = AtomicU64::new(1);

impl EmbeddedIdentity {
    /// Mint a fresh never-reused embedded identity.
    pub fn fresh() -> Self {
        let raw = NEXT_EMBEDDED.fetch_add(1, Ordering::Relaxed);
        Self(std::num::NonZeroU64::new(raw).expect("embedded counter starts at 1"))
    }

    /// Raw counter value, crate-only, for the embed boundary's kind-prefixed
    /// rendering and nothing else.
    pub(crate) fn raw(&self) -> u64 {
        self.0.get()
    }
}

/// Why an embedded request was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EmbedRefusal {
    /// This source already has a live handle; there is only ever one.
    SourceAlreadyOpen {
        /// The identity currently holding it.
        held_by: EmbeddedIdentity,
    },
    /// Closing here would wait on the thread doing the closing.
    ///
    /// Returned instead of deadlocking. A finalizer that closes the source it is
    /// finalizing is waiting for itself, and blocking would hang the embedder's
    /// thread with no diagnosis.
    WouldSelfWait,
    /// The handle has already closed.
    AlreadyClosed,
}

/// What a close actually did.
///
/// Records whether THIS call performed the shutdown or joined one already done,
/// so a caller cannot mistake a coalesced close for having been the one that
/// tore the source down.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CloseReceipt {
    identity: EmbeddedIdentity,
    performed_shutdown: bool,
    was_final_owner: bool,
}

impl CloseReceipt {
    /// The source that was closed.
    pub fn identity(&self) -> EmbeddedIdentity {
        self.identity
    }

    /// Whether this call performed the shutdown, rather than joining one that
    /// had already happened.
    pub fn performed_shutdown(&self) -> bool {
        self.performed_shutdown
    }

    /// Whether this was the last open source in the registration.
    pub fn was_final_owner(&self) -> bool {
        self.was_final_owner
    }
}

thread_local! {
    /// Which source this thread is finalizing, if any, so a close attempted
    /// from inside that source's own finalizer can refuse rather than wait on
    /// itself.
    ///
    /// The identity is the whole point. A bare `bool` refused ANY close made
    /// from inside ANY finalizer, so `a.finalize(|| b.close())` reported that
    /// closing `b` would wait on itself — a diagnosis naming something that did
    /// not happen, while `b` was left open.
    static FINALIZING: std::cell::Cell<Option<EmbeddedIdentity>> =
        const { std::cell::Cell::new(None) };
}

/// Mints embedded source handles, and is the only thing that can.
///
/// Named by the frozen `ORACLE-EMBED-FOUNDATION` seam. Construction of a handle
/// is private to this type, which is what makes "one incarnation owns at most
/// one handle" enforceable rather than advisory.
#[derive(Debug, Default)]
pub struct EmbeddedSourceFactory {
    open: std::sync::Mutex<HashMap<ProjectKey, OpenEmbeddedSource>>,
    shutdown: AtomicBool,
}

#[derive(Debug)]
struct OpenEmbeddedSource {
    identity: EmbeddedIdentity,
    owner: Option<EmbeddedIdentity>,
    opening: bool,
    binding: Option<Arc<EmbeddedBinding>>,
}

#[cfg(feature = "__test-internals")]
static PANIC_AFTER_START_ROOT: std::sync::Mutex<Option<ProjectKey>> = std::sync::Mutex::new(None);

#[cfg(feature = "__test-internals")]
pub fn panic_after_start_for_test(root: &std::path::Path) {
    let crate::domain::RootResolution::Bound(binding) = crate::discovery::resolve_root_candidate(
        root,
        crate::domain::RootCandidateSource::McpClientRoot,
        crate::domain::RootRequestMode::Automatic,
    ) else {
        panic!("test root must resolve to an embedded binding");
    };
    *PANIC_AFTER_START_ROOT
        .lock()
        .expect("embedded panic hook mutex") = Some(ProjectKey::new(&binding.root_id.0));
}

#[cfg(feature = "__test-internals")]
fn take_panic_after_start_for_test(key: &ProjectKey) -> bool {
    let mut configured = PANIC_AFTER_START_ROOT
        .lock()
        .expect("embedded panic hook mutex");
    if configured.as_ref() == Some(key) {
        configured.take();
        true
    } else {
        false
    }
}

#[cfg(feature = "__test-internals")]
struct JoinEnteredState {
    entered: std::sync::Mutex<bool>,
    reached: Condvar,
}

#[cfg(feature = "__test-internals")]
static JOIN_ENTERED: std::sync::OnceLock<
    std::sync::Mutex<HashMap<PathBuf, Arc<JoinEnteredState>>>,
> = std::sync::OnceLock::new();

/// Wait until `shutdown` has dropped the factory mutex and is at `worker.join()`.
#[cfg(feature = "__test-internals")]
pub struct JoinEnteredForTest {
    root: PathBuf,
    state: Arc<JoinEnteredState>,
}

#[cfg(feature = "__test-internals")]
pub fn watch_join_entered_for_test(root: &std::path::Path) -> JoinEnteredForTest {
    let root = crate::live_index::store::normalize_root(root);
    let state = Arc::new(JoinEnteredState {
        entered: std::sync::Mutex::new(false),
        reached: Condvar::new(),
    });
    let watches = JOIN_ENTERED.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
    let previous = watches
        .lock()
        .expect("join-entered watch registry")
        .insert(root.clone(), Arc::clone(&state));
    assert!(
        previous.is_none(),
        "a root can hold only one join-entered watch"
    );
    JoinEnteredForTest { root, state }
}

#[cfg(feature = "__test-internals")]
impl JoinEnteredForTest {
    pub fn wait_until_entered(&self, timeout: Duration) -> bool {
        let entered = self.state.entered.lock().expect("join-entered watch");
        let (entered, _) = self
            .state
            .reached
            .wait_timeout_while(entered, timeout, |entered| !*entered)
            .expect("join-entered watch");
        *entered
    }
}

#[cfg(feature = "__test-internals")]
impl Drop for JoinEnteredForTest {
    fn drop(&mut self) {
        let watches = JOIN_ENTERED.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
        let mut watches = watches.lock().expect("join-entered watch registry");
        if watches
            .get(&self.root)
            .is_some_and(|current| Arc::ptr_eq(current, &self.state))
        {
            watches.remove(&self.root);
        }
    }
}

#[cfg(feature = "__test-internals")]
fn notify_join_entered(root: &std::path::Path) {
    let root = crate::live_index::store::normalize_root(root);
    let Some(state) = JOIN_ENTERED
        .get()
        .and_then(|watches| watches.lock().ok()?.get(&root).cloned())
    else {
        return;
    };
    *state.entered.lock().expect("join-entered watch") = true;
    state.reached.notify_all();
}

#[cfg(feature = "__test-internals")]
struct OpenAfterReserveState {
    holding: std::sync::Mutex<bool>,
    entered: std::sync::Mutex<bool>,
    reached: Condvar,
}

#[cfg(feature = "__test-internals")]
static OPEN_AFTER_RESERVE: std::sync::OnceLock<
    std::sync::Mutex<HashMap<ProjectKey, Arc<OpenAfterReserveState>>>,
> = std::sync::OnceLock::new();

/// Parks `open_bound` after it has reserved the root and before it admits.
#[cfg(feature = "__test-internals")]
pub struct OpenAfterReserveHoldForTest {
    key: ProjectKey,
    state: Arc<OpenAfterReserveState>,
}

#[cfg(feature = "__test-internals")]
pub fn hold_open_after_reserve_for_test(root: &std::path::Path) -> OpenAfterReserveHoldForTest {
    let crate::domain::RootResolution::Bound(binding) = crate::discovery::resolve_root_candidate(
        root,
        crate::domain::RootCandidateSource::McpClientRoot,
        crate::domain::RootRequestMode::Automatic,
    ) else {
        panic!("test root must resolve to an embedded binding");
    };
    let key = ProjectKey::new(&binding.root_id.0);
    let state = Arc::new(OpenAfterReserveState {
        holding: std::sync::Mutex::new(true),
        entered: std::sync::Mutex::new(false),
        reached: Condvar::new(),
    });
    let holds = OPEN_AFTER_RESERVE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
    let previous = holds
        .lock()
        .expect("open-after-reserve hold registry")
        .insert(key.clone(), Arc::clone(&state));
    assert!(
        previous.is_none(),
        "a root can hold only one open-after-reserve gate"
    );
    OpenAfterReserveHoldForTest { key, state }
}

#[cfg(feature = "__test-internals")]
impl OpenAfterReserveHoldForTest {
    pub fn wait_until_entered(&self, timeout: Duration) -> bool {
        let entered = self.state.entered.lock().expect("open-after-reserve hold");
        let (entered, _) = self
            .state
            .reached
            .wait_timeout_while(entered, timeout, |entered| !*entered)
            .expect("open-after-reserve hold");
        *entered
    }

    pub fn release(&self) {
        *self.state.holding.lock().expect("open-after-reserve hold") = false;
        self.state.reached.notify_all();
    }
}

#[cfg(feature = "__test-internals")]
impl Drop for OpenAfterReserveHoldForTest {
    fn drop(&mut self) {
        self.release();
        let holds = OPEN_AFTER_RESERVE.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
        let mut holds = holds.lock().expect("open-after-reserve hold registry");
        if holds
            .get(&self.key)
            .is_some_and(|current| Arc::ptr_eq(current, &self.state))
        {
            holds.remove(&self.key);
        }
    }
}

#[cfg(feature = "__test-internals")]
fn pause_open_after_reserve_for_test(key: &ProjectKey) {
    let Some(state) = OPEN_AFTER_RESERVE
        .get()
        .and_then(|holds| holds.lock().ok()?.get(key).cloned())
    else {
        return;
    };
    let mut entered = state.entered.lock().expect("open-after-reserve hold");
    if *entered {
        return;
    }
    *entered = true;
    drop(entered);
    state.reached.notify_all();
    let holding = state.holding.lock().expect("open-after-reserve hold");
    drop(
        state
            .reached
            .wait_while(holding, |holding| *holding)
            .expect("open-after-reserve hold"),
    );
}

struct OpenRollback {
    factory: Arc<EmbeddedSourceFactory>,
    key: ProjectKey,
    identity: EmbeddedIdentity,
    binding: Option<Arc<EmbeddedBinding>>,
    committed: bool,
}

impl OpenRollback {
    fn reserve(
        factory: Arc<EmbeddedSourceFactory>,
        key: ProjectKey,
        identity: EmbeddedIdentity,
    ) -> Self {
        Self {
            factory,
            key,
            identity,
            binding: None,
            committed: false,
        }
    }

    fn bind(&mut self, binding: Arc<EmbeddedBinding>) {
        self.binding = Some(binding);
    }

    fn commit(mut self) {
        self.committed = true;
    }
}

impl Drop for OpenRollback {
    fn drop(&mut self) {
        if self.committed {
            return;
        }
        if let Some(binding) = &self.binding {
            binding.shutdown();
        }
        let mut open = self
            .factory
            .open
            .lock()
            .expect("embedded registration mutex");
        if open
            .get(&self.key)
            .is_some_and(|source| source.identity == self.identity && source.opening)
        {
            open.remove(&self.key);
        }
        self.factory
            .shutdown
            .store(open.is_empty(), Ordering::Release);
        drop(open);
        let _ = super::activation::process_project_registry().stop(&self.key);
    }
}

#[derive(Debug)]
pub(crate) enum EmbeddedOpenError {
    SourceAlreadyOpen,
    AdmissionUnavailable,
    WorkerUnavailable,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct EmbeddedShutdownReport {
    pub closed_sources: u64,
    pub joined_workers: u64,
}

#[derive(Debug, Clone)]
struct EmbeddedRuntimeState {
    phase: super::public_api::SourceRuntimePhase,
    current_publication_identity: Option<String>,
    observer_epoch: u64,
    source_version: u64,
    change_revision: u64,
    #[cfg(feature = "embed")]
    lifecycle_epoch: u64,
}

#[derive(Debug, Default)]
struct WorkerControl {
    stop: bool,
    refresh_requested: bool,
    /// An `index_folder` reset deleted the snapshot scope; the next reload
    /// that publishes Current records the reset generation (MCP marks it
    /// only after its reload succeeds).
    reset_pending: bool,
}

#[cfg(feature = "embed")]
struct GraphLeaseEntry {
    expires_at: std::time::Instant,
    snapshot: Arc<super::embed_query::EmbeddedQuerySnapshot>,
}

#[cfg(feature = "embed")]
/// A bounded lease pinning one immutable graph publication across pagination. Drop releases it; forgotten leases expire within 30 seconds.
pub struct GraphPublicationLease {
    binding: std::sync::Weak<EmbeddedBinding>,
    id: u64,
    source_id: u64,
    lifecycle_epoch: u64,
}

#[cfg(feature = "embed")]
impl std::fmt::Debug for GraphPublicationLease {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GraphPublicationLease")
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "embed")]
impl Drop for GraphPublicationLease {
    fn drop(&mut self) {
        if let Some(binding) = self.binding.upgrade() {
            let mut state = binding.state.lock().expect("embedded state mutex");
            let mut leases = binding.graph_leases.lock().expect("graph lease mutex");
            let was_full = leases.len() >= 8;
            let removed = leases.remove(&self.id).is_some();
            drop(leases);
            if was_full && removed {
                binding.advance_change(&mut state);
            }
        }
    }
}

#[cfg(feature = "embed")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// Opaque source-local phase, publication, or lease-capacity revision for lossless blocking waits. Capture before a retryable operation, then pass to `EmbeddedSourceHandle::wait_for_change`.
pub struct SourceChangeVersion {
    source_id: u64,
    revision: u64,
}

struct EmbeddedBinding {
    identity: EmbeddedIdentity,
    key: ProjectKey,
    root: PathBuf,
    state_placement: StatePlacement,
    runtime: super::activation::ProjectRuntimeHandle,
    #[cfg(feature = "embed")]
    authority: Arc<super::activation::ProjectSourceAuthority>,
    #[cfg(feature = "embed")]
    state_anchor: Option<AdmittedStateAnchor>,
    #[cfg(feature = "embed")]
    restored_mtimes: std::sync::Mutex<Option<HashMap<String, u64>>>,
    #[cfg(feature = "embed")]
    git_view: std::sync::Mutex<Option<Arc<super::embed_git::PreparedGitView>>>,
    #[cfg(feature = "embed")]
    temporal_cache: Arc<super::embed_temporal::TemporalCache>,
    #[cfg(feature = "embed")]
    impact_symbols: super::embed_file_impact::ImpactSymbolStore,
    #[cfg(feature = "embed")]
    stel_store: super::embed_stel::StelStoreSlot,
    #[cfg(feature = "embed")]
    open_reset: Option<crate::embed::parity::source_options::SnapshotResetReceipt>,
    /// The host's control-state directory (`<replay_control_directory>/embed-host`),
    /// MCP's process control state for this source; `None` when the host gave none.
    #[cfg(feature = "embed")]
    control_directory: Option<PathBuf>,
    #[cfg(feature = "embed")]
    trust_mode: crate::embed::parity::source_options::ProjectConfigTrustMode,
    state: std::sync::Mutex<EmbeddedRuntimeState>,
    change_wake: Condvar,
    #[cfg(feature = "embed")]
    refresh_snapshot: std::sync::Mutex<Option<Arc<super::embed_query::EmbeddedQuerySnapshot>>>,
    #[cfg(feature = "embed")]
    graph_leases: std::sync::Mutex<HashMap<u64, GraphLeaseEntry>>,
    #[cfg(feature = "embed")]
    next_graph_lease: AtomicU64,
    control: std::sync::Mutex<WorkerControl>,
    wake: Condvar,
    worker: std::sync::Mutex<Option<std::thread::JoinHandle<()>>>,
    shutdown_started: AtomicBool,
    progress: Arc<crate::live_index::store::ReloadProgressSink>,
}

/// Original selected state child. Parked between operations so an idle source
/// does not hold Windows directory handles, while every reopen checks identity.
#[cfg(feature = "embed")]
#[derive(Clone)]
pub(super) struct AdmittedStateAnchor {
    lease: Arc<super::physical_root::PhysicalRootLease>,
    stable_key: [u8; 16],
}

#[cfg(feature = "embed")]
impl AdmittedStateAnchor {
    fn capture(
        placement: &StatePlacement,
        authority: &super::activation::ProjectSourceAuthority,
    ) -> Result<Option<Self>, EmbeddedOpenError> {
        let opened = match placement {
            StatePlacement::MemoryOnly { .. } => return Ok(None),
            StatePlacement::ProjectLocal { .. } => authority
                .with_source_anchor_read(|root| {
                    root.child_directory(std::path::Path::new(".symforge"), false)
                })
                .map_err(|_| EmbeddedOpenError::AdmissionUnavailable)?,
            StatePlacement::UserLocal { directory, .. } => {
                super::physical_root::PhysicalRootLease::take(directory.as_path())
            }
        };
        let stable_key = opened
            .opened_stable_key()
            .ok_or(EmbeddedOpenError::AdmissionUnavailable)?;
        Ok(Some(Self {
            lease: Arc::new(opened.parked()),
            stable_key,
        }))
    }

    pub(super) fn lease(&self) -> &super::physical_root::PhysicalRootLease {
        &self.lease
    }

    pub(super) fn stable_key(&self) -> [u8; 16] {
        self.stable_key
    }
}

impl std::fmt::Debug for EmbeddedBinding {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("EmbeddedBinding")
            .field("identity", &self.identity)
            .field("root", &self.root)
            .field("state", &self.state.lock().expect("embedded state mutex"))
            .finish_non_exhaustive()
    }
}

impl EmbeddedBinding {
    #[allow(clippy::too_many_arguments)]
    fn new(
        identity: EmbeddedIdentity,
        key: ProjectKey,
        root: PathBuf,
        state_placement: StatePlacement,
        runtime: super::activation::ProjectRuntimeHandle,
        #[cfg(feature = "embed")] authority: Arc<super::activation::ProjectSourceAuthority>,
        #[cfg(feature = "embed")] state_anchor: Option<AdmittedStateAnchor>,
        #[cfg(feature = "embed")] restored_mtimes: Option<HashMap<String, u64>>,
        #[cfg(feature = "embed")] open_reset: Option<
            crate::embed::parity::source_options::SnapshotResetReceipt,
        >,
        #[cfg(feature = "embed")] control_directory: Option<PathBuf>,
        #[cfg(feature = "embed")]
        trust_mode: crate::embed::parity::source_options::ProjectConfigTrustMode,
    ) -> Arc<Self> {
        Arc::new(Self {
            identity,
            key,
            root,
            state_placement,
            runtime,
            #[cfg(feature = "embed")]
            authority,
            #[cfg(feature = "embed")]
            state_anchor,
            #[cfg(feature = "embed")]
            restored_mtimes: std::sync::Mutex::new(restored_mtimes),
            #[cfg(feature = "embed")]
            git_view: std::sync::Mutex::new(None),
            #[cfg(feature = "embed")]
            temporal_cache: Arc::default(),
            #[cfg(feature = "embed")]
            impact_symbols: Default::default(),
            #[cfg(feature = "embed")]
            stel_store: Default::default(),
            #[cfg(feature = "embed")]
            open_reset: open_reset.clone(),
            #[cfg(feature = "embed")]
            control_directory,
            #[cfg(feature = "embed")]
            trust_mode,
            state: std::sync::Mutex::new(EmbeddedRuntimeState {
                phase: super::public_api::SourceRuntimePhase::Loading,
                current_publication_identity: None,
                observer_epoch: 0,
                source_version: 0,
                change_revision: 0,
                #[cfg(feature = "embed")]
                lifecycle_epoch: 0,
            }),
            change_wake: Condvar::new(),
            #[cfg(feature = "embed")]
            refresh_snapshot: std::sync::Mutex::new(None),
            #[cfg(feature = "embed")]
            graph_leases: std::sync::Mutex::new(HashMap::new()),
            #[cfg(feature = "embed")]
            next_graph_lease: AtomicU64::new(1),
            control: std::sync::Mutex::new(WorkerControl {
                #[cfg(feature = "embed")]
                reset_pending: open_reset.is_some(),
                ..WorkerControl::default()
            }),
            wake: Condvar::new(),
            worker: std::sync::Mutex::new(None),
            shutdown_started: AtomicBool::new(false),
            progress: crate::live_index::store::ReloadProgressSink::new(),
        })
    }

    fn start(self: &Arc<Self>) -> std::io::Result<()> {
        let worker_binding = Arc::clone(self);
        let worker = std::thread::Builder::new()
            .name(format!("symforge-embed-{}", self.identity.raw()))
            .spawn(move || worker_binding.run())?;
        *self.worker.lock().expect("embedded worker mutex") = Some(worker);
        Ok(())
    }

    fn run(&self) {
        {
            let mut state = self.state.lock().expect("embedded state mutex");
            state.observer_epoch = 1;
        }

        #[cfg(feature = "embed")]
        let restored = self
            .restored_mtimes
            .lock()
            .expect("embedded restored seed mutex")
            .take();
        #[cfg(feature = "embed")]
        let mut observed_fingerprint = if let Some(mtimes) = restored {
            crate::live_index::persist::background_verify_bound(
                self.runtime.data_plane(),
                &self.root,
                &mtimes,
                &self.authority,
                || self.shutdown_started.load(Ordering::Acquire),
            );
            self.publish_observed_current()
        } else {
            self.reload_and_publish()
        };
        #[cfg(not(feature = "embed"))]
        let mut observed_fingerprint = self.reload_and_publish();
        self.complete_pending_reset();
        loop {
            let mut control = self.control.lock().expect("embedded control mutex");
            let (next, _) = self
                .wake
                .wait_timeout_while(control, EMBED_OBSERVER_POLL, |control| {
                    !control.stop && !control.refresh_requested
                })
                .expect("embedded control mutex");
            control = next;
            if control.stop {
                break;
            }
            let explicit_refresh = std::mem::take(&mut control.refresh_requested);
            drop(control);
            #[cfg(feature = "embed")]
            {
                let mut state = self.state.lock().expect("embedded state mutex");
                self.prune_graph_leases(&mut state);
            }

            let next_fingerprint = self.observe_fingerprint();
            if self.shutdown_started.load(Ordering::Acquire) {
                break;
            }
            let disk_changed = match (&observed_fingerprint, &next_fingerprint) {
                (Some(previous), Some(current)) => previous != current,
                (None, Some(_)) | (Some(_), None) => true,
                (None, None) => false,
            };
            let blocked = self.state.lock().expect("embedded state mutex").phase
                == super::public_api::SourceRuntimePhase::Blocked;
            if explicit_refresh || disk_changed || blocked {
                self.set_phase(super::public_api::SourceRuntimePhase::Refreshing);
                if self.wait_refresh_visibility_or_stop() {
                    break;
                }
                observed_fingerprint = self.reload_and_publish();
                if self.shutdown_started.load(Ordering::Acquire) {
                    break;
                }
                self.complete_pending_reset();
            } else {
                observed_fingerprint = next_fingerprint;
            }
        }
        self.set_phase(super::public_api::SourceRuntimePhase::Stopped);
        #[cfg(feature = "embed")]
        self.git_view
            .lock()
            .expect("embedded Git view mutex")
            .take();
    }

    /// Record the `index_folder` reset generation once a reload after the
    /// reset has published Current; otherwise keep it pending for the next.
    fn complete_pending_reset(&self) {
        let mut control = self.control.lock().expect("embedded control mutex");
        if !control.reset_pending {
            return;
        }
        let current = self.state.lock().expect("embedded state mutex").phase
            == super::public_api::SourceRuntimePhase::Current;
        if current {
            control.reset_pending = false;
            drop(control);
            self.runtime.data_plane().mark_index_folder_reset();
        }
    }

    fn wait_refresh_visibility_or_stop(&self) -> bool {
        let control = self.control.lock().expect("embedded control mutex");
        let (control, _) = self
            .wake
            .wait_timeout_while(control, REFRESHING_VISIBILITY_WINDOW, |control| {
                !control.stop
            })
            .expect("embedded control mutex");
        control.stop
    }

    fn reload_and_publish(&self) -> Option<String> {
        #[cfg(feature = "embed")]
        if self.authority.verify_physical_root_anchor().is_err() {
            self.set_blocked();
            return None;
        }
        self.progress.reset();
        let _progress = crate::live_index::store::register_reload_progress(
            &self.root,
            Arc::clone(&self.progress),
        );
        let exclusions = crate::discovery::SourceExclusions::for_state_placement(
            &self.root,
            &self.state_placement,
        );
        let result = self.runtime.data_plane().refresh_bound_tree_cancellable(
            &self.root,
            self.state_placement.directory().cloned(),
            exclusions,
            &self.shutdown_started,
        );
        if let Err(error) = result {
            if self.shutdown_started.load(Ordering::Acquire)
                || crate::live_index::store::reload_was_cancelled(&error)
            {
                return None;
            }
            self.set_blocked();
            return None;
        }

        self.publish_observed_current()
    }

    /// MCP's synchronous exact-path freshen before a targeted read
    /// (`freshen_exact_path_for_targeted_retrieval`): re-admit one changed
    /// path through the shared single-file seam and publish the result as the
    /// next Current publication, so the read captured after it serves the
    /// bytes on disk. Only a Current source is freshened; every other phase
    /// belongs to the worker, and the capture that follows refuses it.
    // ponytail: the single-file seam reads by path beneath the bound root, not
    // through the original-root capability; a replaced root is caught after the
    // fact because every served read re-verifies its bytes through that
    // capability and refuses a mismatch as a stale publication.
    #[cfg(feature = "embed")]
    fn freshen_exact_path(
        &self,
        relative_path: &str,
    ) -> Result<(), super::guidance::freshen::TargetedFreshenRefusal> {
        if self.shutdown_started.load(Ordering::Acquire)
            || self.authority.verify_physical_root_anchor().is_err()
            || self.state.lock().expect("embedded state mutex").phase
                != super::public_api::SourceRuntimePhase::Current
        {
            return Ok(());
        }
        #[cfg(test)]
        if let Some(hook) =
            refresh_lifecycle_tests::BEFORE_FRESHEN_GENERATION.with(|hook| hook.take())
        {
            hook();
        }
        let shared = self.runtime.data_plane();
        let expected_gen = shared.current_project_generation();
        if super::guidance::freshen::freshen_exact_path(
            shared,
            expected_gen,
            &self.root,
            &self.authority,
            relative_path,
        )? {
            self.publish_freshened();
        }
        Ok(())
    }

    /// MCP `analyze_file_impact`'s re-admission and symbol diff on a Current
    /// source, publishing whatever it indexed as the next Current publication
    /// exactly as the targeted freshen does.
    #[cfg(feature = "embed")]
    fn analyze_file_impact(
        &self,
        request: &crate::embed::parity::file_impact::FileImpactRequest,
        stop: &dyn Fn() -> Result<(), crate::embed::parity::QueryRefusalKind>,
    ) -> Result<super::embed_file_impact::FileImpactAdmission, crate::embed::parity::QueryRefusalKind>
    {
        if self.shutdown_started.load(Ordering::Acquire)
            || self.authority.verify_physical_root_anchor().is_err()
            || self.state.lock().expect("embedded state mutex").phase
                != super::public_api::SourceRuntimePhase::Current
        {
            return Err(crate::embed::parity::QueryRefusalKind::SourceUnavailable);
        }
        let shared = self.runtime.data_plane();
        let before = shared.published_generation().publication_generation;
        let result = super::embed_file_impact::admit(
            shared,
            &self.root,
            &self.authority,
            &self.impact_symbols,
            request,
            stop,
        );
        if shared.published_generation().publication_generation != before {
            self.publish_freshened();
        }
        result
    }

    /// Advance the Current publication to the data plane's after a freshen,
    /// unless the worker has taken the source out of Current meanwhile.
    #[cfg(feature = "embed")]
    fn publish_freshened(&self) {
        let mut state = self.state.lock().expect("embedded state mutex");
        let published = self.runtime.data_plane().published_generation();
        if self.shutdown_started.load(Ordering::Acquire)
            || state.phase != super::public_api::SourceRuntimePhase::Current
            || !matches!(published.freshness.as_ref(), FreshnessStatus::Current)
        {
            return;
        }
        state.source_version = state.source_version.saturating_add(1).max(1);
        state.current_publication_identity = Some(format!(
            "embed-publication-{}-{}",
            self.identity.raw(),
            published.publication_generation
        ));
        self.advance_change(&mut state);
    }

    fn publish_observed_current(&self) -> Option<String> {
        #[cfg(feature = "embed")]
        if self.authority.verify_physical_root_anchor().is_err() {
            self.set_blocked();
            return None;
        }
        if self.shutdown_started.load(Ordering::Acquire) {
            return None;
        }

        let Some(fingerprint) = self.observe_fingerprint() else {
            if self.shutdown_started.load(Ordering::Acquire) {
                return None;
            }
            self.set_blocked();
            return None;
        };
        #[cfg(all(test, feature = "embed"))]
        if let Some(hook) = refresh_lifecycle_tests::BEFORE_OBSERVED_STATE.with(|hook| hook.take())
        {
            hook();
        }
        let mut state = self.state.lock().expect("embedded state mutex");
        if self.shutdown_started.load(Ordering::Acquire) {
            return None;
        }
        let published = self.runtime.data_plane().published_generation();
        if !matches!(published.freshness.as_ref(), FreshnessStatus::Current) {
            drop(state);
            self.set_blocked();
            return Some(fingerprint);
        }
        state.source_version = state.source_version.saturating_add(1).max(1);
        state.current_publication_identity = Some(format!(
            "embed-publication-{}-{}",
            self.identity.raw(),
            published.publication_generation
        ));
        state.phase = super::public_api::SourceRuntimePhase::Current;
        #[cfg(feature = "embed")]
        {
            *self
                .refresh_snapshot
                .lock()
                .expect("refresh snapshot mutex") = None;
        }
        self.advance_change(&mut state);
        Some(fingerprint)
    }

    fn observe_fingerprint(&self) -> Option<String> {
        if self.shutdown_started.load(Ordering::Acquire) {
            return None;
        }
        #[cfg(feature = "embed")]
        self.authority.verify_physical_root_anchor().ok()?;
        let exclusions = crate::discovery::SourceExclusions::for_state_placement(
            &self.root,
            &self.state_placement,
        );
        let plan = crate::discovery::scout_repository_with_exclusions_cancellable(
            &self.root,
            &exclusions,
            &self.shutdown_started,
        )
        .ok()?;
        if self.shutdown_started.load(Ordering::Acquire) {
            return None;
        }
        #[cfg(feature = "embed")]
        self.authority.verify_physical_root_anchor().ok()?;
        Some(crate::hash::digest_hex(format!("{plan:?}").as_bytes()))
    }

    #[cfg(feature = "embed")]
    fn complete_query_snapshot(
        &self,
        state: &EmbeddedRuntimeState,
        normalized: &[u8],
    ) -> Result<super::embed_query::EmbeddedQuerySnapshot, super::public_api::EmbedSourceRefusal>
    {
        use super::public_api::{
            OperationKind, RetryAdvice, SourceRefusalKind, SourceRuntimePhase,
        };
        let refuse = |kind, retry| {
            super::public_api::bound_source_refusal(
                kind,
                OperationKind::IndexCensus,
                retry,
                normalized,
            )
        };
        if self.shutdown_started.load(Ordering::Acquire)
            || matches!(
                state.phase,
                SourceRuntimePhase::Stopping | SourceRuntimePhase::Stopped
            )
        {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::Never,
            ));
        }
        let index = self
            .runtime
            .acquire()
            .map_err(|_| refuse(SourceRefusalKind::AdmissionUnavailable, RetryAdvice::Never))?;
        let authority = Arc::clone(&self.authority);
        authority
            .verify_physical_root_anchor()
            .map_err(|_| refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::Never))?;
        if state.phase == SourceRuntimePhase::Refreshing {
            return self
                .refresh_snapshot
                .lock()
                .expect("refresh snapshot mutex")
                .as_ref()
                .filter(|snapshot| snapshot.lifecycle_epoch == state.lifecycle_epoch)
                .map(|snapshot| (**snapshot).clone())
                .ok_or_else(|| refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::OnEvent));
        }
        if state.phase != SourceRuntimePhase::Current {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::OnEvent,
            ));
        }
        let authority_publication = authority
            .current_publication()
            .ok_or_else(|| refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::OnEvent))?;
        let source_set = index.published_source_set();
        let generation = source_set.current_generation();
        let publication_identity = format!(
            "embed-publication-{}-{}",
            self.identity.raw(),
            generation.publication_generation,
        );
        if state.current_publication_identity.as_deref() != Some(&publication_identity)
            || !matches!(generation.freshness.as_ref(), FreshnessStatus::Current)
            || authority.current_publication() != Some(authority_publication)
        {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::OnEvent,
            ));
        }
        if self.shutdown_started.load(Ordering::Acquire) {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::Never,
            ));
        }
        let binding_identity = format!("source-{}", self.identity.raw());
        let serving_publication_identity = super::embed_query::serving_publication_identity(
            &binding_identity,
            &publication_identity,
            state.source_version,
        );
        Ok(super::embed_query::EmbeddedQuerySnapshot {
            root: self.root.clone(),
            project_state: self.state_placement.directory().cloned(),
            state_dir: self
                .state_placement
                .directory()
                .map(|directory| directory.as_path().to_path_buf()),
            source_set,
            generation,
            binding_identity,
            publication_identity,
            serving_publication_identity,
            source_version: state.source_version,
            lifecycle_epoch: state.lifecycle_epoch,
            source_phase: SourceRuntimePhase::Current,
            authority_publication,
            authority,
            state_anchor: self.state_anchor.clone(),
            temporal_cache: Arc::clone(&self.temporal_cache),
            control_directory: self.control_directory.clone(),
            trust_mode: self.trust_mode,
        })
    }

    #[cfg(feature = "embed")]
    fn prune_graph_leases(&self, state: &mut EmbeddedRuntimeState) {
        let now = std::time::Instant::now();
        let mut leases = self.graph_leases.lock().expect("graph lease mutex");
        let was_full = leases.len() >= 8;
        leases.retain(|_, entry| entry.expires_at > now);
        if was_full && leases.len() < 8 {
            self.advance_change(state);
        }
    }

    fn advance_change(&self, state: &mut EmbeddedRuntimeState) {
        state.change_revision = state.change_revision.wrapping_add(1);
        self.change_wake.notify_all();
    }

    fn set_phase(&self, phase: super::public_api::SourceRuntimePhase) {
        let mut state = self.state.lock().expect("embedded state mutex");
        if self.shutdown_started.load(Ordering::Acquire)
            && !matches!(
                phase,
                super::public_api::SourceRuntimePhase::Stopping
                    | super::public_api::SourceRuntimePhase::Stopped
            )
        {
            return;
        }
        if state.phase == phase {
            return;
        }
        #[cfg(feature = "embed")]
        if phase == super::public_api::SourceRuntimePhase::Refreshing
            && state.phase == super::public_api::SourceRuntimePhase::Current
        {
            let snapshot = self
                .complete_query_snapshot(&state, b"refresh-snapshot")
                .ok()
                .map(|mut snapshot| {
                    snapshot.source_phase = super::public_api::SourceRuntimePhase::Refreshing;
                    Arc::new(snapshot)
                });
            *self
                .refresh_snapshot
                .lock()
                .expect("refresh snapshot mutex") = snapshot;
        }
        #[cfg(feature = "embed")]
        if matches!(
            phase,
            super::public_api::SourceRuntimePhase::Current
                | super::public_api::SourceRuntimePhase::Blocked
                | super::public_api::SourceRuntimePhase::Stopping
                | super::public_api::SourceRuntimePhase::Stopped
        ) {
            *self
                .refresh_snapshot
                .lock()
                .expect("refresh snapshot mutex") = None;
        }
        state.phase = phase;
        self.advance_change(&mut state);
        if matches!(
            phase,
            super::public_api::SourceRuntimePhase::Blocked
                | super::public_api::SourceRuntimePhase::Stopping
                | super::public_api::SourceRuntimePhase::Stopped
        ) {
            #[cfg(feature = "embed")]
            {
                state.lifecycle_epoch = state.lifecycle_epoch.wrapping_add(1);
                self.graph_leases.lock().expect("graph lease mutex").clear();
            }
        }
    }

    fn set_blocked(&self) {
        let mut state = self.state.lock().expect("embedded state mutex");
        if self.shutdown_started.load(Ordering::Acquire) {
            return;
        }
        if state.phase != super::public_api::SourceRuntimePhase::Blocked {
            state.phase = super::public_api::SourceRuntimePhase::Blocked;
            state.current_publication_identity = None;
            #[cfg(feature = "embed")]
            {
                state.lifecycle_epoch = state.lifecycle_epoch.wrapping_add(1);
            }
            self.advance_change(&mut state);
        }
        #[cfg(feature = "embed")]
        {
            *self
                .refresh_snapshot
                .lock()
                .expect("refresh snapshot mutex") = None;
            self.graph_leases.lock().expect("graph lease mutex").clear();
        }
    }

    fn runtime_view(&self) -> super::public_api::SourceRuntimeView {
        let state = self.state.lock().expect("embedded state mutex").clone();
        super::public_api::SourceRuntimeView {
            binding_identity: format!("source-{}", self.identity.raw()),
            current_publication_identity: state.current_publication_identity,
            observer_epoch: state.observer_epoch,
            phase: state.phase,
            source_version: state.source_version,
        }
    }

    fn current_claim(
        &self,
        operation: crate::lifecycle_identity::OperationKind,
        normalized_arguments: &[u8],
    ) -> Result<CurrentEmbedClaim, super::public_api::EmbedSourceRefusal> {
        let state = self.state.lock().expect("embedded state mutex");
        if state.phase != super::public_api::SourceRuntimePhase::Current {
            let retry = match state.phase {
                super::public_api::SourceRuntimePhase::Blocked => {
                    crate::lifecycle_identity::RetryAdvice::Operator
                }
                super::public_api::SourceRuntimePhase::Stopped
                | super::public_api::SourceRuntimePhase::Stopping => {
                    crate::lifecycle_identity::RetryAdvice::Never
                }
                _ => crate::lifecycle_identity::RetryAdvice::OnEvent,
            };
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                operation,
                retry,
                normalized_arguments,
            ));
        }
        let publication_identity = state
            .current_publication_identity
            .clone()
            .expect("Current embedded source has a publication identity");
        Ok(CurrentEmbedClaim {
            binding_identity: format!("source-{}", self.identity.raw()),
            publication_identity,
            source_version: state.source_version,
        })
    }

    fn request_refresh(&self, reset: bool) -> Option<u64> {
        let state = self.state.lock().expect("embedded state mutex");
        if matches!(
            state.phase,
            super::public_api::SourceRuntimePhase::Stopped
                | super::public_api::SourceRuntimePhase::Stopping
        ) {
            return None;
        }
        let version = state.source_version;
        drop(state);
        let mut control = self.control.lock().expect("embedded control mutex");
        control.refresh_requested = true;
        control.reset_pending |= reset;
        self.wake.notify_all();
        Some(version)
    }

    fn shutdown(&self) -> (u64, u64) {
        if self.shutdown_started.swap(true, Ordering::AcqRel) {
            let version = self
                .state
                .lock()
                .expect("embedded state mutex")
                .source_version;
            return (version, 0);
        }
        self.set_phase(super::public_api::SourceRuntimePhase::Stopping);
        {
            let mut control = self.control.lock().expect("embedded control mutex");
            control.stop = true;
            self.wake.notify_all();
        }
        let worker = self.worker.lock().expect("embedded worker mutex").take();
        // Factory mutex is already dropped by close_one/shutdown_owner.
        // Signal before join so an unrelated open can race the parked worker.
        #[cfg(feature = "__test-internals")]
        notify_join_entered(&self.root);
        let joined = worker
            .map(|worker| {
                let _ = worker.join();
                1
            })
            .unwrap_or(0);
        self.set_phase(super::public_api::SourceRuntimePhase::Stopped);
        if let Err(refusal) = super::activation::process_project_registry().stop(&self.key) {
            tracing::debug!(?refusal, "embedded admission stop refused");
        }
        let version = self
            .state
            .lock()
            .expect("embedded state mutex")
            .source_version;
        (version, joined)
    }
}

struct CurrentEmbedClaim {
    binding_identity: String,
    publication_identity: String,
    source_version: u64,
}

fn normalized_path_prefix(prefix: Option<&str>) -> Option<String> {
    prefix.map(|prefix| {
        prefix
            .replace('\\', "/")
            .trim_start_matches("./")
            .trim_end_matches('/')
            .to_string()
    })
}

fn path_matches_prefix(path: &str, prefix: Option<&str>) -> bool {
    match normalized_path_prefix(prefix) {
        None => true,
        Some(prefix) if prefix.is_empty() => true,
        Some(prefix) => crate::live_index::search::PathScope::prefix(prefix).matches(path),
    }
}

fn knowledge_lifecycle_label(
    lifecycle: crate::live_index::knowledge_authority::KnowledgeLifecycle,
) -> String {
    format!("{lifecycle:?}").to_ascii_lowercase()
}

fn knowledge_coverage_label(
    coverage: &crate::live_index::knowledge_bridge::DerivedCoverage,
) -> String {
    match coverage {
        crate::live_index::knowledge_bridge::DerivedCoverage::Complete => "complete".to_string(),
        crate::live_index::knowledge_bridge::DerivedCoverage::Loading => "loading".to_string(),
        crate::live_index::knowledge_bridge::DerivedCoverage::Truncated { .. } => {
            "truncated".to_string()
        }
    }
}

fn knowledge_withheld_label(
    reason: crate::live_index::knowledge_retrieve::KnowledgeWithheldReason,
) -> String {
    match reason {
        crate::live_index::knowledge_retrieve::KnowledgeWithheldReason::PolicyWithheld => {
            "policy_withheld".to_string()
        }
    }
}

fn bounded_preview(line: &str) -> String {
    const MAX_PREVIEW_CHARS: usize = 500;
    let mut chars = line.chars();
    let preview: String = chars.by_ref().take(MAX_PREVIEW_CHARS).collect();
    if chars.next().is_some() {
        format!("{preview}…")
    } else {
        preview
    }
}

impl EmbeddedSourceFactory {
    /// A registration with nothing open.
    pub fn new() -> Arc<Self> {
        Arc::new(Self::default())
    }

    /// Test-internal dark registration retained for the Slice-2 ownership
    /// oracles. Production opens always use [`Self::open_bound`].
    #[cfg(feature = "__test-internals")]
    pub fn open(self: &Arc<Self>, key: ProjectKey) -> Result<EmbeddedSourceHandle, EmbedRefusal> {
        let mut open = self.open.lock().expect("embedded registration mutex");
        if let Some(held_by) = open.get(&key) {
            return Err(EmbedRefusal::SourceAlreadyOpen {
                held_by: held_by.identity,
            });
        }
        let identity = EmbeddedIdentity::fresh();
        open.insert(
            key.clone(),
            OpenEmbeddedSource {
                identity,
                owner: None,
                opening: false,
                binding: None,
            },
        );
        self.shutdown.store(false, Ordering::Release);
        Ok(EmbeddedSourceHandle {
            identity,
            key,
            registration: Arc::clone(self),
            binding: None,
            closed: AtomicBool::new(false),
            _not_unwind_safe: std::marker::PhantomData,
        })
    }

    /// Open `binding`, yielding the sole handle for it and starting its worker.
    ///
    /// Refuses if a handle is already live for this key. Handing out a second
    /// handle would let one close while the other still believes it holds an
    /// open source.
    pub(crate) fn open_bound(
        self: &Arc<Self>,
        binding: RootBinding,
        state_placement: StatePlacement,
        owner: EmbeddedIdentity,
    ) -> Result<EmbeddedSourceHandle, EmbeddedOpenError> {
        self.open_bound_with_reset(
            binding,
            state_placement,
            owner,
            false,
            None,
            #[cfg(feature = "embed")]
            Default::default(),
        )
    }

    /// `open_bound` plus the MCP `index_folder` snapshot reset. A failed reset
    /// refuses the open as admission-unavailable before anything is restored.
    pub(crate) fn open_bound_with_reset(
        self: &Arc<Self>,
        binding: RootBinding,
        state_placement: StatePlacement,
        owner: EmbeddedIdentity,
        reset_snapshot_state: bool,
        control_directory: Option<PathBuf>,
        #[cfg(feature = "embed")]
        trust_mode: crate::embed::parity::source_options::ProjectConfigTrustMode,
    ) -> Result<EmbeddedSourceHandle, EmbeddedOpenError> {
        let key = ProjectKey::new(&binding.root_id.0);
        let identity = EmbeddedIdentity::fresh();
        {
            let mut open = self.open.lock().expect("embedded registration mutex");
            if open.contains_key(&key) {
                return Err(EmbeddedOpenError::SourceAlreadyOpen);
            }
            open.insert(
                key.clone(),
                OpenEmbeddedSource {
                    identity,
                    owner: Some(owner),
                    opening: true,
                    binding: None,
                },
            );
            self.shutdown.store(false, Ordering::Release);
        }

        #[cfg(feature = "__test-internals")]
        pause_open_after_reserve_for_test(&key);

        let mut rollback = OpenRollback::reserve(Arc::clone(self), key.clone(), identity);
        let admission = super::activation::admit_project_with_outcome(
            super::process_runtime::SurfaceKind::Embed,
            &binding.canonical_root,
            &binding.root_id.0,
            binding.access_mode,
            &state_placement,
        )
        .map_err(|_| EmbeddedOpenError::AdmissionUnavailable)?;
        #[cfg(feature = "embed")]
        let authority = {
            let candidate = super::activation::project_source_authority(&binding.canonical_root);
            let admitted_root = admission
                .slot()
                .binding()
                .map_err(|_| EmbeddedOpenError::AdmissionUnavailable)?
                .physical_root();
            if candidate.admission_binding().physical_root() != admitted_root {
                return Err(EmbeddedOpenError::AdmissionUnavailable);
            }
            candidate
        };
        #[cfg(feature = "embed")]
        let state_anchor = AdmittedStateAnchor::capture(&state_placement, &authority)?;
        // MCP `index_folder` reset: delete the snapshot scope after admission
        // and before restore, so the open cannot warm-load what was reset.
        #[cfg(feature = "embed")]
        let open_reset = if reset_snapshot_state {
            let report = crate::live_index::persist::reset_snapshot_state(
                &binding.canonical_root,
                &state_placement,
            )
            .map_err(|_| EmbeddedOpenError::AdmissionUnavailable)?;
            Some(crate::embed::parity::source_options::SnapshotResetReceipt::from_report(&report))
        } else {
            None
        };
        #[cfg(not(feature = "embed"))]
        let _ = (reset_snapshot_state, control_directory);
        #[cfg(feature = "embed")]
        let restored = super::embed_restore::load_admitted_snapshot(
            &binding.canonical_root,
            &state_placement,
            state_anchor.as_ref(),
            &authority,
        )
        .map_err(|_| EmbeddedOpenError::AdmissionUnavailable)?;
        #[cfg(feature = "embed")]
        let (index, restored_mtimes) = match restored {
            Some(seed) => (seed.index, Some(seed.mtimes)),
            None => (crate::live_index::store::LiveIndex::empty(), None),
        };
        #[cfg(not(feature = "embed"))]
        let index = crate::live_index::store::LiveIndex::empty();
        let runtime =
            super::activation::ProjectRuntimeHandle::bind_admitted(index, admission.into_slot());
        let source = EmbeddedBinding::new(
            identity,
            key.clone(),
            binding.canonical_root,
            state_placement,
            runtime,
            #[cfg(feature = "embed")]
            authority,
            #[cfg(feature = "embed")]
            state_anchor,
            #[cfg(feature = "embed")]
            restored_mtimes,
            #[cfg(feature = "embed")]
            open_reset,
            #[cfg(feature = "embed")]
            control_directory,
            #[cfg(feature = "embed")]
            trust_mode,
        );
        rollback.bind(Arc::clone(&source));
        if source.start().is_err() {
            return Err(EmbeddedOpenError::WorkerUnavailable);
        }
        #[cfg(feature = "__test-internals")]
        if take_panic_after_start_for_test(&key) {
            panic!("embedded open panic injected after worker start");
        }

        let promoted = {
            let mut open = self.open.lock().expect("embedded registration mutex");
            match open.get_mut(&key) {
                Some(reservation) if reservation.identity == identity && reservation.opening => {
                    reservation.opening = false;
                    reservation.binding = Some(Arc::clone(&source));
                    true
                }
                _ => false,
            }
        };
        if !promoted {
            return Err(EmbeddedOpenError::WorkerUnavailable);
        }
        rollback.commit();

        Ok(EmbeddedSourceHandle {
            identity,
            key,
            registration: Arc::clone(self),
            binding: Some(source),
            closed: AtomicBool::new(false),
            _not_unwind_safe: std::marker::PhantomData,
        })
    }

    /// How many sources are open.
    pub fn open_count(&self) -> usize {
        self.open.lock().expect("embedded registration mutex").len()
    }

    /// Whether the factory is currently shut down: the final owner closed and
    /// nothing has been opened since.
    pub fn has_shut_down(&self) -> bool {
        self.shutdown.load(Ordering::Acquire)
    }

    /// Close one source. Returns whether this call performed the shutdown.
    ///
    /// The registration entry stays until join finishes so a same-root reopen
    /// still refuses, but the mutex is not held across `join` — an unrelated
    /// root must be able to open while this worker is still unwinding.
    fn close_one(&self, key: &ProjectKey, identity: EmbeddedIdentity) -> (bool, bool, u64, u64) {
        let (matched, source) = {
            let open = self.open.lock().expect("embedded registration mutex");
            let matched = open
                .get(key)
                .is_some_and(|source| source.identity == identity);
            let source = open
                .get(key)
                .filter(|source| source.identity == identity)
                .and_then(|source| source.binding.as_ref().map(Arc::clone));
            (matched, source)
        };
        let (terminal_version, joined_workers) = source
            .as_ref()
            .map(|source| source.shutdown())
            .unwrap_or((0, 0));
        let (performed, final_owner) = if matched {
            let mut open = self.open.lock().expect("embedded registration mutex");
            if open
                .get(key)
                .is_some_and(|source| source.identity == identity)
            {
                open.remove(key);
                let final_owner = open.is_empty();
                if final_owner {
                    self.shutdown.store(true, Ordering::Release);
                }
                (true, final_owner)
            } else {
                (false, false)
            }
        } else {
            (false, false)
        };
        (performed, final_owner, terminal_version, joined_workers)
    }

    pub(crate) fn shutdown_owner(&self, owner: EmbeddedIdentity) -> EmbeddedShutdownReport {
        let closing: Vec<(ProjectKey, Option<Arc<EmbeddedBinding>>)> = {
            let open = self.open.lock().expect("embedded registration mutex");
            open.iter()
                .filter(|(_, source)| source.owner == Some(owner))
                .map(|(key, source)| (key.clone(), source.binding.clone()))
                .collect()
        };
        let mut closed_sources = 0u64;
        let mut joined_workers = 0u64;
        for (_, binding) in &closing {
            let joined = binding
                .as_ref()
                .map(|binding| binding.shutdown().1)
                .unwrap_or(0);
            closed_sources = closed_sources.saturating_add(1);
            joined_workers = joined_workers.saturating_add(joined);
        }
        let mut open = self.open.lock().expect("embedded registration mutex");
        for (key, _) in &closing {
            if open
                .get(key)
                .is_some_and(|source| source.owner == Some(owner))
            {
                open.remove(key);
            }
        }
        self.shutdown.store(open.is_empty(), Ordering::Release);
        EmbeddedShutdownReport {
            closed_sources,
            joined_workers,
        }
    }
}

#[cfg(feature = "embed")]
impl super::public_api::ProcessRuntimeApi {
    /// Open a source with state placement selected by the trusted host. These
    /// options are Rust capabilities, never fields decoded from a room query.
    pub fn open_embedded_source_with_options(
        &self,
        spec: super::public_api::EmbeddedSourceSpec,
        options: crate::embed::parity::source_options::EmbeddedOpenOptions,
    ) -> Result<EmbeddedSourceHandle, super::public_api::EmbedSourceRefusal> {
        use super::public_api::{
            OperationKind, RetryAdvice, SourceRefusalKind, bound_source_refusal,
        };
        use crate::embed::parity::source_options::{StateSelectionError, select_state_placement};
        let normalized = format!(
            "current_worktree={:?};state={:?};allow_protected_root={};reset_snapshot_state={};replay_control_directory={:?};project_config_trust_mode={:?}",
            spec.root,
            options.state,
            options.allow_protected_root,
            options.reset_snapshot_state,
            options.replay_control_directory,
            options.project_config_trust_mode
        );
        let refuse = |kind, retry| {
            bound_source_refusal(
                kind,
                OperationKind::OpenEmbeddedSource,
                retry,
                normalized.as_bytes(),
            )
        };
        // MCP `index_folder` resolves an explicit root; without the override it
        // admits exactly what automatic resolution admits.
        let (candidate_source, request_mode) = if options.allow_protected_root {
            (
                crate::domain::RootCandidateSource::ExplicitIndexFolder,
                crate::domain::RootRequestMode::ExplicitIndexFolder {
                    allow_protected_root: true,
                },
            )
        } else {
            (
                crate::domain::RootCandidateSource::McpClientRoot,
                crate::domain::RootRequestMode::Automatic,
            )
        };
        let binding = match crate::discovery::resolve_root_candidate(
            &spec.root,
            candidate_source,
            request_mode,
        ) {
            crate::domain::RootResolution::Bound(binding) => binding,
            crate::domain::RootResolution::Unbound { .. } => {
                return Err(refuse(
                    SourceRefusalKind::InvalidSelection,
                    RetryAdvice::Operator,
                ));
            }
        };
        if options
            .replay_control_directory
            .as_deref()
            .is_some_and(|directory| !directory.is_absolute() || !directory.is_dir())
        {
            return Err(refuse(
                SourceRefusalKind::InvalidSelection,
                RetryAdvice::Operator,
            ));
        }
        let placement =
            select_state_placement(&binding, &options).map_err(|error| match error {
                StateSelectionError::InvalidSelection => {
                    refuse(SourceRefusalKind::InvalidSelection, RetryAdvice::Operator)
                }
                StateSelectionError::Unavailable => refuse(
                    SourceRefusalKind::AdmissionUnavailable,
                    RetryAdvice::Operator,
                ),
            })?;
        self.owner
            .factory()
            .open_bound_with_reset(
                binding,
                placement,
                self.owner.identity(),
                options.reset_snapshot_state,
                options
                    .replay_control_directory
                    .map(|directory| directory.join("embed-host")),
                options.project_config_trust_mode,
            )
            .map_err(|error| match error {
                EmbeddedOpenError::SourceAlreadyOpen => refuse(
                    SourceRefusalKind::SelectionUnavailable,
                    RetryAdvice::OnEvent,
                ),
                EmbeddedOpenError::AdmissionUnavailable => refuse(
                    SourceRefusalKind::AdmissionUnavailable,
                    RetryAdvice::Automatic,
                ),
                EmbeddedOpenError::WorkerUnavailable => {
                    refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::Automatic)
                }
            })
    }
}

#[derive(Debug)]
pub(crate) struct EmbeddedRuntimeOwner {
    identity: EmbeddedIdentity,
    factory: Arc<EmbeddedSourceFactory>,
}

impl EmbeddedRuntimeOwner {
    pub(crate) fn new(factory: Arc<EmbeddedSourceFactory>) -> Arc<Self> {
        Arc::new(Self {
            identity: EmbeddedIdentity::fresh(),
            factory,
        })
    }

    pub(crate) fn factory(&self) -> &Arc<EmbeddedSourceFactory> {
        &self.factory
    }

    pub(crate) fn identity(&self) -> EmbeddedIdentity {
        self.identity
    }

    pub(crate) fn shutdown(&self) -> EmbeddedShutdownReport {
        self.factory.shutdown_owner(self.identity)
    }
}

impl Drop for EmbeddedRuntimeOwner {
    fn drop(&mut self) {
        self.shutdown();
    }
}

/// The sole handle to one embedded source.
///
/// Not `Clone`: sole ownership is the invariant, and a clonable handle would
/// mean two owners could each believe they hold the source.
#[derive(Debug)]
pub struct EmbeddedSourceHandle {
    identity: EmbeddedIdentity,
    key: ProjectKey,
    registration: Arc<EmbeddedSourceFactory>,
    binding: Option<Arc<EmbeddedBinding>>,
    closed: AtomicBool,
    // T049: the contract pins the handle NOT UnwindSafe/RefUnwindSafe.
    _not_unwind_safe: super::public_api::NotUnwindSafe,
}

impl EmbeddedSourceHandle {
    /// Prepare a bounded disposable Git view using a trusted host workspace.
    /// This lifecycle operation grants no room permission to prepare other state.
    #[cfg(feature = "embed")]
    pub fn prepare_git_view(
        &self,
        options: &crate::embed::parity::source_options::GitPreparationOptions,
        control: &crate::embed::parity::host::OperationControl,
    ) -> Result<
        crate::embed::parity::source_options::GitPreparationClaim,
        crate::embed::parity::source_options::GitPreparationRefusal,
    > {
        use crate::embed::parity::source_options::{
            GitPreparationRefusal, GitPreparationRefusalKind,
        };
        let unavailable = || GitPreparationRefusal {
            kind: GitPreparationRefusalKind::SourceUnavailable,
        };
        let snapshot = self
            .capture_query_snapshot(b"symforge.embed.git-preparation.v1")
            .map_err(|_| unavailable())?;
        let binding = self.binding.as_ref().ok_or_else(unavailable)?;
        let mut current = binding.git_view.lock().expect("embedded Git view mutex");
        let (prepared, claim) =
            super::embed_git::prepare(&snapshot, options, control, current.as_ref())?;
        let final_snapshot = self
            .capture_query_snapshot(b"symforge.embed.git-preparation.v1")
            .map_err(|_| unavailable())?;
        if final_snapshot.serving_publication_identity != snapshot.serving_publication_identity
            || binding.shutdown_started.load(Ordering::Acquire)
        {
            return Err(unavailable());
        }
        control.check().map_err(|stop| GitPreparationRefusal {
            kind: match stop {
                crate::embed::parity::host::OperationStop::Cancelled => {
                    GitPreparationRefusalKind::Cancelled
                }
                crate::embed::parity::host::OperationStop::DeadlineExceeded => {
                    GitPreparationRefusalKind::DeadlineExceeded
                }
            },
        })?;
        *current = Some(prepared);
        Ok(claim)
    }

    /// Open the current prepared Git view exactly as production does.
    #[cfg(all(feature = "embed", feature = "__test-internals"))]
    pub fn prepared_git_repository_for_test(&self) -> Option<git2::Repository> {
        let view = self.binding.as_ref()?.git_view.lock().ok()?.clone()?;
        view.repository().ok()
    }

    /// Run supported pure projections from the last complete publication while
    /// this source is refreshing. The claim retains that publication identity
    /// and records `Refreshing`; other requests are refused before freshening.
    #[cfg(feature = "embed")]
    pub fn query_allowing_refresh(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute_allowing_refresh(self, request, limits, None)
    }

    #[cfg(feature = "embed")]
    pub fn query_allowing_refresh_with_control(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
        control: &crate::embed::parity::host::OperationControl,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute_allowing_refresh(self, request, limits, Some(control))
    }

    #[cfg(feature = "embed")]
    pub fn query_with_graph_lease(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
        lease: &GraphPublicationLease,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute_with_graph_lease(self, request, limits, None, lease)
    }

    #[cfg(feature = "embed")]
    pub fn query_with_graph_lease_and_control(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
        lease: &GraphPublicationLease,
        control: &crate::embed::parity::host::OperationControl,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute_with_graph_lease(self, request, limits, Some(control), lease)
    }

    #[cfg(feature = "embed")]
    pub fn query(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute(self, request, limits)
    }

    /// MCP `validate_file_syntax`'s disk parse in any live phase, including
    /// while the source is not Current. Use [`Self::query`] with
    /// `QueryRequest::Syntax` for the indexed report of a Current publication.
    #[cfg(feature = "embed")]
    pub fn validate_syntax_from_disk(
        &self,
        path: &str,
        limits: crate::embed::parity::QueryLimits,
    ) -> Result<crate::embed::parity::DiskSyntaxObservation, super::embed_query::QueryRefusal> {
        super::embed_query::validate_syntax_from_disk(self, path, limits)
    }

    /// Execute with the host's deadline and shared cancellation signal.
    /// Stops are checked around engine calls and while projecting rows; a single
    /// parser/search call runs to its next safe checkpoint. The convenience
    /// `query` method imposes output bounds without choosing a host deadline.
    #[cfg(feature = "embed")]
    pub fn query_with_control(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
        control: &crate::embed::parity::host::OperationControl,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute_with_control(self, request, limits, control)
    }

    /// Create an independent context history and retrieval cache bound to this
    /// admitted source incarnation.
    #[cfg(feature = "embed")]
    pub fn new_query_session(
        &self,
    ) -> Result<crate::embed::parity::session::QuerySession, super::public_api::EmbedSourceRefusal>
    {
        let snapshot = self.capture_query_snapshot(b"symforge.embed.session.v1")?;
        Ok(super::embed_session::QuerySession::new(&snapshot))
    }

    /// Create a session with trusted bounds no larger than the engine defaults.
    #[cfg(feature = "embed")]
    pub fn new_query_session_with_limits(
        &self,
        limits: crate::embed::parity::session::SessionCacheLimits,
    ) -> Result<
        crate::embed::parity::session::QuerySession,
        crate::embed::parity::session::SessionCreationRefusal,
    > {
        use crate::embed::parity::session::{SessionCacheLimits, SessionCreationRefusal};
        let defaults = SessionCacheLimits::default();
        if limits.max_bytes > defaults.max_bytes || limits.max_entries > defaults.max_entries {
            return Err(SessionCreationRefusal::InvalidLimits);
        }
        let snapshot = self
            .capture_query_snapshot(b"symforge.embed.session.v1")
            .map_err(|_| SessionCreationRefusal::SourceUnavailable)?;
        Ok(super::embed_session::QuerySession::with_limits(
            &snapshot, limits,
        ))
    }

    /// Execute with explicit source-bound context history and optional host
    /// cancellation. A session from another source is refused.
    #[cfg(feature = "embed")]
    pub fn query_with_session(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
        session: &crate::embed::parity::session::QuerySession,
        control: Option<&crate::embed::parity::host::OperationControl>,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute_with_session(self, request, limits, session, control)
    }

    /// Execute with explicit host rights for optional derived-state preparation.
    /// Read-only queries use the default policy; a grant does not create state
    /// placement authority or change the source bound to this handle.
    #[cfg(feature = "embed")]
    pub fn query_with_policy(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
        policy: crate::embed::parity::QueryPolicy,
        session: Option<&crate::embed::parity::session::QuerySession>,
        control: Option<&crate::embed::parity::host::OperationControl>,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute_with_policy(self, request, limits, policy, session, control)
    }

    /// Run a trusted synchronous envelope check before committing read bookkeeping.
    /// The callback must not reenter this session and must not deliver the result
    /// before this method succeeds; cancellation is checked again after admission.
    #[cfg(feature = "embed")]
    pub(crate) fn query_with_policy_admitted(
        &self,
        request: &crate::embed::parity::QueryRequest,
        limits: crate::embed::parity::QueryLimits,
        policy: crate::embed::parity::QueryPolicy,
        session: Option<&crate::embed::parity::session::QuerySession>,
        control: Option<&crate::embed::parity::host::OperationControl>,
        admit: impl FnOnce(&super::embed_query::QueryClaim) -> bool,
    ) -> Result<super::embed_query::QueryClaim, super::embed_query::QueryRefusal> {
        super::embed_query::execute_with_policy_admitted(
            self, request, limits, policy, session, control, admit,
        )
    }

    /// Original admitted placement for verifying completed replay records while
    /// a refresh is in progress. This carries no query or mutation authority.
    #[cfg(feature = "embed")]
    pub(super) fn bound_replay_placement(&self) -> Option<(PathBuf, Option<PathBuf>)> {
        if self.closed.load(Ordering::Acquire) {
            return None;
        }
        let binding = self.binding.as_ref()?;
        let state = binding.state.lock().expect("embedded state mutex");
        if binding.shutdown_started.load(Ordering::Acquire)
            || !matches!(
                state.phase,
                super::public_api::SourceRuntimePhase::Loading
                    | super::public_api::SourceRuntimePhase::Current
                    | super::public_api::SourceRuntimePhase::Refreshing
            )
            || self.closed.load(Ordering::Acquire)
        {
            return None;
        }
        Some((
            binding.root.clone(),
            binding
                .state_placement
                .directory()
                .map(|directory| directory.as_path().to_path_buf()),
        ))
    }

    /// Original read capability for verifying completed postimages while the
    /// source refreshes. It never re-resolves authority from a path spelling.
    #[cfg(feature = "embed")]
    pub(super) fn bound_replay_authority(
        &self,
    ) -> Option<Arc<super::activation::ProjectSourceAuthority>> {
        self.bound_replay_placement()?;
        Some(Arc::clone(&self.binding.as_ref()?.authority))
    }

    #[cfg(feature = "embed")]
    pub(super) fn bound_state_anchor(&self) -> Option<AdmittedStateAnchor> {
        self.bound_replay_placement()?;
        self.binding.as_ref()?.state_anchor.clone()
    }

    /// Freshen one exact path before a targeted read; see the binding's
    /// `freshen_exact_path`.
    #[cfg(feature = "embed")]
    pub(super) fn freshen_exact_path(
        &self,
        relative_path: &str,
    ) -> Result<(), super::guidance::freshen::TargetedFreshenRefusal> {
        match &self.binding {
            Some(binding) if !self.closed.load(Ordering::Acquire) => {
                binding.freshen_exact_path(relative_path)
            }
            _ => Ok(()),
        }
    }

    /// MCP `analyze_file_impact`'s re-admission; see the binding's method.
    #[cfg(feature = "embed")]
    pub(super) fn analyze_file_impact(
        &self,
        request: &crate::embed::parity::file_impact::FileImpactRequest,
        stop: &dyn Fn() -> Result<(), crate::embed::parity::QueryRefusalKind>,
    ) -> Result<super::embed_file_impact::FileImpactAdmission, crate::embed::parity::QueryRefusalKind>
    {
        match &self.binding {
            Some(binding) if !self.closed.load(Ordering::Acquire) => {
                binding.analyze_file_impact(request, stop)
            }
            _ => Err(crate::embed::parity::QueryRefusalKind::SourceUnavailable),
        }
    }

    /// Internal capture of the Current publication or the retained complete
    /// snapshot while Refreshing. This is never a write permit.
    #[cfg(feature = "embed")]
    pub(super) fn capture_query_snapshot_allowing_refresh(
        &self,
        normalized: &[u8],
    ) -> Result<super::embed_query::EmbeddedQuerySnapshot, super::public_api::EmbedSourceRefusal>
    {
        use super::public_api::{OperationKind, RetryAdvice, SourceRefusalKind};
        let unavailable = || {
            super::public_api::bound_source_refusal(
                SourceRefusalKind::SourceUnavailable,
                OperationKind::IndexCensus,
                RetryAdvice::Never,
                normalized,
            )
        };
        if self.closed.load(Ordering::Acquire) {
            return Err(unavailable());
        }
        let binding = self.binding.as_ref().ok_or_else(unavailable)?;
        let state = binding.state.lock().expect("embedded state mutex");
        let snapshot = binding.complete_query_snapshot(&state, normalized)?;
        if self.closed.load(Ordering::Acquire) {
            return Err(unavailable());
        }
        Ok(snapshot)
    }

    #[cfg(feature = "embed")]
    pub(super) fn validate_refresh_snapshot(
        &self,
        lifecycle_epoch: u64,
        normalized: &[u8],
    ) -> Result<(), super::public_api::EmbedSourceRefusal> {
        use super::public_api::{
            OperationKind, RetryAdvice, SourceRefusalKind, SourceRuntimePhase,
        };
        let refuse = |kind, retry| {
            super::public_api::bound_source_refusal(
                kind,
                OperationKind::IndexCensus,
                retry,
                normalized,
            )
        };
        if self.closed.load(Ordering::Acquire) {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::Never,
            ));
        }
        let binding = self
            .binding
            .as_ref()
            .ok_or_else(|| refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::Never))?;
        let state = binding.state.lock().expect("embedded state mutex");
        if self.closed.load(Ordering::Acquire)
            || binding.shutdown_started.load(Ordering::Acquire)
            || matches!(
                state.phase,
                SourceRuntimePhase::Stopping | SourceRuntimePhase::Stopped
            )
        {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::Never,
            ));
        }
        binding
            .runtime
            .acquire()
            .map_err(|_| refuse(SourceRefusalKind::AdmissionUnavailable, RetryAdvice::Never))?;
        binding
            .authority
            .verify_physical_root_anchor()
            .map_err(|_| refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::Never))?;
        if lifecycle_epoch != state.lifecycle_epoch
            || !matches!(
                state.phase,
                SourceRuntimePhase::Current | SourceRuntimePhase::Refreshing
            )
        {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::OnEvent,
            ));
        }
        Ok(())
    }

    /// Pin one immutable graph publication for bounded pagination. Leases last at most 30 seconds and at most eight may be live; zero timeout creates an immediately expired lease. A lease can capture the last complete publication during refresh.
    #[cfg(feature = "embed")]
    pub fn begin_graph_publication_lease(
        &self,
        timeout: Duration,
    ) -> Result<GraphPublicationLease, super::public_api::EmbedSourceRefusal> {
        use super::public_api::{OperationKind, RetryAdvice, SourceRefusalKind};
        let normalized = b"begin-graph-publication-lease";
        let unavailable = || {
            super::public_api::bound_source_refusal(
                SourceRefusalKind::SourceUnavailable,
                OperationKind::IndexCensus,
                RetryAdvice::Never,
                normalized,
            )
        };
        if self.closed.load(Ordering::Acquire) {
            return Err(unavailable());
        }
        let binding = self.binding.as_ref().ok_or_else(unavailable)?;
        let mut state = binding.state.lock().expect("embedded state mutex");
        if self.closed.load(Ordering::Acquire) {
            return Err(unavailable());
        }
        let snapshot = binding.complete_query_snapshot(&state, normalized)?;
        binding.prune_graph_leases(&mut state);
        let mut leases = binding.graph_leases.lock().expect("graph lease mutex");
        if leases.len() >= 8 {
            return Err(super::public_api::bound_source_refusal(
                SourceRefusalKind::AdmissionUnavailable,
                OperationKind::IndexCensus,
                RetryAdvice::OnEvent,
                normalized,
            ));
        }
        let id = binding.next_graph_lease.fetch_add(1, Ordering::Relaxed);
        let duration = timeout.min(Duration::from_secs(30));
        let expires_at = std::time::Instant::now()
            .checked_add(duration)
            .unwrap_or_else(std::time::Instant::now);
        leases.insert(
            id,
            GraphLeaseEntry {
                expires_at,
                snapshot: Arc::new(snapshot),
            },
        );
        if self.closed.load(Ordering::Acquire) {
            leases.remove(&id);
            return Err(super::public_api::bound_source_refusal(
                SourceRefusalKind::SourceUnavailable,
                OperationKind::IndexCensus,
                RetryAdvice::Never,
                normalized,
            ));
        }
        if leases.len() == 8 {
            binding.change_wake.notify_all();
        }
        Ok(GraphPublicationLease {
            binding: Arc::downgrade(binding),
            id,
            source_id: self.identity.raw(),
            lifecycle_epoch: state.lifecycle_epoch,
        })
    }

    #[cfg(feature = "embed")]
    pub(super) fn capture_graph_lease_snapshot(
        &self,
        lease: &GraphPublicationLease,
    ) -> Result<super::embed_query::EmbeddedQuerySnapshot, crate::embed::parity::QueryRefusalKind>
    {
        use crate::embed::parity::QueryRefusalKind;
        let Some(binding) = self.binding.as_ref() else {
            return Err(QueryRefusalKind::StaleHandle);
        };
        if lease.source_id != self.identity.raw()
            || lease
                .binding
                .upgrade()
                .is_none_or(|leased| !Arc::ptr_eq(&leased, binding))
        {
            return Err(QueryRefusalKind::StaleHandle);
        }
        let mut state = binding.state.lock().expect("embedded state mutex");
        if self.closed.load(Ordering::Acquire)
            || binding.authority.verify_physical_root_anchor().is_err()
            || matches!(
                state.phase,
                super::public_api::SourceRuntimePhase::Blocked
                    | super::public_api::SourceRuntimePhase::Stopping
                    | super::public_api::SourceRuntimePhase::Stopped
            )
        {
            return Err(QueryRefusalKind::SourceUnavailable);
        }
        if binding.runtime.acquire().is_err() {
            return Err(QueryRefusalKind::AdmissionUnavailable);
        }
        if lease.lifecycle_epoch != state.lifecycle_epoch {
            return Err(QueryRefusalKind::SourceUnavailable);
        }
        binding.prune_graph_leases(&mut state);
        binding
            .graph_leases
            .lock()
            .expect("graph lease mutex")
            .get(&lease.id)
            .map(|entry| (*entry.snapshot).clone())
            .ok_or(QueryRefusalKind::GraphPublicationLeaseExpired)
    }

    #[cfg(feature = "embed")]
    pub(super) fn validate_graph_lease(
        &self,
        lease: &GraphPublicationLease,
    ) -> Result<(), crate::embed::parity::QueryRefusalKind> {
        self.capture_graph_lease_snapshot(lease).map(|_| ())
    }

    #[cfg(feature = "embed")]
    pub(super) fn capture_query_snapshot(
        &self,
        normalized: &[u8],
    ) -> Result<super::embed_query::EmbeddedQuerySnapshot, super::public_api::EmbedSourceRefusal>
    {
        use super::public_api::{
            OperationKind, RetryAdvice, SourceRefusalKind, SourceRuntimePhase,
        };
        let refuse = |kind, retry| {
            super::public_api::bound_source_refusal(
                kind,
                OperationKind::IndexCensus,
                retry,
                normalized,
            )
        };
        if self.closed.load(Ordering::Acquire) {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::Never,
            ));
        }
        let binding = self
            .binding
            .as_ref()
            .ok_or_else(|| refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::Never))?;
        let state = binding.state.lock().expect("embedded state mutex");
        if state.phase != SourceRuntimePhase::Current {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::OnEvent,
            ));
        }
        let index = binding
            .runtime
            .acquire()
            .map_err(|_| refuse(SourceRefusalKind::AdmissionUnavailable, RetryAdvice::Never))?;
        let authority = Arc::clone(&binding.authority);
        authority
            .verify_physical_root_anchor()
            .map_err(|_| refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::OnEvent))?;
        let authority_publication = authority
            .current_publication()
            .ok_or_else(|| refuse(SourceRefusalKind::SourceUnavailable, RetryAdvice::OnEvent))?;
        let source_set = index.published_source_set();
        let generation = source_set.current_generation();
        let publication_identity = format!(
            "embed-publication-{}-{}",
            self.identity.raw(),
            generation.publication_generation
        );
        if state.current_publication_identity.as_deref() != Some(&publication_identity)
            || !matches!(generation.freshness.as_ref(), FreshnessStatus::Current)
            || authority.current_publication() != Some(authority_publication)
            || self.closed.load(Ordering::Acquire)
        {
            return Err(refuse(
                SourceRefusalKind::SourceUnavailable,
                RetryAdvice::OnEvent,
            ));
        }
        let binding_identity = format!("source-{}", self.identity.raw());
        let serving_publication_identity = super::embed_query::serving_publication_identity(
            &binding_identity,
            &publication_identity,
            state.source_version,
        );
        Ok(super::embed_query::EmbeddedQuerySnapshot {
            root: binding.root.clone(),
            project_state: binding.state_placement.directory().cloned(),
            state_dir: binding
                .state_placement
                .directory()
                .map(|directory| directory.as_path().to_path_buf()),
            source_set,
            generation,
            binding_identity,
            publication_identity,
            serving_publication_identity,
            source_version: state.source_version,
            lifecycle_epoch: state.lifecycle_epoch,
            source_phase: SourceRuntimePhase::Current,
            authority_publication,
            authority,
            state_anchor: binding.state_anchor.clone(),
            temporal_cache: Arc::clone(&binding.temporal_cache),
            control_directory: binding.control_directory.clone(),
            trust_mode: binding.trust_mode,
        })
    }

    /// Disk-observation capture in ANY live phase: the admitted root authority,
    /// the latest published generation (for its admission policy only) and the
    /// observed phase. It authorizes no claim about the publication.
    #[cfg(feature = "embed")]
    pub(super) fn capture_disk_observation_context(
        &self,
    ) -> Option<(
        Arc<super::activation::ProjectSourceAuthority>,
        Arc<crate::live_index::PublishedGeneration>,
        super::public_api::SourceRuntimePhase,
    )> {
        if self.closed.load(Ordering::Acquire) {
            return None;
        }
        let binding = self.binding.as_ref()?;
        let phase = binding.state.lock().expect("embedded state mutex").phase;
        let index = binding.runtime.acquire().ok()?;
        let generation = index.published_source_set().current_generation();
        Some((Arc::clone(&binding.authority), generation, phase))
    }

    /// The bound root's admitted authority, in any phase: it reads a committed
    /// post-image beneath the original anchor even while the worker refreshes.
    #[cfg(feature = "embed")]
    pub(super) fn source_authority(
        &self,
    ) -> Option<Arc<super::activation::ProjectSourceAuthority>> {
        Some(Arc::clone(&self.binding.as_ref()?.authority))
    }

    /// This source's durable STEL ledger under `policy`, opened on first use
    /// in the binding's own state placement.
    #[cfg(feature = "embed")]
    pub(super) fn stel_store(
        &self,
        policy: crate::embed::parity::QueryPolicy,
    ) -> Option<Arc<crate::stel::ledger_store::StelLedgerStore>> {
        let binding = self.binding.as_ref()?;
        binding
            .stel_store
            .get(&binding.state_placement, policy, || {
                format!("embedded-{}", binding.identity.0)
            })
    }

    /// Health capture: the bound data plane, root and placement in ANY live
    /// phase. Health reports Loading/Blocked state from the published set like
    /// the MCP handler; it never answers a query, so it needs no Current claim.
    #[cfg(feature = "embed")]
    pub(super) fn capture_health_context(
        &self,
    ) -> Option<(crate::live_index::SharedIndex, PathBuf, StatePlacement)> {
        if self.closed.load(Ordering::Acquire) {
            return None;
        }
        let binding = self.binding.as_ref()?;
        let index = binding.runtime.acquire().ok()?;
        Some((
            Arc::clone(index),
            binding.root.clone(),
            binding.state_placement.clone(),
        ))
    }

    /// Internal curation context. A read capture is insufficient to authorize
    /// apply: the coordinator must separately require host authority and its
    /// own durability, review and mutation fences.
    #[cfg(feature = "embed")]
    pub(super) fn capture_curation_context(
        &self,
        normalized: &[u8],
    ) -> Result<
        (
            super::embed_query::EmbeddedQuerySnapshot,
            crate::live_index::SharedIndex,
            StatePlacement,
        ),
        super::public_api::EmbedSourceRefusal,
    > {
        let snapshot = self.capture_query_snapshot(normalized)?;
        let refuse = || {
            super::public_api::bound_source_refusal(
                super::public_api::SourceRefusalKind::SourceUnavailable,
                super::public_api::OperationKind::IndexCensus,
                super::public_api::RetryAdvice::OnEvent,
                normalized,
            )
        };
        let binding = self.binding.as_ref().ok_or_else(refuse)?;
        let index = binding.runtime.acquire().map_err(|_| refuse())?;
        if self.closed.load(Ordering::Acquire)
            || !Arc::ptr_eq(&index.published_generation(), &snapshot.generation)
        {
            return Err(refuse());
        }
        Ok((snapshot, Arc::clone(index), binding.state_placement.clone()))
    }

    /// This open's identity.
    pub fn identity(&self) -> EmbeddedIdentity {
        self.identity
    }

    /// The key it holds open.
    pub fn key(&self) -> &ProjectKey {
        &self.key
    }

    /// Whether this handle is still open.
    pub fn is_open(&self) -> bool {
        !self.closed.load(Ordering::Acquire)
            && self.binding.as_ref().is_none_or(|binding| {
                !matches!(
                    binding.runtime_view().phase,
                    super::public_api::SourceRuntimePhase::Stopped
                        | super::public_api::SourceRuntimePhase::Stopping
                )
            })
    }

    /// Close the source.
    ///
    /// Coalesces with `Drop`: whichever runs first performs the shutdown, and
    /// the other reports that it joined rather than performed it. Refuses with
    /// [`EmbedRefusal::WouldSelfWait`] when called from inside a finalizer,
    /// because waiting there is waiting on the calling thread itself.
    pub fn close(&self) -> Result<CloseReceipt, EmbedRefusal> {
        if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
            return Err(EmbedRefusal::WouldSelfWait);
        }
        if self.closed.swap(true, Ordering::AcqRel) {
            return Err(EmbedRefusal::AlreadyClosed);
        }
        let (performed, final_owner, _, _) = self.registration.close_one(&self.key, self.identity);
        Ok(CloseReceipt {
            identity: self.identity,
            performed_shutdown: performed,
            was_final_owner: final_owner,
        })
    }

    /// V11 (T047, E1 ruling): begin the close INFALLIBLY. The Slice 2 `close`
    /// refuses a self-wait AT CLOSE; the V11 contract relocates that guard to
    /// the WAIT — beginning a close is always legal, and only waiting on your
    /// own close from inside the finalizer refuses. An already-closed source
    /// yields a receipt that joined rather than performed, same as `Drop`
    /// coalescing.
    pub fn begin_close(&self) -> SourceCloseReceipt {
        let performed = if self.closed.swap(true, Ordering::AcqRel) {
            false
        } else {
            let (performed, _final_owner, terminal_version, _joined_workers) =
                self.registration.close_one(&self.key, self.identity);
            return SourceCloseReceipt {
                identity: self.identity,
                performed_shutdown: performed,
                terminal_source_version: terminal_version,
                _not_unwind_safe: std::marker::PhantomData,
            };
        };
        SourceCloseReceipt {
            identity: self.identity,
            performed_shutdown: performed,
            terminal_source_version: self
                .binding
                .as_ref()
                .map(|binding| binding.runtime_view().source_version)
                .unwrap_or(0),
            _not_unwind_safe: std::marker::PhantomData,
        }
    }

    #[cfg(feature = "embed")]
    pub fn change_version(&self) -> SourceChangeVersion {
        SourceChangeVersion {
            source_id: self.identity.raw(),
            revision: self.binding.as_ref().map_or(0, |binding| {
                binding
                    .state
                    .lock()
                    .expect("embedded state mutex")
                    .change_revision
            }),
        }
    }

    /// Block until source phase, publication, or graph lease capacity changes, or timeout.
    #[cfg(feature = "embed")]
    /// Capture `change_version()` before a retryable operation, then wait with that version to avoid losing an event before the wait begins. A capacity event may return an unchanged runtime view.
    pub fn wait_for_change(
        &self,
        since: SourceChangeVersion,
        timeout: Duration,
    ) -> Result<super::public_api::SourceRuntimeView, super::public_api::EmbedSourceRefusal> {
        use super::public_api::{OperationKind, RetryAdvice, SourceRefusalKind};
        let Some(binding) = self.binding.as_ref() else {
            return Ok(self.runtime_view());
        };
        if since.source_id != self.identity.raw() {
            return Err(super::public_api::bound_source_refusal(
                SourceRefusalKind::SourceUnavailable,
                OperationKind::IndexCensus,
                RetryAdvice::Never,
                b"foreign-source-change-version",
            ));
        }
        let started = std::time::Instant::now();
        let mut state = binding.state.lock().expect("embedded state mutex");
        while state.change_revision == since.revision && !self.closed.load(Ordering::Acquire) {
            binding.prune_graph_leases(&mut state);
            if state.change_revision != since.revision {
                break;
            }
            let remaining = timeout.saturating_sub(started.elapsed());
            if remaining.is_zero() {
                break;
            }
            let next_expiry = {
                let leases = binding.graph_leases.lock().expect("graph lease mutex");
                if leases.len() >= 8 {
                    leases.values().map(|entry| entry.expires_at).min()
                } else {
                    None
                }
            };
            let wait = next_expiry.map_or(remaining, |expiry| {
                remaining.min(expiry.saturating_duration_since(std::time::Instant::now()))
            });
            let (next, _) = binding
                .change_wake
                .wait_timeout(state, wait)
                .expect("embedded state mutex");
            state = next;
        }
        Ok(super::public_api::SourceRuntimeView {
            binding_identity: format!("source-{}", self.identity.raw()),
            current_publication_identity: state.current_publication_identity.clone(),
            observer_epoch: state.observer_epoch,
            phase: state.phase,
            source_version: state.source_version,
        })
    }

    /// Capture the source's lifecycle state atomically.
    pub fn runtime_view(&self) -> super::public_api::SourceRuntimeView {
        self.binding.as_ref().map_or_else(
            || super::public_api::SourceRuntimeView {
                binding_identity: format!("source-{}", self.identity.raw()),
                current_publication_identity: None,
                observer_epoch: 0,
                phase: if self.closed.load(Ordering::Acquire) {
                    super::public_api::SourceRuntimePhase::Stopped
                } else {
                    super::public_api::SourceRuntimePhase::Loading
                },
                source_version: 0,
            },
            |binding| binding.runtime_view(),
        )
    }

    /// Search one pinned current generation and return its claim provenance.
    pub fn search_symbols(
        &self,
        request: &super::public_api::SymbolSearchRequest,
    ) -> Result<
        super::public_api::EmbedClaim<super::public_api::SymbolSearchResult>,
        super::public_api::EmbedSourceRefusal,
    > {
        let normalized = format!(
            "query={:?};path_prefix={:?};limit={}",
            request.query, request.path_prefix, request.limit
        );
        if self.closed.load(Ordering::Acquire) {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchSymbols,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::SearchSymbols,
            ));
        };
        let claim = binding.current_claim(
            crate::lifecycle_identity::OperationKind::SearchSymbols,
            normalized.as_bytes(),
        )?;
        let index = binding.runtime.acquire().map_err(|_| {
            super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchSymbols,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            )
        })?;
        let live = index.read();
        let query = request.query.as_deref().map(str::to_lowercase);
        let mut matches = Vec::new();
        for (path, file) in live.all_files() {
            if !path_matches_prefix(path, request.path_prefix.as_deref()) {
                continue;
            }
            for symbol in &file.symbols {
                if query
                    .as_deref()
                    .is_some_and(|query| !symbol.name.to_lowercase().contains(query))
                {
                    continue;
                }
                matches.push((
                    symbol.sort_order,
                    super::public_api::SymbolMatch {
                        name: symbol.name.clone(),
                        kind: symbol.kind.to_string(),
                        path: path.clone(),
                        start_line: symbol.line_range.0.saturating_add(1),
                        end_line: symbol.line_range.1.saturating_add(1),
                    },
                ));
            }
        }
        matches.sort_by(|(left_order, left), (right_order, right)| {
            left.path
                .cmp(&right.path)
                .then_with(|| left.start_line.cmp(&right.start_line))
                .then_with(|| left_order.cmp(right_order))
                .then_with(|| left.name.cmp(&right.name))
                .then_with(|| left.kind.cmp(&right.kind))
        });
        let limit = request.limit as usize;
        let truncated = matches.len() > limit;
        let matches = matches
            .into_iter()
            .take(limit)
            .map(|(_, value)| value)
            .collect();
        Ok(super::public_api::live_claim(
            super::public_api::SymbolSearchResult { matches, truncated },
            crate::lifecycle_identity::OperationKind::SearchSymbols,
            normalized.as_bytes(),
            &claim.binding_identity,
            &claim.publication_identity,
            claim.source_version,
        ))
    }

    /// Search stored byte-exact file content from one pinned current generation.
    pub fn search_text(
        &self,
        request: &super::public_api::TextSearchRequest,
    ) -> Result<
        super::public_api::EmbedClaim<super::public_api::TextSearchResult>,
        super::public_api::EmbedSourceRefusal,
    > {
        let normalized = format!(
            "query={:?};path_prefix={:?};limit={};case_sensitive={}",
            request.query, request.path_prefix, request.limit, request.case_sensitive
        );
        if request.query.is_empty() {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::InvalidSelection,
                crate::lifecycle_identity::OperationKind::SearchText,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            ));
        }
        if self.closed.load(Ordering::Acquire) {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchText,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::SearchText,
            ));
        };
        let claim = binding.current_claim(
            crate::lifecycle_identity::OperationKind::SearchText,
            normalized.as_bytes(),
        )?;
        let matcher = regex::RegexBuilder::new(&regex::escape(&request.query))
            .case_insensitive(!request.case_sensitive)
            .build()
            .map_err(|_| {
                super::public_api::bound_source_refusal(
                    crate::lifecycle_identity::SourceRefusalKind::InvalidSelection,
                    crate::lifecycle_identity::OperationKind::SearchText,
                    crate::lifecycle_identity::RetryAdvice::Never,
                    normalized.as_bytes(),
                )
            })?;
        let index = binding.runtime.acquire().map_err(|_| {
            super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchText,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            )
        })?;
        let live = index.read();
        let limit = request.limit as usize;
        let mut matches = Vec::new();
        let mut truncated = false;
        'files: for (path, file) in live.all_files() {
            if !path_matches_prefix(path, request.path_prefix.as_deref()) {
                continue;
            }
            let Ok(content) = std::str::from_utf8(&file.content) else {
                continue;
            };
            let mut line_start = 0usize;
            for (line_index, line) in content.split_inclusive('\n').enumerate() {
                let searchable = line.strip_suffix('\n').unwrap_or(line);
                for found in matcher.find_iter(searchable) {
                    if matches.len() == limit {
                        truncated = true;
                        break 'files;
                    }
                    let byte_start = line_start.saturating_add(found.start());
                    let byte_end = line_start.saturating_add(found.end());
                    matches.push(super::public_api::TextMatch {
                        path: path.clone(),
                        line: u32::try_from(line_index.saturating_add(1)).unwrap_or(u32::MAX),
                        byte_start: byte_start as u64,
                        byte_end: byte_end as u64,
                        preview: bounded_preview(searchable.trim_end_matches('\r')),
                    });
                }
                line_start = line_start.saturating_add(line.len());
            }
        }
        Ok(super::public_api::live_claim(
            super::public_api::TextSearchResult { matches, truncated },
            crate::lifecycle_identity::OperationKind::SearchText,
            normalized.as_bytes(),
            &claim.binding_identity,
            &claim.publication_identity,
            claim.source_version,
        ))
    }

    /// Census one pinned current generation's parsed files, including zeros.
    pub fn index_census(
        &self,
    ) -> Result<
        super::public_api::EmbedClaim<super::public_api::IndexCensus>,
        super::public_api::EmbedSourceRefusal,
    > {
        let normalized = b"index-census";
        if self.closed.load(Ordering::Acquire) {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::IndexCensus,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized,
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::IndexCensus,
            ));
        };
        let claim = binding.current_claim(
            crate::lifecycle_identity::OperationKind::IndexCensus,
            normalized,
        )?;
        let index = binding.runtime.acquire().map_err(|_| {
            super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::IndexCensus,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized,
            )
        })?;
        let generation = index.published_generation();
        let parsed: std::collections::BTreeSet<String> = generation
            .live
            .all_files()
            .filter(|(_, file)| {
                matches!(
                    file.parse_status,
                    crate::live_index::store::ParseStatus::Parsed
                        | crate::live_index::store::ParseStatus::PartialParse { .. }
                )
            })
            .map(|(path, _)| path.clone())
            .collect();
        crate::live_index::store::pause_census_after_first_read_for_test(&binding.root);
        let files: Vec<super::public_api::CensusFile> = generation
            .outline
            .files
            .iter()
            .filter(|file| parsed.contains(&file.relative_path))
            .map(|file| {
                let (reference_count, parse_status) = generation
                    .live
                    .get_file(&file.relative_path)
                    .map(|indexed| {
                        (
                            u32::try_from(indexed.references.len()).unwrap_or(u32::MAX),
                            match &indexed.parse_status {
                                crate::live_index::store::ParseStatus::Parsed => {
                                    super::public_api::CensusParseStatus::Parsed
                                }
                                crate::live_index::store::ParseStatus::PartialParse { .. } => {
                                    super::public_api::CensusParseStatus::PartialParse
                                }
                                crate::live_index::store::ParseStatus::Failed { .. } => {
                                    super::public_api::CensusParseStatus::Failed
                                }
                            },
                        )
                    })
                    .unwrap_or((0, super::public_api::CensusParseStatus::Parsed));
                super::public_api::CensusFile {
                    path: file.relative_path.clone(),
                    language: file.language.name().to_string(),
                    symbol_count: u32::try_from(file.symbol_count).unwrap_or(u32::MAX),
                    reference_count,
                    parse_status,
                }
            })
            .collect();
        let total_files = files.len() as u64;
        let total_symbols = files.iter().map(|file| u64::from(file.symbol_count)).sum();
        Ok(super::public_api::live_claim(
            super::public_api::IndexCensus {
                total_files,
                total_symbols,
                files,
                snapshot_verify: match &generation.health.snapshot_verify_state {
                    crate::live_index::store::SnapshotVerifyState::NotNeeded => {
                        super::public_api::CensusVerifyPhase::NotNeeded
                    }
                    crate::live_index::store::SnapshotVerifyState::Pending => {
                        super::public_api::CensusVerifyPhase::Pending
                    }
                    crate::live_index::store::SnapshotVerifyState::Running(_) => {
                        super::public_api::CensusVerifyPhase::Running
                    }
                    crate::live_index::store::SnapshotVerifyState::Completed(_) => {
                        super::public_api::CensusVerifyPhase::Completed
                    }
                    crate::live_index::store::SnapshotVerifyState::Failed(_) => {
                        super::public_api::CensusVerifyPhase::Failed
                    }
                },
            },
            crate::lifecycle_identity::OperationKind::IndexCensus,
            normalized,
            &claim.binding_identity,
            &claim.publication_identity,
            claim.source_version,
        ))
    }

    /// Binding-owned reload counters. Always succeeds; zeros if unbound.
    pub fn index_progress(&self) -> super::public_api::IndexProgress {
        self.binding
            .as_ref()
            .map_or_else(super::public_api::IndexProgress::default, |binding| {
                let (files_discovered, files_parsed, symbols_found) = binding.progress.snapshot();
                super::public_api::IndexProgress {
                    files_discovered,
                    files_parsed,
                    symbols_found,
                }
            })
    }

    /// Search admitted knowledge from one pinned current generation.
    pub fn search_knowledge(
        &self,
        request: &super::public_api::KnowledgeSearchRequest,
    ) -> Result<
        super::public_api::EmbedClaim<super::public_api::KnowledgeSearchResult>,
        super::public_api::EmbedSourceRefusal,
    > {
        let normalized = format!(
            "query={:?};path_prefix={:?};limit={}",
            request.query, request.path_prefix, request.limit
        );
        if self.closed.load(Ordering::Acquire) {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchKnowledge,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::SearchKnowledge,
            ));
        };
        let parsed = crate::live_index::knowledge_retrieve::KnowledgeRetrieveRequest::parse(
            &request.query,
            request.path_prefix.as_deref(),
            crate::live_index::knowledge_retrieve::KnowledgeRetrieveAuthorityScope::Default,
            request.limit as usize,
        )
        .map_err(|_| {
            super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::InvalidSelection,
                crate::lifecycle_identity::OperationKind::SearchKnowledge,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            )
        })?;
        let claim = binding.current_claim(
            crate::lifecycle_identity::OperationKind::SearchKnowledge,
            normalized.as_bytes(),
        )?;
        let index = binding.runtime.acquire().map_err(|_| {
            super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::SearchKnowledge,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized.as_bytes(),
            )
        })?;
        let generation = index.published_generation();
        let retrieved = crate::live_index::knowledge_retrieve::retrieve_knowledge(
            &[
                crate::live_index::knowledge_retrieve::KnowledgeRetrieveLane {
                    generation: &generation,
                    label: "current",
                },
            ],
            &parsed,
        );
        let matches = retrieved
            .hits
            .into_iter()
            .map(|hit| super::public_api::KnowledgeMatch {
                path: hit.path,
                heading_path: hit.heading_path,
                preview: hit.preview,
                content_hash: hit.content_hash,
                provenance_ids: hit.authority.provenance_ids,
                relationship_evidence: hit
                    .relationship_evidence
                    .iter()
                    .map(|evidence| evidence.preview_token())
                    .collect(),
                authority: knowledge_lifecycle_label(hit.authority.lifecycle),
                coverage: knowledge_coverage_label(&hit.authority.coverage),
            })
            .collect();
        Ok(super::public_api::live_claim(
            super::public_api::KnowledgeSearchResult {
                matches,
                truncated: retrieved.truncated,
                withheld_count: retrieved.withheld_count as u64,
                withheld_reasons: retrieved
                    .withheld_reasons
                    .into_iter()
                    .map(knowledge_withheld_label)
                    .collect(),
            },
            crate::lifecycle_identity::OperationKind::SearchKnowledge,
            normalized.as_bytes(),
            &claim.binding_identity,
            &claim.publication_identity,
            claim.source_version,
        ))
    }

    #[cfg(feature = "__test-internals")]
    pub fn revoke_admission_for_test(&self) {
        if let Some(binding) = &self.binding {
            binding.runtime.revoke_admission_for_test();
        }
    }

    /// Signal reload cancel without joining the worker. Close still joins.
    #[cfg(feature = "__test-internals")]
    pub fn cancel_reload_for_test(&self) {
        if let Some(binding) = &self.binding {
            binding.shutdown_started.store(true, Ordering::Release);
            let mut control = binding.control.lock().expect("embedded control mutex");
            control.stop = true;
            binding.wake.notify_all();
        }
    }

    /// Queue a refresh on this source's worker.
    pub fn request_refresh(
        &self,
    ) -> Result<super::public_api::EmbedRefreshTicket, super::public_api::EmbedSourceRefusal> {
        let normalized = b"refresh-current-worktree";
        if self.closed.load(Ordering::Acquire) {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::RefreshSource,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized,
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::RefreshSource,
            ));
        };
        let Some(source_version) = binding.request_refresh(false) else {
            return Err(super::public_api::bound_source_refusal(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::OperationKind::RefreshSource,
                crate::lifecycle_identity::RetryAdvice::Never,
                normalized,
            ));
        };
        Ok(super::public_api::refresh_ticket(
            normalized,
            source_version,
        ))
    }

    /// MCP `index_folder` in-place reset: delete the persisted snapshot scope
    /// through the shared `persist::reset_snapshot_state`, then request a full
    /// reload. The reset generation is recorded once that reload publishes.
    #[cfg(feature = "embed")]
    pub fn request_refresh_with_reset(
        &self,
    ) -> Result<
        (
            super::public_api::EmbedRefreshTicket,
            crate::embed::parity::source_options::SnapshotResetReceipt,
        ),
        super::public_api::EmbedSourceRefusal,
    > {
        let normalized = b"refresh-current-worktree;reset_snapshot_state=true";
        let refuse = |kind, retry| {
            super::public_api::bound_source_refusal(
                kind,
                crate::lifecycle_identity::OperationKind::RefreshSource,
                retry,
                normalized,
            )
        };
        if self.closed.load(Ordering::Acquire) {
            return Err(refuse(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::RetryAdvice::Never,
            ));
        }
        let Some(binding) = self.binding.as_ref() else {
            return Err(super::public_api::dark_unbound_refusal(
                crate::lifecycle_identity::OperationKind::RefreshSource,
            ));
        };
        let report = crate::live_index::persist::reset_snapshot_state(
            &binding.root,
            &binding.state_placement,
        )
        .map_err(|_| {
            refuse(
                crate::lifecycle_identity::SourceRefusalKind::AdmissionUnavailable,
                crate::lifecycle_identity::RetryAdvice::Operator,
            )
        })?;
        let Some(source_version) = binding.request_refresh(true) else {
            return Err(refuse(
                crate::lifecycle_identity::SourceRefusalKind::SourceUnavailable,
                crate::lifecycle_identity::RetryAdvice::Never,
            ));
        };
        Ok((
            super::public_api::refresh_ticket(normalized, source_version),
            crate::embed::parity::source_options::SnapshotResetReceipt::from_report(&report),
        ))
    }

    /// The snapshot reset performed by `EmbeddedOpenOptions::reset_snapshot_state`,
    /// or `None` when the open did not reset.
    #[cfg(feature = "embed")]
    pub fn open_reset_receipt(
        &self,
    ) -> Option<crate::embed::parity::source_options::SnapshotResetReceipt> {
        self.binding.as_ref()?.open_reset.clone()
    }

    /// Fixture probe for the relocated guard: arms the finalizer for THIS
    /// source and attempts to wait on its own close receipt from inside it —
    /// which must refuse with [`ReceiptWaitError::WouldSelfWait`] rather than
    /// deadlock.
    #[cfg(all(test, feature = "server"))]
    pub fn self_wait_probe_for_test(&self) -> Result<SourceCloseReport, ReceiptWaitError> {
        let receipt = self.begin_close();
        self.finalize(|| receipt.wait_for_test())
    }

    /// Run `finalizer` with self-wait detection armed for THIS source.
    ///
    /// A finalizer that tries to close this source is refused rather than
    /// deadlocked; a finalizer that closes some other source is none of this
    /// source's business and proceeds. The previous value is restored even if
    /// the finalizer panics, so one bad finalizer cannot poison every later
    /// close on this thread, and nesting two finalizers cannot leave the outer
    /// one disarmed.
    pub fn finalize<R>(&self, finalizer: impl FnOnce() -> R) -> R {
        struct Guard(Option<EmbeddedIdentity>);
        impl Drop for Guard {
            fn drop(&mut self) {
                FINALIZING.with(|flag| flag.set(self.0));
            }
        }
        let _guard = Guard(FINALIZING.with(|flag| flag.replace(Some(self.identity))));
        finalizer()
    }
}

/// Waiting on a receipt can refuse; the wait is where the self-wait guard
/// lives in V11, so the error is typed rather than a deadlock.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReceiptWaitError {
    /// The deadline passed before the wait completed. A CONTRACT variant
    /// (T049): dark waits complete immediately, so nothing in Slice 3 can
    /// produce it — Slice 4's real waits can. T047's transcription omitted
    /// it, the same defect class as the invented `ServerExit::Clean`, caught
    /// by the dependent-positive fixture once its feature gate was honest.
    DeadlineElapsed,
    /// The wait was attempted from inside this source's own finalizer:
    /// waiting there is waiting on the calling thread itself.
    WouldSelfWait,
}

// T049: `Display` and `Error` are contract-pinned direct impls on this atom.
impl std::fmt::Display for ReceiptWaitError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::DeadlineElapsed => {
                write!(f, "the deadline passed before the wait completed")
            }
            Self::WouldSelfWait => write!(
                f,
                "waiting on this receipt from inside its own source's finalizer \
                 would wait on the calling thread itself"
            ),
        }
    }
}

impl std::error::Error for ReceiptWaitError {}

/// Receipt for a completed V11 `begin_close`.
#[derive(Debug)]
pub struct SourceCloseReceipt {
    identity: EmbeddedIdentity,
    performed_shutdown: bool,
    terminal_source_version: u64,
    // T049: the contract pins the receipt NOT UnwindSafe/RefUnwindSafe.
    _not_unwind_safe: super::public_api::NotUnwindSafe,
}

impl SourceCloseReceipt {
    /// The contract wait (T049): refuses a self-wait and otherwise returns the
    /// teardown result already observed by synchronous close.
    pub fn wait(
        &self,
        deadline: std::time::Instant,
    ) -> Result<super::public_api::SourceCloseReport, ReceiptWaitError> {
        let _ = deadline;
        if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
            return Err(ReceiptWaitError::WouldSelfWait);
        }
        Ok(super::public_api::SourceCloseReport {
            already_terminal: !self.performed_shutdown,
            terminal_source_version: self.terminal_source_version,
        })
    }

    /// Wait for the close to finalize, reporting the INTERNAL observation
    /// record (T047's oracle shape). Refuses a self-wait; completes
    /// immediately otherwise, because the close performed synchronously and
    /// only observed completions may be reported.
    #[cfg(all(test, feature = "server"))]
    pub fn wait_for_test(&self) -> Result<SourceCloseReport, ReceiptWaitError> {
        if FINALIZING.with(std::cell::Cell::get) == Some(self.identity) {
            return Err(ReceiptWaitError::WouldSelfWait);
        }
        Ok(SourceCloseReport {
            finalized: true,
            performed_shutdown: self.performed_shutdown,
        })
    }
}

/// What the close wait OBSERVED.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceCloseReport {
    finalized: bool,
    performed_shutdown: bool,
}

impl SourceCloseReport {
    pub fn finalized(&self) -> bool {
        self.finalized
    }

    pub fn performed_shutdown(&self) -> bool {
        self.performed_shutdown
    }
}

impl Drop for EmbeddedSourceHandle {
    fn drop(&mut self) {
        // Coalesce with an explicit close. A handle dropped without closing must
        // still release the source, or the registration would believe a source
        // is open that nothing holds.
        //
        // `Drop` deliberately does NOT consult `FINALIZING`. The self-wait
        // hazard `close` refuses is about WAITING, and `close_one` takes a
        // mutex and returns — it never waits on the finalizer. Refusing here
        // would be worse than the hazard: a `Drop` cannot report a refusal, so
        // the source would simply stay open forever with nothing holding it.
        // This is stated rather than left as an inconsistency between the two
        // paths, which is how it read before: `a.finalize(|| drop(b))` was
        // permitted while `a.finalize(|| b.close())` was refused.
        if !self.closed.swap(true, Ordering::AcqRel) {
            let _ = self.registration.close_one(&self.key, self.identity);
        }
    }
}

#[cfg(all(test, feature = "embed"))]
mod refresh_lifecycle_tests {
    use super::*;
    use crate::embed::parity::{QueryLimits, QueryRefusalKind, QueryRequest};
    use crate::embed::{EmbeddedSourceSpec, ProcessIndexRuntime, SourceRuntimePhase};

    thread_local! {
        pub(super) static BEFORE_FRESHEN_GENERATION: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
            const { std::cell::RefCell::new(None) };
        pub(super) static BEFORE_OBSERVED_STATE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> =
            const { std::cell::RefCell::new(None) };
    }

    fn wait_current(handle: &EmbeddedSourceHandle, after: u64) {
        let started = std::time::Instant::now();
        loop {
            let since = handle.change_version();
            let view = handle.runtime_view();
            if view.phase == SourceRuntimePhase::Current && view.source_version > after {
                return;
            }
            let remaining = Duration::from_secs(20).saturating_sub(started.elapsed());
            assert!(
                !remaining.is_zero(),
                "source did not become Current: {view:?}"
            );
            handle.wait_for_change(since, remaining).unwrap();
        }
    }

    fn open_current() -> (
        tempfile::TempDir,
        ProcessIndexRuntime,
        Arc<EmbeddedSourceHandle>,
    ) {
        let root = tempfile::tempdir().unwrap();
        std::fs::write(root.path().join("lib.rs"), "pub fn loaded() {}\n").unwrap();
        let runtime = ProcessIndexRuntime::acquire().unwrap();
        let handle = Arc::new(
            runtime
                .open_embedded_source(EmbeddedSourceSpec::current_worktree(
                    root.path().to_path_buf(),
                ))
                .unwrap(),
        );
        wait_current(&handle, 0);
        (root, runtime, handle)
    }

    #[test]
    fn observed_publication_includes_freshening_admitted_before_refresh() {
        let (root, _runtime, handle) = open_current();
        let binding = Arc::clone(handle.binding.as_ref().unwrap());
        // Keep the observer out while the test drives the worker's publication path.
        let control = binding.control.lock().unwrap();
        let (admitted_tx, admitted_rx) = std::sync::mpsc::sync_channel(1);
        let (resume_tx, resume_rx) = std::sync::mpsc::sync_channel(1);
        let (finished_tx, finished_rx) = std::sync::mpsc::sync_channel(1);
        let freshening = Arc::clone(&binding);
        let freshener = std::thread::spawn(move || {
            BEFORE_FRESHEN_GENERATION.with(|hook| {
                *hook.borrow_mut() = Some(Box::new(move || {
                    admitted_tx.send(()).unwrap();
                    resume_rx.recv_timeout(Duration::from_secs(5)).unwrap();
                }));
            });
            let result = freshening.freshen_exact_path("lib.rs");
            finished_tx.send(result).unwrap();
        });
        admitted_rx.recv_timeout(Duration::from_secs(5)).unwrap();

        binding.set_phase(SourceRuntimePhase::Refreshing);
        let shared = binding.runtime.data_plane();
        let previous_project_generation = shared.current_project_generation();
        shared
            .refresh_bound_tree_cancellable(
                &binding.root,
                binding.state_placement.directory().cloned(),
                crate::discovery::SourceExclusions::for_state_placement(
                    &binding.root,
                    &binding.state_placement,
                ),
                &binding.shutdown_started,
            )
            .unwrap();
        assert!(shared.current_project_generation() > previous_project_generation);
        let before = shared.published_generation().publication_generation;
        let mtime = shared.read().get_file("lib.rs").unwrap().mtime_secs;
        let final_bytes = b"pub fn freshened_after_reload() {}\n";
        std::fs::write(root.path().join("lib.rs"), final_bytes).unwrap();
        filetime::set_file_mtime(
            root.path().join("lib.rs"),
            filetime::FileTime::from_unix_time(mtime as i64 + 2, 0),
        )
        .unwrap();

        let publishing = Arc::clone(&binding);
        BEFORE_OBSERVED_STATE.with(|hook| {
            *hook.borrow_mut() = Some(Box::new(move || {
                resume_tx.send(()).unwrap();
                finished_rx
                    .recv_timeout(Duration::from_secs(5))
                    .unwrap()
                    .unwrap();
                assert_eq!(
                    publishing.runtime_view().phase,
                    SourceRuntimePhase::Refreshing
                );
                assert!(
                    publishing
                        .runtime
                        .data_plane()
                        .published_generation()
                        .publication_generation
                        > before
                );
            }));
        });
        let fingerprint = binding.publish_observed_current().unwrap();
        let published = shared.published_generation();
        let snapshot = handle.capture_query_snapshot(b"freshened-during-refresh");
        let unchanged_fingerprint = binding.observe_fingerprint();
        let current_identity = binding
            .state
            .lock()
            .unwrap()
            .current_publication_identity
            .clone();
        let assertions = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            assert_eq!(Some(fingerprint), unchanged_fingerprint);
            assert_eq!(handle.runtime_view().phase, SourceRuntimePhase::Current);
            assert_eq!(
                current_identity,
                Some(format!(
                    "embed-publication-{}-{}",
                    binding.identity.raw(),
                    published.publication_generation
                )),
                "Current lifecycle identity must match the freshened publication"
            );
            let snapshot = snapshot.expect("Current must capture the latest freshened publication");
            assert_eq!(
                snapshot.generation.publication_generation,
                published.publication_generation
            );
            assert_eq!(
                snapshot
                    .generation
                    .live
                    .get_file("lib.rs")
                    .unwrap()
                    .content
                    .as_slice(),
                final_bytes
            );
            assert!(
                handle
                    .query(
                        &QueryRequest::File {
                            path: "lib.rs".into(),
                            start_line: None,
                            end_line: None,
                        },
                        QueryLimits::default(),
                    )
                    .is_ok()
            );
        }));
        drop(control);
        freshener.join().unwrap();
        if let Err(panic) = assertions {
            std::panic::resume_unwind(panic);
        }
    }

    #[test]
    fn observed_non_current_freshness_blocks_without_relocking_state() {
        const CHILD_ENV: &str = "SYMFORGE_NON_CURRENT_PUBLICATION_CHILD";
        if std::env::var_os(CHILD_ENV).is_some() {
            let (_root, _runtime, handle) = open_current();
            let binding = Arc::clone(handle.binding.as_ref().unwrap());
            let control = binding.control.lock().unwrap();
            binding
                .runtime
                .data_plane()
                .set_freshness_status(FreshnessStatus::Verifying);
            assert!(binding.publish_observed_current().is_some());
            assert_eq!(handle.runtime_view().phase, SourceRuntimePhase::Blocked);
            drop(control);
            return;
        }

        let mut child = crate::process_util::hidden_command(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "internals::index_lifecycle::embedded::refresh_lifecycle_tests::observed_non_current_freshness_blocks_without_relocking_state",
                "--nocapture",
            ])
            .env(CHILD_ENV, "1")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .unwrap();
        let deadline = std::time::Instant::now() + Duration::from_secs(30);
        loop {
            match child.try_wait() {
                Ok(Some(_)) => break,
                Ok(None) if std::time::Instant::now() < deadline => {
                    std::thread::sleep(Duration::from_millis(25));
                }
                outcome => {
                    let _ = child.kill();
                    let reaped = child.wait();
                    panic!(
                        "non-Current publication child timed out or could not be observed: {outcome:?}; reaped: {reaped:?}"
                    );
                }
            }
        }
        let output = child.wait_with_output().unwrap();
        assert!(
            output.status.success(),
            "non-Current publication child failed: {} {}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
        assert!(
            String::from_utf8_lossy(&output.stdout).contains("running 1 test"),
            "child must execute the exact non-Current publication fixture"
        );
    }

    #[test]
    #[cfg(feature = "__test-internals")]
    fn lease_begin_preserves_transient_and_invalid_root_retry_advice() {
        use super::super::public_api::{RetryAdvice, SourceRefusalKind};
        let parent = tempfile::tempdir().unwrap();
        let root = parent.path().join("source");
        std::fs::create_dir(&root).unwrap();
        std::fs::write(root.join("lib.rs"), "pub fn loaded() {}\n").unwrap();
        let reload_hold = crate::live_index::store::hold_reload_after_discovery_for_test(&root);
        let runtime = ProcessIndexRuntime::acquire().unwrap();
        let handle = runtime
            .open_embedded_source(EmbeddedSourceSpec::current_worktree(root.clone()))
            .unwrap();
        // Release the reload hold before the handle during assertion unwinding.
        let gate = reload_hold;
        assert!(gate.wait_until_blocked(Duration::from_secs(5)));
        assert_eq!(handle.runtime_view().phase, SourceRuntimePhase::Loading);
        let loading = handle
            .begin_graph_publication_lease(Duration::from_secs(20))
            .unwrap_err();
        assert_eq!(loading.kind(), SourceRefusalKind::SourceUnavailable);
        assert_eq!(loading.retry(), RetryAdvice::OnEvent);
        let binding = handle.binding.as_ref().unwrap();
        binding.set_phase(SourceRuntimePhase::Refreshing);
        let refreshing = handle
            .begin_graph_publication_lease(Duration::from_secs(20))
            .unwrap_err();
        assert_eq!(refreshing.kind(), SourceRefusalKind::SourceUnavailable);
        assert_eq!(refreshing.retry(), RetryAdvice::OnEvent);

        std::fs::rename(&root, parent.path().join("original")).unwrap();
        std::fs::create_dir(&root).unwrap();
        let invalid = handle
            .begin_graph_publication_lease(Duration::from_secs(20))
            .unwrap_err();
        assert_eq!(invalid.kind(), SourceRefusalKind::SourceUnavailable);
        assert_eq!(invalid.retry(), RetryAdvice::Never);
        let captured = handle
            .capture_query_snapshot_allowing_refresh(b"invalid-root")
            .err()
            .expect("invalid root must refuse capture");
        assert_eq!(captured.kind(), SourceRefusalKind::SourceUnavailable);
        assert_eq!(captured.retry(), RetryAdvice::Never);
        let completed = handle
            .validate_refresh_snapshot(0, b"invalid-root")
            .unwrap_err();
        assert_eq!(completed.kind(), SourceRefusalKind::SourceUnavailable);
        assert_eq!(completed.retry(), RetryAdvice::Never);
        drop(gate);
    }

    #[test]
    #[cfg(feature = "__test-internals")]
    fn blocked_recovery_invalidates_leases_and_retained_completion() {
        use super::super::public_api::{RetryAdvice, SourceRefusalKind};
        let (root, _runtime, handle) = open_current();
        let initial = handle.runtime_view();
        let lease = handle
            .begin_graph_publication_lease(Duration::from_secs(20))
            .unwrap();
        assert_eq!(format!("{lease:?}"), "GraphPublicationLease { .. }");
        let snapshot = handle
            .capture_query_snapshot_allowing_refresh(b"before-blocked")
            .unwrap();
        let gate = crate::live_index::store::hold_reload_after_discovery_for_test(root.path());
        handle.request_refresh().unwrap();
        assert!(gate.wait_until_blocked(Duration::from_secs(5)));
        assert!(handle.capture_graph_lease_snapshot(&lease).is_ok());
        let binding = handle.binding.as_ref().unwrap();
        binding.set_blocked();
        binding.set_phase(SourceRuntimePhase::Refreshing);
        assert_eq!(
            handle
                .capture_graph_lease_snapshot(&lease)
                .err()
                .expect("invalidated lease must refuse"),
            QueryRefusalKind::SourceUnavailable,
        );
        let completion = handle
            .validate_refresh_snapshot(snapshot.lifecycle_epoch, b"after-blocked")
            .unwrap_err();
        assert_eq!(completion.kind(), SourceRefusalKind::SourceUnavailable);
        assert_eq!(completion.retry(), RetryAdvice::OnEvent);
        let unavailable = handle
            .begin_graph_publication_lease(Duration::from_secs(20))
            .unwrap_err();
        assert_eq!(unavailable.kind(), SourceRefusalKind::SourceUnavailable);
        assert_eq!(unavailable.retry(), RetryAdvice::OnEvent);
        drop(gate);
        wait_current(&handle, initial.source_version);
        assert_eq!(
            handle
                .capture_graph_lease_snapshot(&lease)
                .err()
                .expect("invalidated lease must refuse"),
            QueryRefusalKind::SourceUnavailable,
        );
        let replacement = handle
            .begin_graph_publication_lease(Duration::from_secs(20))
            .unwrap();
        assert!(handle.capture_graph_lease_snapshot(&replacement).is_ok());
    }

    #[test]
    fn unsupported_freshening_request_refuses_before_taking_source_state() {
        let (root, _runtime, handle) = open_current();
        let request = QueryRequest::Syntax {
            path: "lib.rs".into(),
        };
        assert_eq!(request.freshen_path(), Some("lib.rs"));
        let binding = handle.binding.as_ref().unwrap();
        let state = binding.state.lock().unwrap();
        std::fs::write(root.path().join("lib.rs"), "pub fn changed() {}\n").unwrap();
        let (sent, received) = std::sync::mpsc::sync_channel(1);
        let querying = Arc::clone(&handle);
        let worker = std::thread::spawn(move || {
            sent.send(querying.query_allowing_refresh(&request, QueryLimits::default()))
                .unwrap();
        });
        let result = received.recv_timeout(Duration::from_secs(2));
        drop(state);
        worker.join().unwrap();
        let refusal = result
            .expect("unsupported request entered the source/freshening path")
            .unwrap_err();
        assert_eq!(refusal.kind(), QueryRefusalKind::UnsupportedOption);
        assert_eq!(
            refusal.retry(),
            super::super::public_api::RetryAdvice::Never
        );
    }
}