subc-client-rs 0.32.2

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

use sha2::{Digest, Sha256};
pub use subc_control::SupervisorEntry;
use subc_control::{
    CatalogEntry, ClientControlRequest, ClientControlResponse, ConsumerIdentity, PollKind,
};
/// The spawn snapshot types, re-exported so a caller of
/// [`SubcConsumer::spawn_snapshot`] needs no direct `subc-control` dependency.
pub use subc_control::{LiveSpawn, SpawnCursor, SpawnEvent, SpawnEventKind, SpawnSnapshot};
/// The scope a route is opened under, re-exported so a caller of
/// [`SubcConsumer::open_route_scoped`] can name the type from this crate.
pub use subc_protocol::scope::ScopeSelector;
use subc_protocol::{
    error_codes, manifest::is_valid_capability_identifier, AdmissionClass, BindIdentity, ErrorBody,
    Flags, Frame, FrameBuildError, FrameType, Priority, RouteTarget, FLAG_SUBSCRIPTION,
    SUBC_MODULE_ID_ENV,
};

use crate::{
    ActivityCursor, ActivityQueryRequest, ActivityQueryResponse, ActivitySubscribeRequest,
    ActivitySubscription, RouteHandle,
};
use subc_transport::{
    authenticate_client, connection_file, read_frame, write_frame, AuthError, ConnectionFileError,
    FrameIoError,
};
use tokio::{
    io::{AsyncWrite, AsyncWriteExt, BufWriter},
    net::{tcp::OwnedReadHalf, TcpStream},
    sync::{mpsc, oneshot, watch, Notify, OwnedSemaphorePermit, Semaphore},
    task::JoinHandle,
    time::{sleep, sleep_until, timeout_at, Instant},
};
use tokio_util::sync::CancellationToken;

const DEFAULT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(2);
pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(30);
// Sized against a real module restart, not a single bind: the daemon drains the
// module's routes (up to 30s), waits for the old process to stop (up to its stop
// budget, 25s by default), then boots the new one. A measured prefrontal-core
// restart kept route.open refused for 62.5s end to end, which a 30s budget gave
// up on halfway through. 90s covers that window with room for a slow boot. The
// retries still end at the call's own deadline (`CallOptions::timeout`) when
// that comes first, so a caller that wants to ride out a restart raises both.
pub const DEFAULT_ROUTE_RETRY_DEADLINE: Duration = Duration::from_secs(90);
/// The most route.open requests a consumer keeps outstanding on its connection.
/// Mirrors the daemon's `MAX_PENDING_ROUTE_OPENS_PER_CONNECTION`
/// (`crates/subc-daemon/src/server.rs`): the daemon refuses every open beyond
/// that many with a retryable `target_unavailable`, so sending more at once only
/// manufactures refusals. Extra opens wait here, first come first served, and the
/// wait counts against the same deadline as retrying refusals.
pub const MAX_ROUTE_OPENS_IN_FLIGHT: usize = 8;
const DEFAULT_RESTORED_DEBOUNCE: Duration = Duration::from_millis(250);
pub const DEFAULT_LIVENESS_PROBE_WINDOW: Duration = Duration::from_secs(2);
const EGRESS_BUFFER: usize = 128;
const DEFAULT_ROUTE_WINDOW: usize = 1024;
const DEFAULT_SUBSCRIPTION_EVENT_BUFFER: usize = 128;
const DEFAULT_PUSH_EVENT_BUFFER: usize = 128;
const REVERSE_REQUEST_UNHANDLED: &str = "reverse_request_unhandled";
/// The spawn stream's event buffer. A subscription from an old cursor receives the
/// daemon's whole retained ring at once (4096 events in the current daemon); a smaller
/// buffer would drop the stream on its own replay. Twice that leaves room for live
/// events arriving while the replay is being read.
const SPAWN_EVENT_BUFFER: usize = 8192;
// Hold the daemon's 1024-entry activity replay plus live entries without ending
// a healthy subscriber merely because its initial replay arrives in a burst.
const ACTIVITY_EVENT_BUFFER: usize = 2048;

#[cfg(test)]
#[path = "activity_consumer_tests.rs"]
mod activity_consumer_tests;

mod cancellation;
mod supervisor_ops;
pub use cancellation::{CancelHandle, CancelOutcome};
use cancellation::{CancelRegistration, UnaryCancel};
pub use supervisor_ops::{
    HealthProbeResponse, ServerDescription, StderrTailResponse, SupervisorAck,
    SupervisorHealthResponse, SupervisorProvenanceResponse,
};

/// `supervisor.spawn_subscribe` refused a cursor from another daemon incarnation.
pub const SPAWN_CURSOR_INCARNATION_MISMATCH: &str = "spawn_cursor_incarnation_mismatch";
/// `supervisor.spawn_subscribe` refused a cursor older than the daemon's retained ring.
pub const SPAWN_CURSOR_TOO_OLD: &str = "spawn_cursor_too_old";
/// The daemon dropped a spawn subscriber that fell too far behind.
pub const SPAWN_SUBSCRIBER_LAGGED: &str = "spawn_subscriber_lagged";

type ReverseRequestFuture =
    Pin<Box<dyn Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static>>;
type ReverseRequestHandler =
    Arc<dyn Fn(Vec<u8>, ReverseRequestContext) -> ReverseRequestFuture + Send + Sync + 'static>;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReverseRequestContext {
    pub corr: u64,
    pub method: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReverseRequestError {
    message: String,
}

impl ReverseRequestError {
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }
}

impl fmt::Display for ReverseRequestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl Error for ReverseRequestError {}

#[derive(Default)]
struct ReverseRequestRegistryState {
    handlers: HashMap<String, ReverseRequestHandler>,
    declared_families: Option<BTreeSet<String>>,
    consumer_capabilities: BTreeSet<String>,
}

/// Handler registry prepared before route.open. It carries the reverse-request
/// method families and any extra capability strings added through route options'
/// `with_consumer_capability` builder.
#[derive(Clone, Default)]
pub struct ReverseRequestRegistry {
    inner: Arc<Mutex<ReverseRequestRegistryState>>,
}

impl fmt::Debug for ReverseRequestRegistry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ReverseRequestRegistry")
            .field("capabilities", &self.capabilities())
            .field("consumer_capabilities", &self.consumer_capabilities())
            .finish()
    }
}

impl PartialEq for ReverseRequestRegistry {
    fn eq(&self, other: &Self) -> bool {
        self.capabilities() == other.capabilities()
            && self.consumer_capabilities() == other.consumer_capabilities()
    }
}

impl Eq for ReverseRequestRegistry {}

impl ReverseRequestRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn on_request<F, Fut>(
        &self,
        method_family: impl Into<String>,
        handler: F,
    ) -> Result<(), ReverseRequestRegistrationError>
    where
        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Vec<u8>> + Send + 'static,
    {
        self.on_request_fallible(method_family, move |body, ctx| {
            let future = handler(body, ctx);
            async move { Ok(future.await) }
        })
    }

    pub fn on_request_fallible<F, Fut>(
        &self,
        method_family: impl Into<String>,
        handler: F,
    ) -> Result<(), ReverseRequestRegistrationError>
    where
        F: Fn(Vec<u8>, ReverseRequestContext) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Vec<u8>, ReverseRequestError>> + Send + 'static,
    {
        let method_family = method_family.into();
        if !is_valid_method_family(&method_family) {
            return Err(ReverseRequestRegistrationError::InvalidFamily(
                method_family,
            ));
        }
        let mut state = self
            .inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if state
            .declared_families
            .as_ref()
            .is_some_and(|families| !families.contains(&method_family))
        {
            return Err(ReverseRequestRegistrationError::NotDeclared(method_family));
        }
        state.handlers.insert(
            method_family,
            Arc::new(move |body, ctx| Box::pin(handler(body, ctx))),
        );
        Ok(())
    }

    fn capabilities(&self) -> Vec<String> {
        let state = self
            .inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let mut capabilities = state.handlers.keys().cloned().collect::<Vec<_>>();
        capabilities.sort();
        capabilities
    }

    fn declare_consumer_capability(
        &self,
        capability: String,
    ) -> Result<(), ConsumerCapabilityError> {
        if capability.is_empty()
            || capability.len() > 64
            || !capability.bytes().all(|byte| (0x21..=0x7e).contains(&byte))
        {
            return Err(ConsumerCapabilityError { capability });
        }

        self.inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .consumer_capabilities
            .insert(capability);
        Ok(())
    }

    fn consumer_capabilities(&self) -> Vec<String> {
        self.inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .consumer_capabilities
            .iter()
            .cloned()
            .collect()
    }

    fn handler(&self, method_family: &str) -> Option<ReverseRequestHandler> {
        self.inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .handlers
            .get(method_family)
            .cloned()
    }

    pub(crate) fn seal(&self) {
        let mut state = self
            .inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if state.declared_families.is_none() {
            state.declared_families = Some(state.handlers.keys().cloned().collect());
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReverseRequestRegistrationError {
    InvalidFamily(String),
    NotDeclared(String),
    NotConsumerRoute,
}

impl fmt::Display for ReverseRequestRegistrationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidFamily(family) => {
                write!(f, "invalid reverse-request method family {family:?}")
            }
            Self::NotDeclared(family) => write!(
                f,
                "reverse-request capability {family:?} was not registered before route.open"
            ),
            Self::NotConsumerRoute => {
                f.write_str("route handle does not belong to a consumer route")
            }
        }
    }
}

impl Error for ReverseRequestRegistrationError {}

fn is_valid_method_family(value: &str) -> bool {
    let mut segments = value.split(['.', '_', '-']);
    segments.next().is_some_and(|segment| {
        segment
            .as_bytes()
            .first()
            .is_some_and(u8::is_ascii_lowercase)
            && segment
                .bytes()
                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
    }) && segments.all(|segment| {
        !segment.is_empty()
            && segment
                .bytes()
                .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
    })
}

/// Reverse-request handlers live in a process-global map keyed by an id the
/// `RouteHandle` carries, rather than inside the handle itself.
///
/// WHY, so nobody "simplifies" this into the handle later: `RouteHandle` is
/// `Copy`, deliberately and publicly. Every route-scoped call in this SDK takes
/// it by value, and the fleet's Rust consumers pass it around freely on that
/// assumption. An `Arc<ReverseRequestRegistry>` field would make it non-`Copy`
/// and break every one of those call sites across twelve repositories, for a
/// lane most of them do not use.
///
/// The cost is real and bounded: entries are removed on every teardown path
/// (`remove_route`, `remove_route_by_handle`, `drain_routes`,
/// `uninstall_route_handle`, `install_ingress_handle`), so a consumer that opens
/// and closes routes for its lifetime does not grow. A consumer DROPPED without
/// closing leaks its remaining entries until process exit, which is the one gap
/// and is acceptable because nothing else about a dropped consumer is reclaimed
/// either.
///
/// If `RouteHandle` ever stops being `Copy` for another reason, move this into
/// the handle and delete the map — the indirection exists only to preserve that
/// property.
static NEXT_REVERSE_REQUEST_REGISTRY_ID: AtomicU64 = AtomicU64::new(1);
static REVERSE_REQUEST_REGISTRIES: OnceLock<Mutex<HashMap<u64, ReverseRequestRegistry>>> =
    OnceLock::new();

fn reverse_request_registries() -> &'static Mutex<HashMap<u64, ReverseRequestRegistry>> {
    REVERSE_REQUEST_REGISTRIES.get_or_init(|| Mutex::new(HashMap::new()))
}

pub(crate) fn install_reverse_request_registry(registry: ReverseRequestRegistry) -> u64 {
    let id = crate::checked_increment(&NEXT_REVERSE_REQUEST_REGISTRY_ID)
        .expect("reverse-request route registry id exhausted");
    reverse_request_registries()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .insert(id, registry);
    id
}

pub(crate) fn route_reverse_request_registry(
    id: u64,
) -> Result<ReverseRequestRegistry, ReverseRequestRegistrationError> {
    if id == 0 {
        return Err(ReverseRequestRegistrationError::NotConsumerRoute);
    }
    reverse_request_registries()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .get(&id)
        .cloned()
        .ok_or(ReverseRequestRegistrationError::NotConsumerRoute)
}

fn release_reverse_request_registry(handle: RouteHandle) {
    let id = handle.reverse_request_registry_id();
    if id != 0 {
        reverse_request_registries()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .remove(&id);
    }
}

/// Capped exponential backoff used for reconnects and transient route-open retry.
/// Each delay is jittered before it is slept: half of it is kept and the other
/// half is random.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RetryBackoff {
    pub base: Duration,
    pub cap: Duration,
    /// Maximum attempts, including the first immediate attempt.
    pub max_attempts: usize,
}

impl Default for RetryBackoff {
    fn default() -> Self {
        Self {
            base: Duration::from_millis(100),
            cap: Duration::from_secs(2),
            max_attempts: 6,
        }
    }
}

impl RetryBackoff {
    fn delay_after_attempt(self, attempt: usize) -> Duration {
        let mut delay = self.base;
        for _ in 1..attempt {
            delay = (delay * 2).min(self.cap);
        }
        delay
    }
}

/// Options for [`SubcConsumer::connect`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConsumerOptions {
    pub handshake_timeout: Duration,
    /// Deadline for channel-0 calls that do not take per-call options.
    pub call_timeout: Duration,
    pub reconnect_backoff: RetryBackoff,
    pub restored_debounce: Duration,
    /// Window a post-deadline Ping waits for any inbound frame before the connection is
    /// treated as half-open. Exposed so callers can use a shorter deterministic test window.
    pub liveness_probe_window: Duration,
}

impl Default for ConsumerOptions {
    fn default() -> Self {
        Self {
            handshake_timeout: DEFAULT_HANDSHAKE_TIMEOUT,
            call_timeout: DEFAULT_CALL_TIMEOUT,
            reconnect_backoff: RetryBackoff::default(),
            restored_debounce: DEFAULT_RESTORED_DEBOUNCE,
            liveness_probe_window: DEFAULT_LIVENESS_PROBE_WINDOW,
        }
    }
}

/// A consumer-capability declaration was empty, contained whitespace or
/// non-printable/non-ASCII bytes, or exceeded 64 bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConsumerCapabilityError {
    capability: String,
}

impl ConsumerCapabilityError {
    /// The invalid declaration value.
    pub fn capability(&self) -> &str {
        &self.capability
    }
}

impl fmt::Display for ConsumerCapabilityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid consumer capability {:?}: expected 1-64 printable ASCII bytes without whitespace",
            self.capability
        )
    }
}

impl Error for ConsumerCapabilityError {}

/// Options for [`SubcConsumer::close_route`].
#[derive(Debug, Clone)]
pub struct CloseRouteOptions {
    /// Await in-flight unary requests on the route to settle naturally before tearing
    /// it down. Defaults to false: close immediately, settling anything in flight as
    /// at-most-once failures (outcome_unknown if already sent, not_sent otherwise).
    pub drain: bool,
    /// Upper bound on the drain wait (ignored when `drain` is false).
    pub drain_timeout: Duration,
    /// Override for the consumer identity used to locate the route being closed;
    /// when absent, SUBC_MODULE_ID and SUBC_LAUNCH_NONCE environment variables
    /// identify the route for a supervised consumer.
    pub consumer_identity: Option<ConsumerIdentity>,
    /// Reverse-request handlers plus extra capability strings added through
    /// [`Self::with_consumer_capability`]. Together, they identify the route being closed.
    pub reverse_requests: ReverseRequestRegistry,
    /// The role versions the route being closed was opened with (see
    /// [`CallOptions::role_versions`]); part of the route's identity.
    pub role_versions: Option<BTreeMap<String, String>>,
}

impl Default for CloseRouteOptions {
    fn default() -> Self {
        Self {
            drain: false,
            drain_timeout: DEFAULT_CALL_TIMEOUT,
            consumer_identity: None,
            reverse_requests: ReverseRequestRegistry::new(),
            role_versions: None,
        }
    }
}

impl CloseRouteOptions {
    /// Add a provider-contract capability declaration to the route identity.
    ///
    /// Values are merged with the reverse-request families. For example,
    /// `tool-result/v1` declares the tool-provider content result format; the
    /// declaration is not verified and grants no privilege.
    ///
    /// Like reverse-request handlers, declarations are kept in the options'
    /// shared reverse-request state, so options cloned before this call share
    /// the declaration. Add declarations before cloning options for other
    /// routes.
    pub fn with_consumer_capability(
        self,
        capability: impl Into<String>,
    ) -> Result<Self, ConsumerCapabilityError> {
        self.reverse_requests
            .declare_consumer_capability(capability.into())?;
        Ok(self)
    }

    /// The extra capability strings added with `with_consumer_capability`, not
    /// the reverse-request handler families. For example, `tool-result/v1` declares
    /// tool-provider content-result support; declarations are unverified and
    /// grant nothing.
    pub fn consumer_capabilities(&self) -> Vec<String> {
        self.reverse_requests.consumer_capabilities()
    }
}

/// Per-call options for [`SubcConsumer::call`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallOptions {
    /// Deadline for the whole managed call, including route-open retry and the response wait.
    pub timeout: Duration,
    pub priority: Priority,
    /// Admission behavior stamped into the request frame. Defaults to NORMAL.
    pub admission_class: AdmissionClass,
    pub route_retry: RetryBackoff,
    /// Maximum real-time limit for retrying route.open attempts when the target is temporarily absent.
    pub route_retry_deadline: Duration,
    /// Explicit consumer identity for route.open; when absent, non-empty SUBC_MODULE_ID and SUBC_LAUNCH_NONCE environment variables are used.
    pub consumer_identity: Option<ConsumerIdentity>,
    /// Reverse-request handlers plus extra capability strings added with
    /// [`Self::with_consumer_capability`]. For example, `tool-result/v1` declares
    /// tool-provider content-result support. These declarations are unverified
    /// and grant nothing; both sets are merged and omitted when empty.
    pub reverse_requests: ReverseRequestRegistry,
    /// The versions of provider roles this consumer speaks on the route, role
    /// name to version (`{"tool-provider": "v1"}`), sent on `route.open` and
    /// forwarded by the daemon to the provider's bind. An unverified
    /// declaration that grants nothing. Routes that differ only here are
    /// separate routes, so a legacy route and a versioned one to the same
    /// target are never shared; an empty map is the same as `None`.
    ///
    /// A daemon that does not advertise `route-role-versions/v1`
    /// ([`subc_protocol::scope::CAP_ROUTE_ROLE_VERSIONS_V1`]) drops the field
    /// without telling the provider, so check the capability before relying
    /// on it. A malformed map (see
    /// [`subc_protocol::session::validate_role_versions`]) is refused by the
    /// daemon as `invalid_request` and the call fails as not sent.
    pub role_versions: Option<BTreeMap<String, String>>,
}

impl Default for CallOptions {
    fn default() -> Self {
        Self {
            timeout: DEFAULT_CALL_TIMEOUT,
            priority: Priority::Interactive,
            admission_class: AdmissionClass::Normal,
            route_retry: RetryBackoff::default(),
            route_retry_deadline: DEFAULT_ROUTE_RETRY_DEADLINE,
            consumer_identity: None,
            reverse_requests: ReverseRequestRegistry::new(),
            role_versions: None,
        }
    }
}

impl CallOptions {
    /// Add a provider-contract capability declaration to the route.
    ///
    /// The list is merged with reverse-request handler families, sorted and
    /// de-duplicated. For example, `tool-result/v1` declares the tool-provider
    /// content result format. This remains an unverified declaration and grants
    /// no privilege. Invalid values are rejected here, before route.open can be
    /// sent.
    ///
    /// Like reverse-request handlers, declarations are kept in the options'
    /// shared reverse-request state, so options cloned before this call share
    /// the declaration. Add declarations before cloning options for other
    /// routes.
    pub fn with_consumer_capability(
        self,
        capability: impl Into<String>,
    ) -> Result<Self, ConsumerCapabilityError> {
        self.reverse_requests
            .declare_consumer_capability(capability.into())?;
        Ok(self)
    }

    /// The extra capability strings added with `with_consumer_capability`, not
    /// the reverse-request handler families. For example, `tool-result/v1` declares
    /// tool-provider content-result support; declarations are unverified and
    /// grant nothing.
    pub fn consumer_capabilities(&self) -> Vec<String> {
        self.reverse_requests.consumer_capabilities()
    }
}

/// Options for [`SubcConsumer::subscribe`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubscribeOptions {
    pub priority: Priority,
    /// Admission behavior stamped into the subscription request. Defaults to NORMAL.
    pub admission_class: AdmissionClass,
    /// Maximum number of events buffered for the caller before the subscription is dropped.
    /// The reader task never awaits a slow event consumer; if this bounded channel fills,
    /// `closed()` resolves with [`CallError::SubscriptionBackpressure`].
    pub event_buffer: usize,
    pub route_retry: RetryBackoff,
    /// Maximum real-time limit for retrying route.open attempts when the target is temporarily absent.
    pub route_retry_deadline: Duration,
    /// Deadline for opening the managed route and queuing the held-open request.
    /// The subscription itself has no response timeout once the request is sent.
    pub route_open_timeout: Duration,
    /// Explicit consumer identity for route.open; when absent, non-empty SUBC_MODULE_ID and SUBC_LAUNCH_NONCE environment variables are used.
    pub consumer_identity: Option<ConsumerIdentity>,
    /// Reverse-request handlers plus extra capability strings added with
    /// [`Self::with_consumer_capability`]. For example, `tool-result/v1` declares
    /// tool-provider content-result support. These declarations are unverified
    /// and grant nothing; both sets are merged and omitted when empty.
    pub reverse_requests: ReverseRequestRegistry,
    /// The role versions declared on the subscription's route; see
    /// [`CallOptions::role_versions`].
    pub role_versions: Option<BTreeMap<String, String>>,
}

impl Default for SubscribeOptions {
    fn default() -> Self {
        Self {
            priority: Priority::Interactive,
            admission_class: AdmissionClass::Normal,
            event_buffer: DEFAULT_SUBSCRIPTION_EVENT_BUFFER,
            route_retry: RetryBackoff::default(),
            route_retry_deadline: DEFAULT_ROUTE_RETRY_DEADLINE,
            route_open_timeout: DEFAULT_CALL_TIMEOUT,
            consumer_identity: None,
            reverse_requests: ReverseRequestRegistry::new(),
            role_versions: None,
        }
    }
}

impl SubscribeOptions {
    /// Add a provider-contract capability declaration to the subscription route.
    ///
    /// This merges with reverse-request families. For example, `tool-result/v1`
    /// declares the tool-provider content result format. The declaration is
    /// unverified and grants no privilege; invalid values are refused before
    /// route.open is sent.
    pub fn with_consumer_capability(
        self,
        capability: impl Into<String>,
    ) -> Result<Self, ConsumerCapabilityError> {
        self.reverse_requests
            .declare_consumer_capability(capability.into())?;
        Ok(self)
    }

    /// The extra capability strings added with `with_consumer_capability`, not
    /// the reverse-request handler families. For example, `tool-result/v1` declares
    /// tool-provider content-result support; declarations are unverified and
    /// grant nothing.
    pub fn consumer_capabilities(&self) -> Vec<String> {
        self.reverse_requests.consumer_capabilities()
    }
}

/// Minimal connection lifecycle signal. It is useful for logging and route-cache invalidation,
/// but callers must not use the consumer epoch as proof that a target provider is current.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConnectionState {
    Dropped,
    Restored { epoch: u64 },
}

/// Result of a route-scoped status or liveness poll.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoutePollResult {
    pub handle: RouteHandle,
    pub status: Option<String>,
    pub live: Option<bool>,
}

/// Typed response from the daemon's channel-0 `catalog.list` operation.
///
/// Each module entry exposes the provider roles and tool definitions advertised by
/// that module.
#[derive(Debug, Clone, serde::Deserialize, PartialEq)]
pub struct CatalogList {
    pub generation: u64,
    #[serde(default)]
    pub modules: Vec<CatalogEntry>,
    #[serde(default)]
    pub subc_ops: Vec<String>,
}

/// Typed response from the daemon's channel-0 `supervisor.list` operation.
///
/// Unlike `catalog.list`, this includes configured modules that are stopped or
/// disabled, along with their current supervisor state.
#[derive(Debug, Clone, PartialEq)]
pub struct SupervisorListResponse {
    pub generation: u64,
    pub modules: Vec<SupervisorEntry>,
}

/// A provider-originated push delivered on one live route.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PushEvent {
    /// The connection-fenced route identity on which the push arrived.
    pub handle: RouteHandle,
    /// Opaque payload bytes sent by the provider.
    pub body: Vec<u8>,
}

/// Disposition of one provider push at delivery time, so the two drop causes
/// land on their own counters (issue #40): the remedies differ.
enum DroppedPush {
    Delivered,
    NoReceiver,
    ReceiverFull,
}

/// A parsed daemon-originated channel-0 control push.
#[derive(Debug, Clone)]
pub struct ControlPush {
    /// The push discriminator, e.g. `route.closing` / `route.closed`.
    pub op: String,
    /// The full parsed body, `op` included, for op-specific fields.
    pub body: serde_json::Value,
}

/// A route-close reason accepted from the daemon control-push wire.
///
/// The protocol may add reasons before this SDK is upgraded. Preserve that fact
/// as [`Self::Unknown`] and classify it conservatively rather than refusing to
/// deliver the enclosing control push.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RouteCloseReason {
    Reload,
    Restart,
    Disable,
    Crash,
    CapabilityDenied,
    ScopeEnded,
    ScopeCarrierRemoved,
    ScopeDelegationChanged,
    ScopeParentEnded,
    Unknown(String),
}

/// Why a route ended. Even a planned closure can leave a call's outcome unknown.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RouteEndReason {
    Daemon(RouteCloseReason),
    ClosedByCaller,
    ConnectionLost,
    Unknown,
}

#[derive(Debug)]
struct RouteEnded {
    message: String,
    reason: RouteEndReason,
}

impl fmt::Display for RouteEnded {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}
impl Error for RouteEnded {}

/// Whether a closed route may be reopened automatically from its reason alone.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RouteCloseDisposition {
    MayReopen,
    MustNotReopen,
}

impl RouteCloseReason {
    /// Decode a wire reason without making a new daemon reason fatal to push delivery.
    pub fn from_wire(reason: &str) -> Self {
        match reason {
            "reload" => Self::Reload,
            "restart" => Self::Restart,
            "disable" => Self::Disable,
            "crash" => Self::Crash,
            "capability_denied" => Self::CapabilityDenied,
            "scope_ended" => Self::ScopeEnded,
            "scope_carrier_removed" => Self::ScopeCarrierRemoved,
            "scope_delegation_changed" => Self::ScopeDelegationChanged,
            "scope_parent_ended" => Self::ScopeParentEnded,
            other => Self::Unknown(other.to_string()),
        }
    }

    /// Unknown reasons take the strictest action: never reopen on their behalf.
    pub fn disposition(&self) -> RouteCloseDisposition {
        match self {
            Self::Reload | Self::Restart => RouteCloseDisposition::MayReopen,
            Self::Disable
            | Self::Crash
            | Self::CapabilityDenied
            | Self::ScopeEnded
            | Self::ScopeCarrierRemoved
            | Self::ScopeDelegationChanged
            | Self::ScopeParentEnded
            | Self::Unknown(_) => RouteCloseDisposition::MustNotReopen,
        }
    }
}

impl ControlPush {
    /// Decode the close reason from a route lifecycle push, if this is one.
    pub fn route_close_reason(&self) -> Option<RouteCloseReason> {
        matches!(self.op.as_str(), "route.closing" | "route.closed")
            .then(|| {
                self.body
                    .get("reason")?
                    .as_str()
                    .map(RouteCloseReason::from_wire)
            })
            .flatten()
    }
}

/// Managed Rust consumer for subc route calls.
pub struct SubcConsumer {
    shared: Arc<Shared>,
}

/// A managed unary reply with the module's raw-body declaration preserved.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallReply {
    body: Vec<u8>,
    binary: bool,
}

impl CallReply {
    /// The body bytes, unchanged from the terminal Response frame.
    /// A StreamEnd without a Response has an empty body.
    pub fn body(&self) -> &[u8] {
        &self.body
    }

    /// Consume the reply and return its body bytes without copying them.
    pub fn into_body(self) -> Vec<u8> {
        self.body
    }

    /// Whether the terminal Response carried `FLAG_BINARY` (raw bytes, not JSON).
    /// A StreamEnd without a Response returns `false`.
    pub fn is_binary(&self) -> bool {
        self.binary
    }
}

/// The first terminal outcome of a subscription.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum SubscriptionEnd {
    Response(Vec<u8>),
    StreamEnd,
    Error(ErrorBody),
    RouteClosed {
        reason: RouteEndReason,
    },
    ConnectionLost,
    Cancelled,
    /// The bounded event channel filled before the caller drained it.
    Backpressure,
}

/// A live subscription to a provider event stream.
///
/// The event receiver yields each `StreamData` payload for the held-open request's
/// correlation id. Await [`Subscription::closed`] to learn whether the provider ended
/// the stream cleanly (`Response` or `StreamEnd`) or the stream was rejected by an Error frame,
/// route GOODBYE, connection drop, or local backpressure. Dropping the subscription
/// sends a best-effort Cancel frame, the same as calling [`Subscription::unsubscribe`].
pub struct Subscription {
    events: mpsc::Receiver<Vec<u8>>,
    closed: SubscriptionClosed,
    ended: watch::Receiver<Option<SubscriptionEnd>>,
    cancel: SubscriptionCancel,
}

impl Subscription {
    /// Receive event payloads emitted as `StreamData` frames for this subscription.
    pub fn events(&mut self) -> &mut mpsc::Receiver<Vec<u8>> {
        &mut self.events
    }

    /// Future that resolves when the subscription reaches a terminal state.
    ///
    /// It resolves with `Ok(())` on `Response`, `StreamEnd` or local unsubscribe, and returns a
    /// [`CallError`] for module Error frames, route teardown, connection loss, or
    /// event-channel backpressure. Await it after the event receiver returns `None`
    /// to distinguish a clean end from an error.
    pub fn closed(&mut self) -> &mut SubscriptionClosed {
        &mut self.closed
    }

    /// Wait for the terminal outcome, retaining a Response body or module Error.
    ///
    /// This is independent of the one-shot [`Self::closed`] future: either can be
    /// awaited first, and `ended` can be awaited again after completion. Neither
    /// method reads frames; both observe the same pending request's settlement.
    pub async fn ended(&mut self) -> SubscriptionEnd {
        loop {
            if let Some(end) = self.ended.borrow().clone() {
                return end;
            }
            if self.ended.changed().await.is_err() {
                return SubscriptionEnd::ConnectionLost;
            }
        }
    }

    /// Cancel the held-open request.
    ///
    /// This sends a best-effort header-only Cancel frame for the subscription's
    /// `(channel, corr)` and settles [`Subscription::closed`] promptly with `Ok(())`.
    /// The provider may still send a terminal frame later; it is ignored because the
    /// local subscription is already closed.
    pub fn unsubscribe(&self) -> Result<(), CallError> {
        self.cancel.unsubscribe()
    }
}

impl Drop for Subscription {
    fn drop(&mut self) {
        let _ = self.cancel.unsubscribe();
    }
}

/// A held `supervisor.spawn_subscribe` request: the daemon's spawn events, in cursor
/// order, until the stream ends. Dropping it cancels the request.
pub struct SpawnSubscription {
    inner: Subscription,
    finished: bool,
}

impl SpawnSubscription {
    /// The next event. `Ok(None)` is a clean end (the daemon ended the stream, or it was
    /// unsubscribed); every later call returns it too.
    ///
    /// Every event the daemon queued before a terminal error is yielded first, so the
    /// last event received is the cursor to resume from. A refused cursor or a dropped
    /// subscriber comes back as the matching [`SpawnStreamError`] variant; anything else
    /// that ends the stream (connection loss, local backpressure, an event that does not
    /// decode) is [`SpawnStreamError::Call`] or [`SpawnStreamError::Decode`].
    pub async fn next(&mut self) -> Result<Option<SpawnEvent>, SpawnStreamError> {
        if self.finished {
            return Ok(None);
        }
        if let Some(body) = self.inner.events().recv().await {
            return serde_json::from_slice::<SpawnEvent>(&body)
                .map(Some)
                .map_err(|err| {
                    self.finished = true;
                    let _ = self.inner.unsubscribe();
                    SpawnStreamError::Decode(err.to_string())
                });
        }
        // Marked finished only once the terminal has been read: a caller that drops this
        // future mid-await (a `select!` arm) still gets the terminal on its next call.
        let terminal = self.inner.closed().await;
        self.finished = true;
        match terminal {
            Ok(()) => Ok(None),
            Err(err) => Err(SpawnStreamError::from_call_error(err)),
        }
    }

    /// Cancel the held request; the daemon releases the subscriber.
    pub fn unsubscribe(&self) -> Result<(), CallError> {
        self.inner.unsubscribe()
    }
}

/// Why a spawn stream ended with an error, by the daemon's code where it sent one.
#[derive(Debug)]
pub enum SpawnStreamError {
    /// `spawn_cursor_incarnation_mismatch`: the cursor names another daemon incarnation,
    /// so every event since it is unknowable from this daemon.
    CursorIncarnationMismatch {
        current_daemon_incarnation: String,
        body: Box<ErrorBody>,
    },
    /// `spawn_cursor_too_old`: events after the cursor have left the daemon's ring.
    CursorTooOld {
        oldest_retained_cursor: SpawnCursor,
        body: Box<ErrorBody>,
    },
    /// `spawn_subscriber_lagged`: the daemon dropped this subscriber for falling behind,
    /// after delivering every event it had queued for it.
    SubscriberLagged {
        first_undelivered_cursor: SpawnCursor,
        body: Box<ErrorBody>,
    },
    /// Any other end: another daemon error (one of the codes above with a detail that
    /// does not parse included, so its code is still readable), connection loss, or
    /// local backpressure.
    Call(CallError),
    /// An event body that is not a `SpawnEvent`.
    Decode(String),
}

impl SpawnStreamError {
    fn from_call_error(err: CallError) -> Self {
        let CallError::Module(body) = err else {
            return Self::Call(err);
        };
        let detail = |key: &str| body.detail.as_ref().and_then(|detail| detail.get(key));
        let cursor = |key: &str| {
            detail(key).and_then(|value| serde_json::from_value::<SpawnCursor>(value.clone()).ok())
        };
        match body.code.as_str() {
            SPAWN_CURSOR_INCARNATION_MISMATCH => {
                match detail("current_daemon_incarnation").and_then(|value| value.as_str()) {
                    Some(current) => Self::CursorIncarnationMismatch {
                        current_daemon_incarnation: current.to_string(),
                        body: Box::new(body),
                    },
                    None => Self::Call(CallError::Module(body)),
                }
            }
            SPAWN_CURSOR_TOO_OLD => match cursor("oldest_retained_cursor") {
                Some(oldest_retained_cursor) => Self::CursorTooOld {
                    oldest_retained_cursor,
                    body: Box::new(body),
                },
                None => Self::Call(CallError::Module(body)),
            },
            SPAWN_SUBSCRIBER_LAGGED => match cursor("first_undelivered_cursor") {
                Some(first_undelivered_cursor) => Self::SubscriberLagged {
                    first_undelivered_cursor,
                    body: Box::new(body),
                },
                None => Self::Call(CallError::Module(body)),
            },
            _ => Self::Call(CallError::Module(body)),
        }
    }

    /// The daemon's error code, when the stream ended with one.
    pub fn code(&self) -> Option<&str> {
        match self {
            Self::CursorIncarnationMismatch { .. } => Some(SPAWN_CURSOR_INCARNATION_MISMATCH),
            Self::CursorTooOld { .. } => Some(SPAWN_CURSOR_TOO_OLD),
            Self::SubscriberLagged { .. } => Some(SPAWN_SUBSCRIBER_LAGGED),
            Self::Call(err) => err.code(),
            Self::Decode(_) => None,
        }
    }
}

impl fmt::Display for SpawnStreamError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CursorIncarnationMismatch {
                current_daemon_incarnation,
                ..
            } => write!(
                f,
                "{SPAWN_CURSOR_INCARNATION_MISMATCH}: the daemon is incarnation \
                 {current_daemon_incarnation}"
            ),
            Self::CursorTooOld {
                oldest_retained_cursor,
                ..
            } => write!(
                f,
                "{SPAWN_CURSOR_TOO_OLD}: the oldest retained event is seq {}",
                oldest_retained_cursor.seq
            ),
            Self::SubscriberLagged {
                first_undelivered_cursor,
                ..
            } => write!(
                f,
                "{SPAWN_SUBSCRIBER_LAGGED}: the first undelivered event is seq {}",
                first_undelivered_cursor.seq
            ),
            Self::Call(err) => write!(f, "spawn stream ended: {err}"),
            Self::Decode(message) => write!(f, "spawn event did not decode: {message}"),
        }
    }
}

impl Error for SpawnStreamError {}

/// Future returned by [`Subscription::closed`].
pub struct SubscriptionClosed {
    rx: oneshot::Receiver<Result<(), CallError>>,
}

impl Unpin for SubscriptionClosed {}

impl Future for SubscriptionClosed {
    type Output = Result<(), CallError>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();
        match Pin::new(&mut this.rx).poll(cx) {
            Poll::Ready(Ok(result)) => Poll::Ready(result),
            Poll::Ready(Err(_)) => Poll::Ready(Err(CallError::outcome_unknown(
                "subscription closed result channel dropped",
                OutcomeUnknownCause::CompletionFailed,
            ))),
            Poll::Pending => Poll::Pending,
        }
    }
}

struct SubscriptionCancel {
    shared: Arc<Shared>,
    key: PendingKey,
    priority: Priority,
    cancelled: AtomicBool,
}

impl SubscriptionCancel {
    fn new(shared: Arc<Shared>, key: PendingKey, priority: Priority) -> Self {
        Self {
            shared,
            key,
            priority,
            cancelled: AtomicBool::new(false),
        }
    }

    fn unsubscribe(&self) -> Result<(), CallError> {
        let handle = RouteHandle::new(self.key.channel, self.key.epoch, self.key.generation);
        self.shared.validate_current_handle(handle)?;
        if self.cancelled.swap(true, Ordering::AcqRel) {
            return Ok(());
        }
        self.shared
            .unsubscribe_subscription(self.key, self.priority)
    }
}

impl SubcConsumer {
    /// Connect through an explicit connection-file path. The initial connection
    /// generation uses epoch 1; each reconnect advances it.
    pub async fn connect(
        connection_file: &Path,
        opts: ConsumerOptions,
    ) -> Result<Self, ConsumerError> {
        let opened = open_connection(connection_file, opts.handshake_timeout).await?;
        let shared = Arc::new(Shared::new(connection_file.to_path_buf(), opts));
        shared.install_initial(opened)?;
        Ok(Self { shared })
    }

    /// Discover the daemon's connection file, authenticate, and start the I/O loop.
    pub async fn connect_default(opts: ConsumerOptions) -> Result<Self, ConsumerError> {
        let discovered = connection_file::discover(None)
            .map_err(|source| ConsumerError::Discovery { source })?;
        let opened =
            open_connection_with_info(&discovered.path, &discovered.info, opts.handshake_timeout)
                .await?;
        let shared = Arc::new(Shared::new(discovered.path, opts));
        shared.install_initial(opened)?;
        Ok(Self { shared })
    }

    /// Open or reuse a managed route and return its connection-fenced handle.
    pub async fn open_route(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        opts: CallOptions,
    ) -> Result<RouteHandle, CallError> {
        let deadline = Instant::now() + opts.timeout;
        let consumer_identity = route_open_consumer_identity(&opts);
        let consumer_capabilities = route_open_consumer_capabilities(&opts);
        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
        let key = RouteKey::new(
            &target,
            &identity,
            consumer_identity.as_ref(),
            consumer_capabilities.as_deref(),
        )
        .with_role_versions(role_versions.as_ref());
        let params = RouteOpenParams {
            target: &target,
            identity: &identity,
            consumer_identity: &consumer_identity,
            consumer_capabilities: &consumer_capabilities,
            role_versions: &role_versions,
            reverse_requests: &opts.reverse_requests,
            scope: None,
        };
        self.shared
            .ensure_route(&key, &params, &opts, deadline)
            .await
            .map(|route| route.handle)
    }

    /// Open or reuse a managed route admitted under `scope`, and return its
    /// connection-fenced handle.
    ///
    /// This is how a carrier opens its onward route for a session. The daemon
    /// admits the open only when the opener (the consumer identity in `opts`,
    /// or the supervised module's own identity from the environment) is the
    /// scope's owner or one of its listed carriers, and it stamps the
    /// provider's bind with the scope. `scope.scope_epoch` must be set: the
    /// daemon refuses an open without it (`scope_epoch_required`).
    ///
    /// The route is cached under the whole selector (owner, ref and epoch) as
    /// well as the target and identities, so a route opened under one scope or
    /// epoch is never returned to a caller asking for another, and a scoped
    /// route is never returned by [`Self::open_route`] (nor an unscoped one
    /// here). Once the route closes, the next call with the same selector opens
    /// a fresh route under that selector. Close it early with
    /// [`Self::close_handle`].
    ///
    /// Refusals: `scope_not_synced` (the owner has not synced since the daemon
    /// started) and `scope_changed` (the scope changed while the bind was in
    /// flight) are retried within the call's deadline, like a module reload.
    /// `scope_ended`, `scope_not_live`, `scope_epoch_required` and
    /// `scope_not_carrier` end the call at once as [`CallError::NotSent`], with
    /// the daemon's code in [`CallError::route_open_refusal`].
    ///
    /// When the daemon later closes the route because its scope ended or the
    /// opener's authority under it was revoked, [`Self::control_pushes`]
    /// delivers `route.closed` with a `scope_*` reason. Its
    /// [`RouteCloseReason::disposition`] is
    /// [`RouteCloseDisposition::MustNotReopen`]: the session the route served is
    /// over, so do not open it again under the same selector.
    pub async fn open_route_scoped(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        scope: ScopeSelector,
        opts: CallOptions,
    ) -> Result<RouteHandle, CallError> {
        let deadline = Instant::now() + opts.timeout;
        let consumer_identity = route_open_consumer_identity(&opts);
        let consumer_capabilities = route_open_consumer_capabilities(&opts);
        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
        let key = RouteKey::new(
            &target,
            &identity,
            consumer_identity.as_ref(),
            consumer_capabilities.as_deref(),
        )
        .with_role_versions(role_versions.as_ref())
        .with_scope(Some(&scope));
        let params = RouteOpenParams {
            target: &target,
            identity: &identity,
            consumer_identity: &consumer_identity,
            consumer_capabilities: &consumer_capabilities,
            role_versions: &role_versions,
            reverse_requests: &opts.reverse_requests,
            scope: Some(&scope),
        };
        self.shared
            .ensure_route(&key, &params, &opts, deadline)
            .await
            .map(|route| route.handle)
    }

    /// Open one admitted route without entering the managed route cache.
    ///
    /// Admitted routes are never cached or reopened after a connection drop. If
    /// this call fails or the route later closes, the caller must perform admission
    /// again and call this method with fresh facts.
    ///
    /// The route declares no reverse-request capabilities, so the provider cannot
    /// send it requests. Use [`Self::open_route_with_admission_facts_and_options`]
    /// when the provider asks the consumer questions on the route (elicitation).
    pub async fn open_route_with_admission_facts(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        facts: serde_json::Value,
    ) -> Result<RouteHandle, CallError> {
        let deadline = Instant::now() + self.shared.opts.call_timeout;
        self.open_admitted_route(
            target,
            identity,
            facts,
            &CallOptions::default(),
            None,
            deadline,
        )
        .await
    }

    /// Open one admitted route, with the reverse-request handlers, capability
    /// declarations and timeout in `opts`.
    ///
    /// The route declares the method families of handlers registered on
    /// `opts.reverse_requests`, together with any provider-contract declarations
    /// in the extra declarations reported by `opts.consumer_capabilities()`. For example, `tool-result/v1` declares the
    /// tool-provider content result format. These are unverified declarations,
    /// not privilege grants. Requests the provider sends back (elicitation,
    /// sampling) reach the registered handlers, exactly as on a managed route.
    /// Handlers must be registered before this call: the registry is sealed
    /// when the route opens, because the declared method families are what the
    /// provider was told.
    ///
    /// Like [`Self::open_route_with_admission_facts`], the route is never cached
    /// or reopened; after a failure or a close the caller performs admission again.
    pub async fn open_route_with_admission_facts_and_options(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        facts: serde_json::Value,
        opts: CallOptions,
    ) -> Result<RouteHandle, CallError> {
        let deadline = Instant::now() + opts.timeout;
        let reverse_requests = opts.reverse_requests.clone();
        self.open_admitted_route(
            target,
            identity,
            facts,
            &opts,
            Some(reverse_requests),
            deadline,
        )
        .await
    }

    /// One admitted route.open. With `reverse_requests`, the route is opened the
    /// way the managed path opens one: the capabilities are declared, the socket
    /// reader installs the handle before the open resolves (so a request the
    /// provider sends right after binding is not lost), and the handle carries
    /// the registry. Without it, the route has no reverse-request handling.
    async fn open_admitted_route(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        facts: serde_json::Value,
        opts: &CallOptions,
        reverse_requests: Option<ReverseRequestRegistry>,
        deadline: Instant,
    ) -> Result<RouteHandle, CallError> {
        let consumer_capabilities = route_open_consumer_capabilities(opts);
        let target_label = route_target_label(&target);
        let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
            target,
            identity,
            consumer_identity: route_open_consumer_identity(opts),
            consumer_capabilities,
            role_versions: route_open_role_versions(opts.role_versions.as_ref()),
            admission_facts: Some(facts),
            scope: None,
        })
        .map_err(|err| CallError::not_sent(format!("failed to encode route.open: {err}")))?;

        let terminal = self
            .shared
            .paced_route_open(body, deadline, reverse_requests.clone())
            .await?;
        let (generation, body) = match terminal {
            TerminalFrame::Response {
                generation, body, ..
            } => (generation, body),
            // The daemon refused the open. Keep its code and detail, as the
            // plain route.open does, so a caller can tell "retry shortly"
            // (module_warming) from "this configuration will never work"
            // (admission_facts_not_permitted).
            TerminalFrame::Error { body, .. } => {
                return Err(CallError::route_open_refused(target_label, body));
            }
            _ => {
                return Err(CallError::not_sent(
                    "route.open returned a non-response frame",
                ));
            }
        };
        let ClientControlResponse::RouteOpen {
            route_channel,
            route_epoch,
        } = serde_json::from_slice(&body).map_err(|err| {
            CallError::not_sent(format!("failed to decode route.open response: {err}"))
        })?
        else {
            return Err(CallError::not_sent(
                "route.open returned an unexpected control response",
            ));
        };
        // Adopt the handle the socket reader installed for this response, which
        // carries the registry passed to control_call; build one only if the
        // reader did not (the connection moved on before the response landed).
        let handle = self
            .shared
            .ingress_handle(generation, route_channel, route_epoch)
            .unwrap_or_else(|| match reverse_requests {
                Some(reverse_requests) => RouteHandle::new_consumer(
                    route_channel,
                    route_epoch,
                    generation,
                    reverse_requests,
                ),
                None => RouteHandle::new(route_channel, route_epoch, generation),
            });
        let route = RouteState {
            handle,
            sem: Arc::new(Semaphore::new(DEFAULT_ROUTE_WINDOW)),
        };
        self.shared.install_one_shot_route(route.clone())?;
        Ok(route.handle)
    }

    /// Fetch the daemon's module catalog over channel 0.
    /// Transport retries use the consumer's reconnect backoff and call deadline.
    pub async fn catalog_list(&self) -> Result<CatalogList, CallError> {
        let deadline = Instant::now() + self.shared.opts.call_timeout;
        let body = serde_json::to_vec(&serde_json::json!({
            "op": subc_control::ops::CATALOG_LIST,
        }))
        .map_err(|err| CallError::not_sent(format!("failed to encode catalog.list: {err}")))?;

        let mut attempt = 0usize;
        loop {
            attempt = attempt.saturating_add(1);
            match self
                .shared
                .control_call(body.clone(), deadline, false, None)
                .await
            {
                Ok(TerminalFrame::Response { body, .. }) => {
                    let response =
                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
                            CallError::not_sent(format!(
                                "failed to decode catalog.list response: {err}"
                            ))
                        })?;
                    let ClientControlResponse::CatalogList {
                        generation,
                        modules,
                        subc_ops,
                    } = response
                    else {
                        return Err(CallError::not_sent(
                            "catalog.list returned an unexpected control response",
                        ));
                    };
                    return Ok(CatalogList {
                        generation,
                        modules,
                        subc_ops,
                    });
                }
                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
                Ok(TerminalFrame::StreamEnd) => {
                    return Err(CallError::not_sent("catalog.list returned StreamEnd"));
                }
                Err(err)
                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
                {
                    // Connection-file and discovery failures can complete without
                    // yielding. Pace the outer retry as well as reconnect itself,
                    // so repeated immediate failures cannot monopolize the executor.
                    let delay = self.shared.jittered(
                        self.shared
                            .opts
                            .reconnect_backoff
                            .delay_after_attempt(attempt),
                    );
                    self.shared.sleep_until_retry(deadline, delay).await?;
                    continue;
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Fetch the supervisor's configured module list over channel 0.
    /// Transport retries use the consumer's reconnect backoff and call deadline.
    pub async fn supervisor_list(&self) -> Result<SupervisorListResponse, CallError> {
        let deadline = Instant::now() + self.shared.opts.call_timeout;
        let body = serde_json::to_vec(&ClientControlRequest::SupervisorList {}).map_err(|err| {
            CallError::not_sent(format!("failed to encode supervisor.list: {err}"))
        })?;

        let mut attempt = 0usize;
        loop {
            attempt = attempt.saturating_add(1);
            match self
                .shared
                .control_call(body.clone(), deadline, false, None)
                .await
            {
                Ok(TerminalFrame::Response { body, .. }) => {
                    let response =
                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
                            CallError::not_sent(format!(
                                "failed to decode supervisor.list response: {err}"
                            ))
                        })?;
                    let ClientControlResponse::SupervisorList {
                        generation,
                        modules,
                    } = response
                    else {
                        return Err(CallError::not_sent(
                            "supervisor.list returned an unexpected control response",
                        ));
                    };
                    return Ok(SupervisorListResponse {
                        generation,
                        modules,
                    });
                }
                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
                Ok(TerminalFrame::StreamEnd) => {
                    return Err(CallError::not_sent("supervisor.list returned StreamEnd"));
                }
                Err(err)
                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
                {
                    // Pace immediate discovery failures so retries cannot monopolize the executor.
                    let delay = self.shared.jittered(
                        self.shared
                            .opts
                            .reconnect_backoff
                            .delay_after_attempt(attempt),
                    );
                    self.shared.sleep_until_retry(deadline, delay).await?;
                    continue;
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Fetch the supervisor's atomic spawn snapshot (`supervisor.spawn_snapshot`)
    /// over channel 0: the live processes with their spawn generations, and the
    /// cursor at which they were observed.
    ///
    /// A daemon refusal comes back as [`CallError::Module`], so its code is readable
    /// through [`CallError::code`]. Transport failures are retried until the
    /// consumer's call deadline with its reconnect backoff, as for
    /// [`SubcConsumer::catalog_list`].
    pub async fn spawn_snapshot(&self) -> Result<SpawnSnapshot, CallError> {
        let deadline = Instant::now() + self.shared.opts.call_timeout;
        let body = serde_json::to_vec(&ClientControlRequest::SupervisorSpawnSnapshot {}).map_err(
            |err| CallError::not_sent(format!("failed to encode supervisor.spawn_snapshot: {err}")),
        )?;

        let mut attempt = 0usize;
        loop {
            attempt = attempt.saturating_add(1);
            match self
                .shared
                .control_call(body.clone(), deadline, false, None)
                .await
            {
                Ok(TerminalFrame::Response { body, .. }) => {
                    let response =
                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
                            CallError::not_sent(format!(
                                "failed to decode supervisor.spawn_snapshot response: {err}"
                            ))
                        })?;
                    let ClientControlResponse::SupervisorSpawnSnapshot { snapshot } = response
                    else {
                        return Err(CallError::not_sent(
                            "supervisor.spawn_snapshot returned an unexpected control response",
                        ));
                    };
                    return Ok(snapshot);
                }
                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
                Ok(TerminalFrame::StreamEnd) => {
                    return Err(CallError::not_sent(
                        "supervisor.spawn_snapshot returned StreamEnd",
                    ));
                }
                Err(err)
                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
                {
                    let delay = self.shared.jittered(
                        self.shared
                            .opts
                            .reconnect_backoff
                            .delay_after_attempt(attempt),
                    );
                    self.shared.sleep_until_retry(deadline, delay).await?;
                    continue;
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Query the newest-first activity ledger. The reply preserves entries, the
    /// continuation cursor and the head to subscribe from without a query/follow gap.
    /// Identity is filled from the supervised launch environment, as for route.open;
    /// without one the daemon treats the caller as Direct. Refusals retain their code
    /// through [`CallError::code`]. Transport retries are paced to the call deadline.
    pub async fn query_activity(
        &self,
        request: ActivityQueryRequest,
    ) -> Result<ActivityQueryResponse, CallError> {
        let deadline = Instant::now() + self.shared.opts.call_timeout;
        let body = activity_read_body(request)?;
        let mut attempt = 0usize;
        loop {
            attempt = attempt.saturating_add(1);
            match self
                .shared
                .control_call(body.clone(), deadline, false, None)
                .await
            {
                Ok(TerminalFrame::Response { body, .. }) => {
                    return serde_json::from_slice(&body).map_err(|err| {
                        CallError::not_sent(format!("invalid activity.query response: {err}"))
                    });
                }
                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
                Ok(TerminalFrame::StreamEnd) => {
                    return Err(CallError::not_sent("activity.query returned StreamEnd"));
                }
                Err(err)
                    if is_retryable_catalog_transport_error(&err) && Instant::now() < deadline =>
                {
                    let delay = self.shared.jittered(
                        self.shared
                            .opts
                            .reconnect_backoff
                            .delay_after_attempt(attempt),
                    );
                    self.shared.sleep_until_retry(deadline, delay).await?;
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Follow durable activity entries after `since`, or from now if absent.
    /// The launch identity is filled as for [`Self::query_activity`]. Refused cursors
    /// and subscriber lag are terminal stream errors whose daemon code is readable
    /// through [`crate::ActivityStreamError::code`]. On reconnect the stream ends;
    /// recover with a query and subscribe from its head.
    pub async fn subscribe_activity(
        &self,
        since: Option<ActivityCursor>,
    ) -> Result<ActivitySubscription, CallError> {
        let deadline = Instant::now() + self.shared.opts.call_timeout;
        let body = activity_read_body(ActivitySubscribeRequest { since })?;
        loop {
            self.shared.ensure_connected_for_call(deadline).await?;
            let permit = Arc::new(Semaphore::new(1))
                .acquire_owned()
                .await
                .map_err(|_| CallError::not_sent("activity subscription permit closed"))?;
            match self
                .shared
                .send_subscription(SubscriptionSend {
                    expected_handle: None,
                    channel: 0,
                    epoch: 0,
                    body: body.clone(),
                    priority: Priority::Interactive,
                    admission_class: AdmissionClass::Normal,
                    event_buffer: ACTIVITY_EVENT_BUFFER,
                    deadline,
                    permit,
                })
                .await
            {
                Ok(inner) => {
                    return Ok(ActivitySubscription {
                        inner,
                        finished: false,
                    })
                }
                Err(err) if err.is_not_sent() && Instant::now() < deadline => continue,
                Err(err) => return Err(err),
            }
        }
    }

    /// Follow the supervisor's spawn event stream (`supervisor.spawn_subscribe`) over
    /// channel 0, from just after `since` (a cursor copied from a snapshot or an event),
    /// or from now when `since` is `None`.
    ///
    /// The request is held open: the returned [`SpawnSubscription`] yields each event
    /// until the stream ends. A cursor the daemon refuses, and the daemon dropping a
    /// subscriber that fell behind, arrive as the stream's terminal error (see
    /// [`SpawnStreamError`]). A reconnect ends the stream; the caller resubscribes from
    /// the last cursor it received. Sending is retried until the consumer's call
    /// deadline, as for [`SubcConsumer::spawn_snapshot`].
    pub async fn spawn_subscribe(
        &self,
        since: Option<SpawnCursor>,
    ) -> Result<SpawnSubscription, CallError> {
        let deadline = Instant::now() + self.shared.opts.call_timeout;
        let body = serde_json::to_vec(&ClientControlRequest::SupervisorSpawnSubscribe { since })
            .map_err(|err| {
                CallError::not_sent(format!(
                    "failed to encode supervisor.spawn_subscribe: {err}"
                ))
            })?;
        loop {
            self.shared.ensure_connected_for_call(deadline).await?;
            // Channel 0 has no route flow-control window; the subscription holds a
            // permit of its own so it is shaped like a route subscription.
            let permit = Arc::new(Semaphore::new(1))
                .acquire_owned()
                .await
                .map_err(|_| CallError::not_sent("spawn subscription permit closed"))?;
            match self
                .shared
                .send_subscription(SubscriptionSend {
                    expected_handle: None,
                    channel: 0,
                    epoch: 0,
                    body: body.clone(),
                    priority: Priority::Interactive,
                    admission_class: AdmissionClass::Normal,
                    event_buffer: SPAWN_EVENT_BUFFER,
                    deadline,
                    permit,
                })
                .await
            {
                Ok(inner) => {
                    return Ok(SpawnSubscription {
                        inner,
                        finished: false,
                    })
                }
                Err(err) if err.is_not_sent() && Instant::now() < deadline => continue,
                Err(err) => return Err(err),
            }
        }
    }

    /// Resolve the sole catalog claimant for a capability.
    ///
    /// Resolution is deliberately based only on the static capabilities mirror in
    /// `catalog.list`; module ids and role names are not fallback claims. Calling
    /// this method expresses singular intent, so a plural catalog result is an
    /// explicit ambiguity rather than an arbitrary choice.
    pub async fn resolve_provider(&self, capability: &str) -> Result<String, CallError> {
        let claimants = self.resolve_providers(capability).await?;
        match claimants.as_slice() {
            [] => Err(CallError::CapabilityUnprovided {
                capability: capability.to_string(),
            }),
            [claimant] => Ok(claimant.clone()),
            _ => Err(CallError::CapabilityAmbiguous {
                capability: capability.to_string(),
                claimants,
            }),
        }
    }

    /// Resolve every catalog claimant for a capability in module-id order.
    ///
    /// The identifier is validated before any channel-0 request is made, so a
    /// typo cannot become a network-dependent "unprovided" result.
    pub async fn resolve_providers(&self, capability: &str) -> Result<Vec<String>, CallError> {
        validate_capability_for_resolution(capability)?;
        let catalog = self.catalog_list().await?;
        Ok(capability_claimants(&catalog, capability))
    }

    /// Send one request using an already-opened route handle.
    pub async fn request(
        &self,
        handle: &RouteHandle,
        body: Vec<u8>,
        opts: CallOptions,
    ) -> Result<Vec<u8>, CallError> {
        self.request_inner(handle, body, opts, None).await
    }

    /// Like [`Self::request`], with explicit cancellation of the in-flight request.
    ///
    /// The returned future is lazy and has the same result and deadline as `request`.
    /// Calling [`CancelHandle::cancel`] sends at most one header-only Cancel on the
    /// request's route; it does not stop waiting for the provider's Response or Error.
    /// Dropping the handle sends nothing. Dropping the future only removes its
    /// pending registration, **without sending Cancel**.
    ///
    /// ```no_run
    /// # async fn turn(consumer: &subc_client_rs::SubcConsumer,
    /// # route: &subc_client_rs::RouteHandle,
    /// # turn_stopped: impl std::future::Future<Output = ()>) -> Result<(), subc_client_rs::CallError> {
    /// let (cancel, reply) = consumer.request_cancellable(
    ///     route, b"work".to_vec(), subc_client_rs::CallOptions::default());
    /// tokio::pin!(reply);
    /// tokio::select! {
    ///     result = &mut reply => { let _body = result?; }
    ///     () = turn_stopped => {
    ///         cancel.cancel().await;
    ///         let _body = reply.await?; // Keep any final Response body.
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn request_cancellable(
        &self,
        handle: &RouteHandle,
        body: Vec<u8>,
        opts: CallOptions,
    ) -> (
        CancelHandle,
        impl Future<Output = Result<Vec<u8>, CallError>> + Send + '_,
    ) {
        let consumer = self;
        let handle = *handle;
        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
        let future = async move {
            let guard = registration;
            consumer
                .request_inner(&handle, body, opts, Some(Arc::clone(&guard.state)))
                .await
        };
        (cancel, future)
    }

    async fn request_inner(
        &self,
        handle: &RouteHandle,
        body: Vec<u8>,
        opts: CallOptions,
        cancel: Option<Arc<UnaryCancel>>,
    ) -> Result<Vec<u8>, CallError> {
        let deadline = Instant::now() + opts.timeout;
        let route = self.shared.route_state(*handle)?;
        let permit = match timeout_at(deadline, Arc::clone(&route.sem).acquire_owned()).await {
            Ok(Ok(permit)) => permit,
            Ok(Err(_)) => return Err(CallError::StaleRouteHandle(*handle)),
            Err(_) => {
                return Err(CallError::not_sent(
                    "call deadline elapsed waiting for route flow-control",
                ))
            }
        };
        let result = self
            .shared
            .send_request_cancellable(
                RequestSend {
                    binary: false,
                    expected_handle: Some(*handle),
                    channel: handle.channel,
                    epoch: handle.epoch,
                    body,
                    priority: opts.priority,
                    admission_class: opts.admission_class,
                    deadline,
                    retain_late_route_open: false,
                    route_open_reverse_requests: None,
                },
                cancel,
            )
            .await;
        drop(permit);
        match result? {
            TerminalFrame::Response { body, .. } => Ok(body),
            TerminalFrame::StreamEnd => Ok(Vec::new()),
            TerminalFrame::Error { body, .. } => Err(CallError::Module(body)),
        }
    }

    /// Start a held-open request using an already-opened route handle.
    pub async fn subscribe_route(
        &self,
        handle: &RouteHandle,
        body: Vec<u8>,
        opts: SubscribeOptions,
    ) -> Result<Subscription, CallError> {
        let deadline = Instant::now() + opts.route_open_timeout;
        let route = self.shared.route_state(*handle)?;
        let permit = match timeout_at(deadline, Arc::clone(&route.sem).acquire_owned()).await {
            Ok(Ok(permit)) => permit,
            Ok(Err(_)) => return Err(CallError::StaleRouteHandle(*handle)),
            Err(_) => {
                return Err(CallError::not_sent(
                    "subscription deadline elapsed waiting for route flow-control",
                ))
            }
        };
        self.shared
            .send_subscription(SubscriptionSend {
                expected_handle: Some(*handle),
                channel: handle.channel,
                epoch: handle.epoch,
                body,
                priority: opts.priority,
                admission_class: opts.admission_class,
                event_buffer: opts.event_buffer,
                deadline,
                permit,
            })
            .await
    }

    /// Poll status or liveness for exactly this route handle.
    /// A daemon refusal is returned as [`CallError::Module`] with its original body.
    pub async fn poll_route(
        &self,
        handle: &RouteHandle,
        kind: PollKind,
        timeout: Duration,
    ) -> Result<RoutePollResult, CallError> {
        let deadline = Instant::now() + timeout;
        let body = serde_json::to_vec(&ClientControlRequest::RoutePoll {
            route_channel: handle.channel,
            route_epoch: handle.epoch,
            kind,
        })
        .map_err(|err| CallError::not_sent(format!("failed to encode route.poll: {err}")))?;
        let terminal = self
            .shared
            .send_request(RequestSend {
                binary: false,
                expected_handle: Some(*handle),
                channel: 0,
                epoch: 0,
                body,
                priority: Priority::Interactive,
                admission_class: AdmissionClass::Normal,
                deadline,
                retain_late_route_open: false,
                route_open_reverse_requests: None,
            })
            .await?;
        let body = match terminal {
            TerminalFrame::Response { body, .. } => body,
            TerminalFrame::Error { body, .. } => return Err(CallError::Module(body)),
            TerminalFrame::StreamEnd => {
                return Err(CallError::not_sent(
                    "route.poll returned a non-response frame",
                ));
            }
        };
        let ClientControlResponse::RoutePoll {
            route_channel,
            route_epoch,
            status,
            live,
        } = serde_json::from_slice(&body)
            .map_err(|err| CallError::not_sent(format!("failed to decode route.poll: {err}")))?
        else {
            return Err(CallError::not_sent(
                "route.poll returned an unexpected control response",
            ));
        };
        if route_channel != handle.channel || route_epoch != handle.epoch {
            return Err(CallError::not_sent(
                "route.poll response echoed a different route handle",
            ));
        }
        self.shared.validate_current_handle(*handle)?;
        Ok(RoutePollResult {
            handle: *handle,
            status,
            live,
        })
    }

    /// Locally observed count of unknown or stale route frames dropped by layer-2 validation.
    pub fn dropped_route_frames(&self) -> u64 {
        self.shared.lock_inner().dropped_route_frames
    }

    /// Register a receiver for provider-originated Push frames on exactly one live route.
    ///
    /// Registering another receiver for the same route replaces and closes the prior receiver.
    /// The receiver closes when its route closes or the connection drops. A FULL buffer drops
    /// the overflowing push and counts it on `pushes_dropped_receiver_full` while the
    /// subscription survives (issue #40; push is a lossy latency optimization and polling
    /// remains the correctness backstop). The reader never waits for an application that is
    /// not draining pushes.
    pub fn push_events(
        &self,
        handle: &RouteHandle,
    ) -> Result<mpsc::Receiver<PushEvent>, CallError> {
        self.shared.register_push_events(*handle)
    }

    /// Number of Push frames dropped because their live route has no active receiver.
    ///
    /// Push is a one-way latency optimization, not a durable feed: the client does not
    /// acknowledge it, and callers retain polling as their correctness backstop. Counting
    /// intentional default-path drops makes an application that has not opted in observable.
    pub fn pushes_dropped_no_receiver(&self) -> u64 {
        self.shared
            .pushes_dropped_no_receiver
            .load(Ordering::Relaxed)
    }

    /// Pushes dropped because the registered receiver's bounded buffer was full.
    /// The subscription SURVIVES a burst (the receiver stays registered); this
    /// counter is the trace the burst leaves. Distinct from
    /// `pushes_dropped_no_receiver` because the remedies differ: full means
    /// drain faster or register with more capacity, no-receiver means nobody
    /// subscribed.
    pub fn pushes_dropped_receiver_full(&self) -> u64 {
        self.shared
            .pushes_dropped_receiver_full
            .load(Ordering::Relaxed)
    }

    /// Register the consumer-level receiver for daemon-originated channel-0
    /// control pushes (`route.closing`, `route.closed`, and any op added
    /// later). Advisory by contract: GOODBYE remains the load-bearing
    /// route-death signal and nothing in the client's own lifecycle consumes
    /// these. Unrecognized ops are DELIVERED (the must-ignore choice belongs
    /// to the consumer); unparseable bodies are dropped and counted. The
    /// receiver survives reconnects. Registering again replaces the prior
    /// receiver; a full or closed receiver drops the push and counts it
    /// rather than blocking the reader.
    pub fn control_pushes(&self, capacity: usize) -> mpsc::Receiver<ControlPush> {
        let (sender, receiver) = mpsc::channel(capacity.max(1));
        self.shared.lock_inner().control_push_receiver = Some(sender);
        receiver
    }

    /// Always-present count of dropped channel-0 control pushes (no receiver
    /// registered, receiver full or closed, or unparseable body). Emitted as a
    /// counter rather than silence so an application that has not opted in is
    /// observable, mirroring `pushes_dropped_no_receiver`.
    pub fn control_pushes_dropped(&self) -> u64 {
        self.shared.control_pushes_dropped.load(Ordering::Relaxed)
    }

    /// Managed unary call. Route-open failures happen before the body is sent and are
    /// classified as `NotSent`; module handler Error frames are the only `Module` errors.
    ///
    /// A daemon refusal that proves the module never received the request
    /// (`unknown_channel`, `stale_route_epoch`, or `module_reloading` while the
    /// module drains for a restart, reload or disable) evicts the cached route,
    /// reopens it and resends the request once, within the call deadline and
    /// only if the call has not been cancelled. Reopening during a drain waits
    /// out the daemon's `route.open` refusals until the replacement process
    /// registers, so the resend reaches the new process. A second such refusal
    /// is returned as `CallError::Module`.
    pub async fn call(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        body: Vec<u8>,
        opts: CallOptions,
    ) -> Result<Vec<u8>, CallError> {
        self.call_with_reply(target, identity, body, opts)
            .await
            .map(CallReply::into_body)
    }

    /// Like [`Self::call`], retaining the terminal Response's binary flag as well
    /// as its unchanged body bytes. A StreamEnd yields an empty, non-binary reply.
    pub async fn call_with_reply(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        body: Vec<u8>,
        opts: CallOptions,
    ) -> Result<CallReply, CallError> {
        self.call_inner(target, identity, (body, false), opts, None)
            .await
    }

    /// Managed unary call with explicit cancellation, like [`Self::request_cancellable`].
    ///
    /// Uses the same route opening, options, errors and deadline as [`Self::call`].
    /// Once cancellation is requested, a dead-route or `module_reloading` refusal is
    /// returned rather than retrying work the caller has asked to stop. Cancellation during route opening
    /// is remembered and sent after the Request is queued. Dropping either value
    /// sends no Cancel; dropping the future removes its pending registration.
    pub fn call_cancellable(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        body: Vec<u8>,
        opts: CallOptions,
    ) -> (
        CancelHandle,
        impl Future<Output = Result<Vec<u8>, CallError>> + Send + '_,
    ) {
        let (cancel, reply) = self.call_cancellable_with_reply(target, identity, body, opts);
        (cancel, async move { reply.await.map(CallReply::into_body) })
    }

    /// Like [`Self::call_cancellable`], retaining the terminal Response's binary
    /// flag and unchanged bytes in [`CallReply`]. Cancellation, retries, deadlines
    /// and drop behavior are identical. A StreamEnd yields an empty, non-binary reply.
    pub fn call_cancellable_with_reply(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        body: Vec<u8>,
        opts: CallOptions,
    ) -> (
        CancelHandle,
        impl Future<Output = Result<CallReply, CallError>> + Send + '_,
    ) {
        let consumer = self;
        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
        let future = async move {
            let guard = registration;
            consumer
                .call_inner(
                    target,
                    identity,
                    (body, false),
                    opts,
                    Some(Arc::clone(&guard.state)),
                )
                .await
        };
        (cancel, future)
    }

    /// Sends a framed JSON object head and opaque payload with `FLAG_BINARY`.
    /// Only use this for management operations that declare `operation_payload`.
    /// The caller enforces the operation's limit; the codec only bounds the head.
    pub async fn call_framed_with_reply(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        head: serde_json::Value,
        payload: Vec<u8>,
        opts: CallOptions,
    ) -> Result<CallReply, CallError> {
        let body = subc_protocol::framed_body::encode(&head, &payload)
            .map_err(|error| CallError::not_sent(format!("invalid framed request: {error}")))?;
        self.call_inner(target, identity, (body, true), opts, None)
            .await
    }

    /// Cancellable companion to [`Self::call_framed_with_reply`], with the same
    /// lazy send, cancellation, retry and deadline behavior as other managed calls.
    pub fn call_framed_cancellable_with_reply(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        head: serde_json::Value,
        payload: Vec<u8>,
        opts: CallOptions,
    ) -> (
        CancelHandle,
        impl Future<Output = Result<CallReply, CallError>> + Send + '_,
    ) {
        let (cancel, registration) = CancelRegistration::new(Arc::clone(&self.shared));
        (cancel, async move {
            let guard = registration;
            let body = subc_protocol::framed_body::encode(&head, &payload)
                .map_err(|error| CallError::not_sent(format!("invalid framed request: {error}")))?;
            self.call_inner(
                target,
                identity,
                (body, true),
                opts,
                Some(Arc::clone(&guard.state)),
            )
            .await
        })
    }

    async fn call_inner(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        body: (Vec<u8>, bool),
        opts: CallOptions,
        cancel: Option<Arc<UnaryCancel>>,
    ) -> Result<CallReply, CallError> {
        let (body, binary) = body;
        let call_deadline = Instant::now() + opts.timeout;
        // One resend per call after a refusal that proves the module never
        // received the request (route dead, or the module draining).
        let mut resent_after_unsent_refusal = false;
        let consumer_identity = route_open_consumer_identity(&opts);
        let consumer_capabilities = route_open_consumer_capabilities(&opts);
        let role_versions = route_open_role_versions(opts.role_versions.as_ref());
        let route_key = RouteKey::new(
            &target,
            &identity,
            consumer_identity.as_ref(),
            consumer_capabilities.as_deref(),
        )
        .with_role_versions(role_versions.as_ref());

        let route_open = RouteOpenParams {
            target: &target,
            identity: &identity,
            consumer_identity: &consumer_identity,
            consumer_capabilities: &consumer_capabilities,
            role_versions: &role_versions,
            reverse_requests: &opts.reverse_requests,
            scope: None,
        };

        loop {
            let route = self
                .shared
                .ensure_route(&route_key, &route_open, &opts, call_deadline)
                .await
                .map_err(request_not_sent_after_route_open_failure)?;
            let permit =
                match timeout_at(call_deadline, Arc::clone(&route.sem).acquire_owned()).await {
                    Ok(Ok(permit)) => permit,
                    Ok(Err(_)) => {
                        return Err(self.shared.route_not_sent_error(route.handle));
                    }
                    Err(_) => {
                        return Err(CallError::not_sent(
                            "call deadline elapsed waiting for route flow-control",
                        ));
                    }
                };

            if !self.shared.route_is_current(&route_key, &route) {
                drop(permit);
                self.shared
                    .sleep_until_retry(call_deadline, opts.route_retry.base)
                    .await?;
                continue;
            }

            let response = self
                .shared
                .send_request_cancellable(
                    RequestSend {
                        expected_handle: Some(route.handle),
                        channel: route.handle.channel,
                        epoch: route.handle.epoch,
                        body: body.clone(),
                        binary,
                        priority: opts.priority,
                        admission_class: opts.admission_class,
                        deadline: call_deadline,
                        retain_late_route_open: false,
                        route_open_reverse_requests: None,
                    },
                    cancel.clone(),
                )
                .await;
            drop(permit);

            match response {
                Ok(TerminalFrame::Response { body, flags, .. }) => {
                    return Ok(CallReply {
                        body,
                        binary: flags.is_binary(),
                    });
                }
                Ok(TerminalFrame::StreamEnd) => {
                    return Ok(CallReply {
                        body: Vec::new(),
                        binary: false,
                    });
                }
                // unknown_channel is the daemon ROUTER refusing an unrouted channel:
                // the request provably never reached a module, so one in-place retry
                // cannot double-execute. The cached bind is dead (module restarted;
                // its route-gone GOODBYE raced or was missed) — invalidate it so the
                // retry re-opens instead of resending into the same dead channel.
                // stale_route_epoch is the same class with a sharper cause (issue
                // #39): channel known, epoch released mid-flight. Its documented
                // contract is NOT-FORWARDED (dropped before delivery), so the retry
                // is safe by construction; the remedy is identical.
                // module_reloading joins the same single resend: see
                // `is_data_plane_drain_refusal`. All three codes share one
                // budget, so a call resends at most once whichever arrives.
                // Parity with the TS client's retry-once in call().
                Ok(TerminalFrame::Error { body, flags })
                    if (error_codes::is_established_route_dead(flags, &body.code)
                        || is_data_plane_drain_refusal(&body.code))
                        && !resent_after_unsent_refusal
                        && !cancel.as_ref().is_some_and(|cancel| cancel.requested())
                        && Instant::now() < call_deadline =>
                {
                    resent_after_unsent_refusal = true;
                    self.shared.invalidate_route(&route_key, Some(route.handle));
                    continue;
                }
                Ok(TerminalFrame::Error { body, .. }) => return Err(CallError::Module(body)),
                Err(err)
                    if err.is_not_sent()
                        && Instant::now() < call_deadline
                        && !cancel.as_ref().is_some_and(|cancel| cancel.requested()) =>
                {
                    self.shared.invalidate_route(&route_key, Some(route.handle));
                    self.shared.ensure_connected_for_call(call_deadline).await?;
                    continue;
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Open a held-open subscription on a managed route.
    ///
    /// This opens or reuses the same `(target, identity, consumer_identity, consumer_capabilities, role_versions)` route as
    /// [`SubcConsumer::call`], sends one Request that the provider keeps open, and
    /// returns a [`Subscription`] whose event receiver yields each matching
    /// `StreamData` payload. The request holds one route flow-control permit until
    /// `StreamEnd`, an Error frame, route teardown, connection loss, local
    /// backpressure, or [`Subscription::unsubscribe`]. Reconnects reject the
    /// subscription; callers that need durable replay should resubscribe with their
    /// own cursor after observing the failure.
    pub async fn subscribe(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        body: Vec<u8>,
        opts: SubscribeOptions,
    ) -> Result<Subscription, CallError> {
        let open_deadline = Instant::now() + opts.route_open_timeout;
        let route_opts = CallOptions {
            timeout: opts.route_open_timeout,
            priority: opts.priority,
            admission_class: opts.admission_class,
            route_retry: opts.route_retry,
            route_retry_deadline: opts.route_retry_deadline,
            consumer_identity: opts.consumer_identity.clone(),
            reverse_requests: opts.reverse_requests.clone(),
            role_versions: opts.role_versions.clone(),
        };
        let consumer_identity = route_open_consumer_identity(&route_opts);
        let consumer_capabilities = route_open_consumer_capabilities(&route_opts);
        let role_versions = route_open_role_versions(route_opts.role_versions.as_ref());
        let route_key = RouteKey::new(
            &target,
            &identity,
            consumer_identity.as_ref(),
            consumer_capabilities.as_deref(),
        )
        .with_role_versions(role_versions.as_ref());

        let route_open = RouteOpenParams {
            target: &target,
            identity: &identity,
            consumer_identity: &consumer_identity,
            consumer_capabilities: &consumer_capabilities,
            role_versions: &role_versions,
            reverse_requests: &opts.reverse_requests,
            scope: None,
        };

        loop {
            let route = self
                .shared
                .ensure_route(&route_key, &route_open, &route_opts, open_deadline)
                .await
                .map_err(request_not_sent_after_route_open_failure)?;
            let permit =
                match timeout_at(open_deadline, Arc::clone(&route.sem).acquire_owned()).await {
                    Ok(Ok(permit)) => permit,
                    Ok(Err(_)) => {
                        return Err(self.shared.route_not_sent_error(route.handle));
                    }
                    Err(_) => {
                        return Err(CallError::not_sent(
                            "subscription open deadline elapsed waiting for route flow-control",
                        ));
                    }
                };

            if !self.shared.route_is_current(&route_key, &route) {
                drop(permit);
                self.shared
                    .sleep_until_retry(open_deadline, opts.route_retry.base)
                    .await?;
                continue;
            }

            match self
                .shared
                .send_subscription(SubscriptionSend {
                    expected_handle: Some(route.handle),
                    channel: route.handle.channel,
                    epoch: route.handle.epoch,
                    body: body.clone(),
                    priority: opts.priority,
                    admission_class: opts.admission_class,
                    event_buffer: opts.event_buffer,
                    deadline: open_deadline,
                    permit,
                })
                .await
            {
                Ok(subscription) => return Ok(subscription),
                Err(err) if err.is_not_sent() && Instant::now() < open_deadline => {
                    self.shared.invalidate_route(&route_key, Some(route.handle));
                    self.shared.ensure_connected_for_call(open_deadline).await?;
                    continue;
                }
                Err(err) => return Err(err),
            }
        }
    }

    /// Tear down ONE route, keyed by its route-open identity tuple — the parity of the TS
    /// client's `closeRoute`. For a long-lived consumer that opens unbounded distinct
    /// routes (one per session), this releases a route on session-end without dropping
    /// the whole consumer: it drops the cached route, settles in-flight requests on it
    /// at-most-once (OutcomeUnknown if already sent, NotSent otherwise), and sends a
    /// best-effort route GOODBYE so the daemon releases it and notifies the module.
    ///
    /// Idempotent: a no-op if the route was never opened or is already closed (callers
    /// over-call on session-end). NOT a permanent tombstone — a later `call()` for the
    /// same key opens a fresh route. The close-beats-reopen guard ensures a close that
    /// races an in-flight route.open WINS (the opened channel is GOODBYE'd, not cached).
    pub async fn close_route(
        &self,
        target: RouteTarget,
        identity: BindIdentity,
        opts: CloseRouteOptions,
    ) {
        let consumer_identity = close_route_consumer_identity(&opts);
        let consumer_capabilities = close_route_consumer_capabilities(&opts);
        let key = RouteKey::new(
            &target,
            &identity,
            consumer_identity.as_ref(),
            consumer_capabilities.as_deref(),
        )
        .with_role_versions(route_open_role_versions(opts.role_versions.as_ref()).as_ref());
        self.shared.close_route(&key, &opts).await;
    }

    /// Close exactly this route handle. A stale connection token fails locally and emits no frame.
    pub async fn close_handle(
        &self,
        handle: &RouteHandle,
        opts: CloseRouteOptions,
    ) -> Result<(), CallError> {
        self.shared.close_handle(*handle, &opts).await
    }

    /// Current transport epoch: 1 on initial connect, then +1 per successful reconnect.
    pub fn current_epoch(&self) -> u64 {
        self.shared.lock_inner().epoch
    }

    /// Register a connection-state callback. Callbacks are best-effort observability hooks.
    pub fn on_connection_state(&self, cb: impl Fn(ConnectionState) + Send + 'static) {
        self.shared
            .lock_inner()
            .callbacks
            .push(Arc::new(Mutex::new(Box::new(cb))));
    }

    /// Close the consumer and settle every pending caller.
    pub async fn close(&self) {
        self.shared.close_sync("consumer closed");
        tokio::task::yield_now().await;
    }
}

impl Drop for SubcConsumer {
    fn drop(&mut self) {
        self.shared.close_sync("consumer dropped");
    }
}

/// Error returned by [`SubcConsumer::connect`] or [`SubcConsumer::connect_default`].
#[derive(Debug)]
pub enum ConsumerError {
    Discovery {
        source: connection_file::DiscoveryError,
    },
    ConnectionFile {
        path: PathBuf,
        source: ConnectionFileError,
    },
    NoEndpoint {
        path: PathBuf,
    },
    Connect {
        path: PathBuf,
        endpoint: String,
        source: io::Error,
    },
    Auth {
        path: PathBuf,
        endpoint: String,
        source: AuthError,
    },
    Closed,
}

impl fmt::Display for ConsumerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Discovery { source } => source.fmt(f),
            Self::ConnectionFile { path, source } => write!(
                f,
                "failed to read subc connection file '{}': {source}",
                path.display()
            ),
            Self::NoEndpoint { path } => {
                write!(
                    f,
                    "subc connection file '{}' has no endpoints",
                    path.display()
                )
            }
            Self::Connect {
                path,
                endpoint,
                source,
            } => write!(
                f,
                "failed to connect to subc endpoint {endpoint} from '{}': {source}",
                path.display()
            ),
            Self::Auth {
                path,
                endpoint,
                source,
            } => write!(
                f,
                "failed to authenticate to subc endpoint {endpoint} from '{}': {source}",
                path.display()
            ),
            Self::Closed => write!(f, "consumer closed"),
        }
    }
}

impl Error for ConsumerError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Discovery { source } => Some(source),
            Self::ConnectionFile { source, .. } => Some(source),
            Self::Connect { source, .. } => Some(source),
            Self::Auth { source, .. } => Some(source),
            Self::NoEndpoint { .. } | Self::Closed => None,
        }
    }
}

/// Why a sent request has no observed terminal response.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OutcomeUnknownCause {
    /// The reply deadline elapsed after the request was sent.
    Deadline,
    /// The connection's writer closed or failed after send.
    WriterClosed,
    /// The caller closed the consumer while a request was pending.
    ConsumerClosed,
    /// The daemon connection failed or dropped.
    ConnectionFailed,
    /// The route ended; [`CallError::close_reason`] gives its reason.
    RouteEnded,
    /// An internal completion channel dropped or an unexpected completion arrived.
    CompletionFailed,
}

#[derive(Debug, Clone)]
struct OutcomeUnknownSource {
    message: String,
    cause: OutcomeUnknownCause,
    route_reason: Option<RouteEndReason>,
}

impl fmt::Display for OutcomeUnknownSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.message)
    }
}
impl Error for OutcomeUnknownSource {}

/// Managed call or subscription failure.
#[derive(Debug)]
pub enum CallError {
    /// The request body was not accepted by the writer path, or route.open failed before data send.
    NotSent(Box<dyn Error + Send + Sync>),
    /// The request body was accepted by the writer path, but no terminal response was observed.
    OutcomeUnknown(Box<dyn Error + Send + Sync>),
    /// The target module handler returned an Error frame. Application-level rejections
    /// are returned as ordinary successful response bytes and do not produce this variant.
    Module(ErrorBody),
    /// A subscription event receiver stopped keeping up with its bounded channel.
    ///
    /// The reader task must never await a slow consumer while it is dispatching frames
    /// for the whole connection, so a full event channel terminates only that subscription.
    SubscriptionBackpressure(Box<dyn Error + Send + Sync>),
    /// The handle belongs to an earlier connection and no frame was emitted.
    StaleRouteHandle(RouteHandle),
    /// No registered catalog entry claims the requested capability.
    CapabilityUnprovided { capability: String },
    /// More than one registered catalog entry claims a singularly requested capability.
    CapabilityAmbiguous {
        capability: String,
        claimants: Vec<String>,
    },
    /// The resolver rejected a malformed capability identifier before querying the daemon.
    InvalidCapabilityIdentifier { capability: String },
}

impl CallError {
    /// A typed terminal scope bind-proof refusal, if the daemon returned one.
    pub fn scope_bind_proof_refusal(&self) -> Option<ScopeBindProofRefusal> {
        match self.route_open_refusal()?.code.as_str() {
            error_codes::SCOPE_BIND_PROOF_REQUIRED => Some(ScopeBindProofRefusal::Required),
            error_codes::SCOPE_BIND_PROOF_MISMATCH => Some(ScopeBindProofRefusal::Mismatch),
            _ => None,
        }
    }

    /// Why the route ended. The error remains `NotSent` or `OutcomeUnknown`:
    /// this reason never makes a sent call safe to resend.
    pub fn close_reason(&self) -> Option<&RouteEndReason> {
        match self {
            Self::NotSent(source) | Self::OutcomeUnknown(source) => source
                .downcast_ref::<RouteEnded>()
                .map(|ended| &ended.reason)
                .or_else(|| {
                    source
                        .downcast_ref::<OutcomeUnknownSource>()?
                        .route_reason
                        .as_ref()
                }),
            _ => None,
        }
    }

    /// Why the outcome is unknown, without parsing the error's message.
    /// Errors constructed outside this crate with an untyped source return `None`.
    pub fn outcome_cause(&self) -> Option<OutcomeUnknownCause> {
        match self {
            Self::OutcomeUnknown(source) => source
                .downcast_ref::<OutcomeUnknownSource>()
                .map(|source| source.cause),
            _ => None,
        }
    }

    /// Return the stable machine-readable code for typed errors.
    pub fn code(&self) -> Option<&str> {
        match self {
            Self::Module(body) => Some(&body.code),
            Self::CapabilityUnprovided { .. } => Some("capability_unprovided"),
            Self::CapabilityAmbiguous { .. } => Some("capability_ambiguous"),
            Self::InvalidCapabilityIdentifier { .. } => Some("invalid_capability_identifier"),
            Self::NotSent(_)
            | Self::OutcomeUnknown(_)
            | Self::SubscriptionBackpressure(_)
            | Self::StaleRouteHandle(_) => None,
        }
    }

    fn not_sent(reason: impl Into<String>) -> Self {
        Self::NotSent(Box::new(SimpleError(reason.into())))
    }

    fn outcome_unknown(reason: impl Into<String>, cause: OutcomeUnknownCause) -> Self {
        Self::outcome_unknown_source(OutcomeUnknownSource {
            message: reason.into(),
            cause,
            route_reason: None,
        })
    }

    fn outcome_unknown_source(source: OutcomeUnknownSource) -> Self {
        Self::OutcomeUnknown(Box::new(source))
    }

    fn is_not_sent(&self) -> bool {
        matches!(self, Self::NotSent(_))
    }

    /// The daemon's refusal body when this failure is a route.open the daemon
    /// refused, with its `code`, `message` and machine-readable `detail`
    /// intact, for example `module_warming` with
    /// `detail.reason = "required_capability_unprovided"`.
    ///
    /// When retryable refusals ran out the route-retry deadline, this is the
    /// most informative refusal seen during the retries, so a caller can tell
    /// "the module was reloading" from "the connection failed". Refusals rank:
    /// `module_reloading` / `module_warming`, then `delegation_not_registered`,
    /// then admission pressure (too many binds in flight), then anything else;
    /// at equal rank the later one wins. The failure is still `NotSent`: a
    /// refused route.open never delivered the request.
    pub fn route_open_refusal(&self) -> Option<&ErrorBody> {
        match self {
            Self::NotSent(err) => err
                .downcast_ref::<RouteOpenRefused>()
                .map(|refused| &refused.body),
            _ => None,
        }
    }

    fn subscription_backpressure(reason: impl Into<String>) -> Self {
        Self::SubscriptionBackpressure(Box::new(SimpleError(reason.into())))
    }
}

impl fmt::Display for CallError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotSent(err) => write!(f, "request not sent: {err}"),
            Self::OutcomeUnknown(err) => write!(f, "request outcome unknown: {err}"),
            Self::Module(body) => write!(f, "module error {}: {}", body.code, body.message),
            Self::SubscriptionBackpressure(err) => {
                write!(f, "subscription event channel backpressure: {err}")
            }
            Self::StaleRouteHandle(handle) => write!(f, "stale route handle: {handle:?}"),
            Self::CapabilityUnprovided { capability } => {
                write!(
                    f,
                    "capability_unprovided: no catalog claimant for {capability}"
                )
            }
            Self::CapabilityAmbiguous {
                capability,
                claimants,
            } => write!(
                f,
                "capability_ambiguous: multiple catalog claimants for {capability}: {claimants:?}"
            ),
            Self::InvalidCapabilityIdentifier { capability } => write!(
                f,
                "invalid_capability_identifier: malformed capability identifier {capability:?}"
            ),
        }
    }
}

impl Error for CallError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::NotSent(err)
            | Self::OutcomeUnknown(err)
            | Self::SubscriptionBackpressure(err) => Some(err.as_ref()),
            Self::Module(_)
            | Self::StaleRouteHandle(_)
            | Self::CapabilityUnprovided { .. }
            | Self::CapabilityAmbiguous { .. }
            | Self::InvalidCapabilityIdentifier { .. } => None,
        }
    }
}

/// A route.open the daemon refused, kept typed inside [`CallError::NotSent`]
/// so the refusal's code and `detail` survive. Read it through
/// [`CallError::route_open_refusal`].
#[derive(Debug, Clone)]
struct RouteOpenRefused {
    target: String,
    body: ErrorBody,
    /// The last refusal of a retry loop, when it is not `body`: kept so the
    /// message still says what the daemon answered most recently.
    most_recent: Option<ErrorBody>,
}

/// Terminal refusals requiring the caller to supply the scope's current proof.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScopeBindProofRefusal {
    Required,
    Mismatch,
}

impl fmt::Display for RouteOpenRefused {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "route.open failed for target {}: {}",
            self.target,
            DescribeRefusal(&self.body)
        )?;
        if let Some(most_recent) = &self.most_recent {
            write!(
                f,
                "; the most recent refusal was {}",
                DescribeRefusal(most_recent)
            )?;
        }
        Ok(())
    }
}

impl Error for RouteOpenRefused {}

/// A refusal as `code (reason r) (message)`, the reason read from
/// `detail.reason` and omitted when the daemon sent none.
struct DescribeRefusal<'a>(&'a ErrorBody);

impl fmt::Display for DescribeRefusal<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.code)?;
        if let Some(reason) = refusal_reason(self.0) {
            write!(f, " (reason {reason})")?;
        }
        write!(f, " ({})", self.0.message)
    }
}

fn refusal_reason(body: &ErrorBody) -> Option<&str> {
    body.detail.as_ref()?.get("reason")?.as_str()
}

/// The daemon's reasons for refusing a route.open because too many binds are
/// already in flight, on the consumer's connection or towards the target module
/// (`crates/subc-daemon/src/control.rs`, `route_open_capacity_refusal` and
/// `route_open_target_capacity_refusal`). Both are sent as `target_unavailable`.
const ADMISSION_PRESSURE_REASONS: [&str; 2] = ["open_admission_full", "target_binds_full"];
/// Markers in the messages of those same admission-pressure refusals. The
/// daemon currently logs the reason but leaves it out of the refusal's detail,
/// so the message is the only way to recognise them.
const ADMISSION_PRESSURE_MESSAGES: [&str; 2] =
    ["route.open binds in flight", "route.bind relays in flight"];

/// How much a route.open refusal says about why the target was unreachable,
/// highest first: the module was changing state (reloading or warming); a
/// delegation was not registered; admission pressure; anything else.
fn route_open_refusal_rank(body: &ErrorBody) -> u8 {
    if body.code == error_codes::MODULE_RELOADING || body.code == error_codes::MODULE_WARMING {
        return 3;
    }
    let reason = refusal_reason(body);
    if body.code == "delegation_not_registered" || reason == Some("delegation_not_registered") {
        return 2;
    }
    if body.code == error_codes::TARGET_UNAVAILABLE {
        let admission_pressure = match reason {
            Some(reason) => ADMISSION_PRESSURE_REASONS.contains(&reason),
            None => ADMISSION_PRESSURE_MESSAGES
                .iter()
                .any(|marker| body.message.contains(marker)),
        };
        if admission_pressure {
            return 1;
        }
    }
    0
}

/// The route.open refusals one retry loop has seen. When the deadline runs out,
/// the error is built from the best-ranked one: after a module restart the most
/// recent refusal is often admission pressure ("8 binds in flight"), which
/// points a reader at the consumer's concurrency when the module was simply down.
#[derive(Default)]
struct RouteOpenRefusals {
    best: Option<ErrorBody>,
    /// Set only while the latest refusal ranked below `best`.
    most_recent: Option<ErrorBody>,
}

impl RouteOpenRefusals {
    fn record(&mut self, body: ErrorBody) {
        // At equal rank the newer refusal wins: it describes the target's latest state.
        let outranks = self
            .best
            .as_ref()
            .is_none_or(|best| route_open_refusal_rank(&body) >= route_open_refusal_rank(best));
        if outranks {
            self.best = Some(body);
            self.most_recent = None;
        } else {
            self.most_recent = Some(body);
        }
    }

    fn into_error(self, target: String) -> Option<CallError> {
        let body = self.best?;
        Some(CallError::NotSent(Box::new(RouteOpenRefused {
            target,
            body,
            most_recent: self.most_recent,
        })))
    }
}

/// The label a route.open refusal names its target by, the same spelling the
/// managed route cache uses.
fn route_target_label(target: &RouteTarget) -> String {
    match target {
        RouteTarget::ToolProvider { module_id } => format!("tool_provider:{module_id}"),
        RouteTarget::ManagementSurface { module_id } => format!("management_surface:{module_id}"),
        RouteTarget::InternalService {
            module_id,
            service_id,
        } => format!("internal_service:{module_id}:{service_id}"),
    }
}

impl CallError {
    fn route_open_refused(target: String, body: ErrorBody) -> Self {
        Self::NotSent(Box::new(RouteOpenRefused {
            target,
            body,
            most_recent: None,
        }))
    }
}

#[derive(Debug)]
struct SimpleError(String);

impl fmt::Display for SimpleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl Error for SimpleError {}

type Callback = Arc<Mutex<Box<dyn Fn(ConnectionState) + Send + 'static>>>;

type OpeningWaiter = oneshot::Sender<Result<RouteState, SharedCallFailure>>;

/// An in-flight route.open for one key: the waiters parked behind the lead opener,
/// plus a `closed` flag a concurrent `close_route` flips so the lead opener refuses
/// to install its channel (the close-beats-reopen guard). The flag lives here, with
/// the in-flight open, so it vanishes when the open finishes — no lingering per-key
/// state to leak for a long-lived consumer with unbounded distinct routes.
struct Opening {
    waiters: Vec<OpeningWaiter>,
    closed: bool,
}

struct Shared {
    connection_file: PathBuf,
    opts: ConsumerOptions,
    inner: Mutex<Inner>,
    notify: Notify,
    #[cfg(test)]
    before_wait: Mutex<Option<Box<dyn FnOnce() + Send>>>,
    close_token: CancellationToken,
    /// Epoch milliseconds of the last frame dispatched from the current connection.
    /// The liveness probe reads this to distinguish a healthy slow request from a
    /// socket that has silently stopped delivering inbound traffic.
    last_inbound_ms: AtomicU64,
    /// Only one deadline-triggered liveness probe may be active across generations.
    liveness_probe_running: AtomicBool,
    pushes_dropped_no_receiver: AtomicU64,
    /// Always-present drop counter for channel-0 control pushes (no receiver,
    /// receiver full/closed, or unparseable body). Before this surface existed
    /// the drop was SILENT -- not even a counter -- which is how #31's push
    /// family shipped unreachable to every Rust consumer (issue #35).
    control_pushes_dropped: AtomicU64,
    /// Pushes dropped because a registered receiver's bounded buffer was full
    /// at delivery time. Distinct from `pushes_dropped_no_receiver` because the
    /// operator remedies differ: full means the consumer is too slow (widen the
    /// buffer or drain faster), no-receiver means it never subscribed.
    pushes_dropped_receiver_full: AtomicU64,
    /// Random source in [0, 1) for retry jitter. Tests replace it with a seeded
    /// one so jittered delays are reproducible.
    random_unit: Box<dyn Fn() -> f64 + Send + Sync>,
    /// One permit per route.open the consumer may have outstanding; see
    /// [`MAX_ROUTE_OPENS_IN_FLIGHT`]. tokio's semaphore grants permits in
    /// request order, which makes the wait first come first served. The consumer
    /// holds one connection at a time and a dropped connection fails every open
    /// in flight on it, so one semaphore is a per-connection limit.
    route_open_slots: Semaphore,
}

struct Inner {
    generation: u64,
    epoch: u64,
    next_corr: Option<u64>,
    writer: Option<mpsc::Sender<WriteCommand>>,
    pending: HashMap<PendingKey, PendingEntry>,
    routes: HashMap<RouteKey, RouteState>,
    route_by_channel: HashMap<u16, RouteKey>,
    one_shot_routes: HashMap<u16, RouteState>,
    route_epochs: HashMap<u16, RouteHandle>,
    retired_routes: HashSet<RouteHandle>,
    route_modules: HashMap<u16, String>,
    route_end_reasons: HashMap<u16, (RouteEndReason, bool)>,
    legacy_channel_reasons: HashMap<u16, RouteCloseReason>,
    push_event_receivers: HashMap<RouteHandle, mpsc::Sender<PushEvent>>,
    /// Consumer-level receiver for daemon-originated channel-0 control pushes
    /// (`route.closing`, `route.closed`, future ops). Connection-independent:
    /// control pushes are advisory daemon events, so the receiver survives
    /// reconnects rather than being keyed by generation.
    control_push_receiver: Option<mpsc::Sender<ControlPush>>,
    dropped_route_frames: u64,
    openings: HashMap<RouteKey, Opening>,
    callbacks: Vec<Callback>,
    closed: bool,
    reconnect: ReconnectState,
    restored_token: u64,
    reader_task: Option<JoinHandle<()>>,
    writer_task: Option<JoinHandle<()>>,
}

impl Inner {
    fn record_route_end(&mut self, push: &ControlPush) {
        let Some(reason) = push.route_close_reason() else {
            return;
        };
        if let Some(channels) = push.body.get("channels") {
            if let Some(channels) = channels.as_array() {
                for channel in channels
                    .iter()
                    .filter_map(|v| v.as_u64().and_then(|v| u16::try_from(v).ok()))
                {
                    let final_reason = push.op == "route.closed";
                    if final_reason
                        || !self
                            .route_end_reasons
                            .get(&channel)
                            .is_some_and(|(_, final_reason)| *final_reason)
                    {
                        self.route_end_reasons.insert(
                            channel,
                            (RouteEndReason::Daemon(reason.clone()), final_reason),
                        );
                    }
                }
            }
        } else if let Some(module) = push.body.get("module_id").and_then(|v| v.as_str()) {
            for (&channel, target) in &self.route_modules {
                if target == module {
                    self.legacy_channel_reasons.insert(channel, reason.clone());
                }
            }
        }
    }

    fn route_end_reason(&self, channel: u16) -> RouteEndReason {
        self.route_end_reasons
            .get(&channel)
            .map(|(reason, _)| reason.clone())
            .or_else(|| {
                self.legacy_channel_reasons
                    .get(&channel)
                    .cloned()
                    .map(RouteEndReason::Daemon)
            })
            .unwrap_or(RouteEndReason::Unknown)
    }

    fn cache_route(&mut self, key: RouteKey, route: RouteState) -> RouteState {
        let cached = self.routes.entry(key.clone()).or_insert(route).clone();
        let previous = self
            .route_by_channel
            .insert(cached.handle.channel, key.clone());
        debug_assert!(previous.as_ref().is_none_or(|previous| previous == &key));
        self.route_epochs
            .insert(cached.handle.channel, cached.handle);
        cached
    }

    fn remove_route(&mut self, key: &RouteKey) -> Option<RouteState> {
        let route = self.evict_route(key)?;
        release_reverse_request_registry(route.handle);
        Some(route)
    }

    fn evict_route(&mut self, key: &RouteKey) -> Option<RouteState> {
        let route = self.routes.remove(key)?;
        let indexed = self.route_by_channel.remove(&route.handle.channel);
        debug_assert_eq!(indexed.as_ref(), Some(key));
        Some(route)
    }

    fn reap_retired_route(&mut self, handle: RouteHandle) {
        // The pending map is authoritative, including subscriptions and calls
        // dropped by their owner. Scan only on retired routes instead of
        // maintaining a second count on every registration/removal path.
        if !self.retired_routes.contains(&handle)
            || self.pending.keys().any(|key| {
                key.generation == handle.connection_token()
                    && key.channel == handle.channel
                    && key.epoch == handle.epoch
            })
        {
            return;
        }
        let handle = self
            .retired_routes
            .take(&handle)
            .expect("retired route exists");
        if self.route_epochs.get(&handle.channel) == Some(&handle) {
            self.route_epochs.remove(&handle.channel);
            self.push_event_receivers.remove(&handle);
        }
        release_reverse_request_registry(handle);
    }

    fn remove_pending(&mut self, key: &PendingKey) -> Option<PendingEntry> {
        let entry = self.pending.remove(key);
        self.reap_retired_route(RouteHandle::new(key.channel, key.epoch, key.generation));
        entry
    }

    fn remove_route_by_handle(&mut self, handle: RouteHandle) -> Option<RouteState> {
        if let Some(key) = self.route_by_channel.get(&handle.channel).cloned() {
            let matches = self
                .routes
                .get(&key)
                .is_some_and(|route| route.handle == handle);
            debug_assert!(matches);
            if matches {
                return self.remove_route(&key);
            }
        }
        let route = self
            .one_shot_routes
            .get(&handle.channel)
            .is_some_and(|route| route.handle == handle)
            .then(|| self.one_shot_routes.remove(&handle.channel))
            .flatten();
        if let Some(route) = &route {
            release_reverse_request_registry(route.handle);
        }
        route
    }

    fn drain_routes(&mut self) -> Vec<RouteState> {
        for handle in self.retired_routes.drain() {
            release_reverse_request_registry(handle);
        }
        self.route_by_channel.clear();
        let routes = self
            .routes
            .drain()
            .map(|(_, route)| route)
            .chain(self.one_shot_routes.drain().map(|(_, route)| route))
            .collect::<Vec<_>>();
        for route in &routes {
            release_reverse_request_registry(route.handle);
        }
        routes
    }

    fn close_routes(&mut self) {
        self.push_event_receivers.clear();
        for route in self.drain_routes() {
            route.sem.close();
        }
    }
}

impl Shared {
    fn new(connection_file: PathBuf, opts: ConsumerOptions) -> Self {
        Self {
            connection_file,
            opts,
            inner: Mutex::new(Inner {
                generation: 1,
                epoch: 1,
                next_corr: Some(1),
                writer: None,
                pending: HashMap::new(),
                routes: HashMap::new(),
                route_by_channel: HashMap::new(),
                one_shot_routes: HashMap::new(),
                route_epochs: HashMap::new(),
                retired_routes: HashSet::new(),
                route_modules: HashMap::new(),
                route_end_reasons: HashMap::new(),
                legacy_channel_reasons: HashMap::new(),
                push_event_receivers: HashMap::new(),
                control_push_receiver: None,
                dropped_route_frames: 0,
                openings: HashMap::new(),
                callbacks: Vec::new(),
                closed: false,
                reconnect: ReconnectState::Idle,
                restored_token: 0,
                reader_task: None,
                writer_task: None,
            }),
            notify: Notify::new(),
            #[cfg(test)]
            before_wait: Mutex::new(None),
            close_token: CancellationToken::new(),
            last_inbound_ms: AtomicU64::new(0),
            liveness_probe_running: AtomicBool::new(false),
            pushes_dropped_no_receiver: AtomicU64::new(0),
            control_pushes_dropped: AtomicU64::new(0),
            pushes_dropped_receiver_full: AtomicU64::new(0),
            random_unit: Box::new(default_random_unit),
            route_open_slots: Semaphore::new(MAX_ROUTE_OPENS_IN_FLIGHT),
        }
    }

    /// "Equal jitter": keep half of `delay` and randomize the other half. Every
    /// route on a connection is closed together when its module drains, so
    /// without jitter they all retry in lock step and reach the daemon as one
    /// burst each round; reconnects after a daemon restart herd the same way.
    fn jittered(&self, delay: Duration) -> Duration {
        let unit = (self.random_unit)();
        let unit = if unit.is_finite() {
            unit.clamp(0.0, 1.0)
        } else {
            0.0
        };
        let half = delay / 2;
        half + half.mul_f64(unit)
    }

    /// One route.open exchange, paced by [`MAX_ROUTE_OPENS_IN_FLIGHT`]. The
    /// wait for a free slot ends at `deadline` like the exchange itself.
    async fn paced_route_open(
        self: &Arc<Self>,
        body: Vec<u8>,
        deadline: Instant,
        reverse_requests: Option<ReverseRequestRegistry>,
    ) -> Result<TerminalFrame, CallError> {
        let _slot = match timeout_at(deadline, self.route_open_slots.acquire()).await {
            Ok(Ok(permit)) => permit,
            Ok(Err(_)) => return Err(CallError::not_sent("consumer closed")),
            Err(_) => {
                return Err(CallError::not_sent(format!(
                    "deadline elapsed waiting for one of {MAX_ROUTE_OPENS_IN_FLIGHT} route.open slots"
                )));
            }
        };
        self.control_call(body, deadline, true, reverse_requests)
            .await
    }

    fn lock_inner(&self) -> MutexGuard<'_, Inner> {
        self.inner
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    fn install_initial(self: &Arc<Self>, opened: OpenedConnection) -> Result<(), ConsumerError> {
        self.install_connection(opened, InstallKind::Initial)
            .map(|_| ())
    }

    fn install_reconnected(
        self: &Arc<Self>,
        opened: OpenedConnection,
    ) -> Result<(u64, u64), ConsumerError> {
        let generation_epoch = self.install_connection(opened, InstallKind::Reconnect)?;
        self.notify.notify_waiters();
        Ok(generation_epoch)
    }

    fn install_connection(
        self: &Arc<Self>,
        opened: OpenedConnection,
        kind: InstallKind,
    ) -> Result<(u64, u64), ConsumerError> {
        if self.close_token.is_cancelled() {
            return Err(ConsumerError::Closed);
        }

        let (reader, writer) = opened.stream.into_split();
        let (tx, rx) = mpsc::channel(EGRESS_BUFFER);
        let (generation, epoch, old_reader, old_writer) = {
            let mut inner = self.lock_inner();
            if inner.closed {
                return Err(ConsumerError::Closed);
            }
            let (generation, epoch) = match kind {
                InstallKind::Initial => (inner.generation, inner.epoch),
                InstallKind::Reconnect => {
                    inner.generation = inner
                        .generation
                        .checked_add(1)
                        .ok_or(ConsumerError::Closed)?;
                    inner.epoch = inner.epoch.checked_add(1).ok_or(ConsumerError::Closed)?;
                    (inner.generation, inner.epoch)
                }
            };
            inner.close_routes();
            inner.route_epochs.clear();
            inner.route_modules.clear();
            inner.route_end_reasons.clear();
            inner.legacy_channel_reasons.clear();
            inner.next_corr = Some(1);
            inner.writer = Some(tx);
            self.last_inbound_ms.store(0, Ordering::Release);
            (
                generation,
                epoch,
                inner.reader_task.take(),
                inner.writer_task.take(),
            )
        };

        if let Some(handle) = old_reader {
            handle.abort();
        }
        if let Some(handle) = old_writer {
            handle.abort();
        }

        let reader_shared = Arc::clone(self);
        let reader_task = tokio::spawn(async move {
            reader_loop(reader_shared, reader, generation).await;
        });
        let writer_shared = Arc::clone(self);
        let writer_task = tokio::spawn(async move {
            writer_loop(writer_shared, writer, rx, generation).await;
        });

        {
            let mut inner = self.lock_inner();
            if inner.closed || inner.generation != generation {
                reader_task.abort();
                writer_task.abort();
                return Err(ConsumerError::Closed);
            }
            inner.reader_task = Some(reader_task);
            inner.writer_task = Some(writer_task);
        }

        Ok((generation, epoch))
    }

    async fn ensure_connected_for_call(
        self: &Arc<Self>,
        deadline: Instant,
    ) -> Result<(), CallError> {
        loop {
            if Instant::now() >= deadline {
                return Err(CallError::not_sent(
                    "call deadline elapsed waiting for reconnection",
                ));
            }
            // Created BEFORE the state is read, and that ordering is the fix.
            // Reconnect completion wakes waiters with `notify_waiters()`, which
            // reaches only `Notified` futures that already exist and stores no
            // permit. A future created after the lock is released misses a
            // reconnect that finishes in between, and the caller then sleeps
            // until its deadline on a healthy connection. (`enable()` is kept
            // for `notify_one` semantics; for `notify_waiters` creation alone
            // is what registers the waiter.)
            let notified = self.notify.notified();
            tokio::pin!(notified);
            let action = {
                let mut inner = self.lock_inner();
                notified.as_mut().enable();
                if inner.closed {
                    return Err(CallError::not_sent("consumer closed"));
                }
                if inner.writer.is_some() {
                    return Ok(());
                }
                let generation = inner.generation;
                let reconnect_is_live = match &inner.reconnect {
                    ReconnectState::Idle => false,
                    ReconnectState::Inline { generation: active } => *active == generation,
                    ReconnectState::Background {
                        generation: active,
                        task,
                    } => *active == generation && !task.is_finished(),
                };
                if reconnect_is_live {
                    EnsureAction::Wait
                } else {
                    let stale_task =
                        match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
                            ReconnectState::Background { task, .. } => Some(task),
                            ReconnectState::Idle | ReconnectState::Inline { .. } => None,
                        };
                    inner.reconnect = ReconnectState::Inline { generation };
                    EnsureAction::Lead {
                        generation,
                        stale_task,
                    }
                }
            };

            match action {
                EnsureAction::Wait => {
                    #[cfg(test)]
                    {
                        let hook = self.before_wait.lock().unwrap().take();
                        if let Some(hook) = hook {
                            hook();
                        }
                    }
                    timeout_at(deadline, notified).await.map_err(|_| {
                        CallError::not_sent("call deadline elapsed waiting for reconnection")
                    })?;
                }
                EnsureAction::Lead {
                    generation,
                    stale_task,
                } => {
                    if let Some(handle) = stale_task {
                        handle.abort();
                    }
                    let mut guard = InlineReconnectGuard::new(Arc::clone(self), generation);
                    let result = timeout_at(deadline, self.reconnect_with_retry(generation)).await;
                    guard.finish();
                    return match result {
                        Ok(Ok(())) => Ok(()),
                        Ok(Err(err)) => Err(CallError::not_sent(err.to_string())),
                        Err(_) => Err(CallError::not_sent(
                            "call deadline elapsed waiting for reconnection",
                        )),
                    };
                }
            }
        }
    }

    fn spawn_reconnect(self: &Arc<Self>, generation: u64) -> bool {
        // Reconnect ownership is fenced by the dropped transport generation. A
        // newer drop replaces an older attempt instead of letting that attempt
        // block recovery for the newer transport.
        let stale_task = {
            let mut inner = self.lock_inner();
            if inner.closed || inner.writer.is_some() || inner.generation != generation {
                return false;
            }
            let should_spawn = match &inner.reconnect {
                ReconnectState::Idle => true,
                ReconnectState::Inline { generation: active } => *active < generation,
                ReconnectState::Background {
                    generation: active,
                    task,
                } => *active < generation || (*active == generation && task.is_finished()),
            };
            if !should_spawn {
                return false;
            }

            let stale_task = match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
                ReconnectState::Background { task, .. } => Some(task),
                ReconnectState::Idle | ReconnectState::Inline { .. } => None,
            };
            let shared = Arc::clone(self);
            let handle = tokio::spawn(async move {
                let _result = shared.reconnect_with_retry(generation).await;
                shared.finish_background_reconnect(generation);
            });
            inner.reconnect = ReconnectState::Background {
                generation,
                task: handle,
            };
            stale_task
        };
        if let Some(handle) = stale_task {
            handle.abort();
        }
        true
    }

    async fn reconnect_with_retry(
        self: &Arc<Self>,
        reconnect_generation: u64,
    ) -> Result<(), ConsumerError> {
        let mut last_error: Option<ConsumerError> = None;
        for attempt in 1..=self.opts.reconnect_backoff.max_attempts {
            if self.close_token.is_cancelled() {
                return Err(ConsumerError::Closed);
            }
            if !self.reconnect_attempt_is_current(reconnect_generation) {
                return Ok(());
            }

            match open_connection(&self.connection_file, self.opts.handshake_timeout).await {
                Ok(opened) => {
                    // A newer drop may have installed its own attempt while this
                    // connection was opening. Do not let the stale attempt replace it.
                    if !self.reconnect_attempt_is_current(reconnect_generation) {
                        return Ok(());
                    }
                    let (generation, epoch) = self.install_reconnected(opened)?;
                    self.schedule_restored(generation, epoch);
                    return Ok(());
                }
                Err(err) => {
                    let transient = is_reconnect_transient(&err);
                    last_error = Some(err);
                    if !transient || attempt >= self.opts.reconnect_backoff.max_attempts {
                        break;
                    }
                    // Jittered like the route.open retries, which share this backoff.
                    let delay =
                        self.jittered(self.opts.reconnect_backoff.delay_after_attempt(attempt));
                    tokio::select! {
                        () = self.close_token.cancelled() => return Err(ConsumerError::Closed),
                        () = sleep(delay) => {}
                    }
                }
            }
        }
        Err(last_error.unwrap_or(ConsumerError::Closed))
    }

    fn reconnect_attempt_is_current(&self, generation: u64) -> bool {
        let inner = self.lock_inner();
        !inner.closed
            && inner.writer.is_none()
            && inner.generation == generation
            && matches!(
                &inner.reconnect,
                ReconnectState::Inline { generation: active }
                    | ReconnectState::Background {
                        generation: active,
                        ..
                    } if *active == generation
            )
    }

    fn finish_inline_reconnect(&self, generation: u64) {
        let finished = {
            let mut inner = self.lock_inner();
            if matches!(
                &inner.reconnect,
                ReconnectState::Inline { generation: active } if *active == generation
            ) {
                inner.reconnect = ReconnectState::Idle;
                true
            } else {
                false
            }
        };
        if finished {
            self.notify.notify_waiters();
        }
    }

    fn finish_background_reconnect(&self, generation: u64) {
        let completed_task = {
            let mut inner = self.lock_inner();
            if !matches!(
                &inner.reconnect,
                ReconnectState::Background { generation: active, .. } if *active == generation
            ) {
                None
            } else {
                match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
                    ReconnectState::Background { task, .. } => Some(task),
                    ReconnectState::Idle | ReconnectState::Inline { .. } => unreachable!(),
                }
            }
        };
        if completed_task.is_some() {
            drop(completed_task);
            self.notify.notify_waiters();
        }
    }

    fn schedule_restored(self: &Arc<Self>, generation: u64, epoch: u64) {
        let token = {
            let mut inner = self.lock_inner();
            inner.restored_token = inner.restored_token.saturating_add(1);
            inner.restored_token
        };
        let shared = Arc::clone(self);
        tokio::spawn(async move {
            tokio::select! {
                () = shared.close_token.cancelled() => {}
                () = sleep(shared.opts.restored_debounce) => {
                    let should_emit = {
                        let inner = shared.lock_inner();
                        !inner.closed
                            && inner.generation == generation
                            && inner.epoch == epoch
                            && inner.restored_token == token
                            && inner.writer.is_some()
                    };
                    if should_emit {
                        shared.emit_connection_state(ConnectionState::Restored { epoch });
                    }
                }
            }
        });
    }

    fn install_one_shot_route(&self, route: RouteState) -> Result<(), CallError> {
        let handle = route.handle;
        let mut inner = self.lock_inner();
        if inner.closed || inner.generation != handle.connection_token() || inner.writer.is_none() {
            return Err(CallError::StaleRouteHandle(handle));
        }
        // The socket reader installs the handle for a route.open response before
        // the waiter resolves (so a request the provider sends right after the
        // bind is routed), so this route's own channel is normally present
        // already, holding exactly this handle. Only a different handle on the
        // channel is a collision.
        if inner
            .route_epochs
            .get(&handle.channel)
            .is_some_and(|existing| *existing != handle)
        {
            return Err(CallError::not_sent(
                "daemon returned a route channel already in use",
            ));
        }
        inner.one_shot_routes.insert(handle.channel, route);
        inner.route_epochs.insert(handle.channel, handle);
        Ok(())
    }

    async fn ensure_route(
        self: &Arc<Self>,
        key: &RouteKey,
        route_open: &RouteOpenParams<'_>,
        opts: &CallOptions,
        call_deadline: Instant,
    ) -> Result<RouteState, CallError> {
        loop {
            let action = {
                let mut inner = self.lock_inner();
                if inner.closed {
                    return Err(CallError::not_sent("consumer closed"));
                }
                if let Some(route) = inner.routes.get(key) {
                    if route.handle.connection_token() == inner.generation && inner.writer.is_some()
                    {
                        return Ok(route.clone());
                    }
                }
                if let Some(opening) = inner.openings.get_mut(key) {
                    let (tx, rx) = oneshot::channel();
                    opening.waiters.push(tx);
                    RouteOpenAction::Wait(rx)
                } else {
                    inner.openings.insert(
                        key.clone(),
                        Opening {
                            waiters: Vec::new(),
                            closed: false,
                        },
                    );
                    RouteOpenAction::Lead
                }
            };

            match action {
                RouteOpenAction::Wait(rx) => match timeout_at(call_deadline, rx).await {
                    Ok(Ok(Ok(route))) => return Ok(route),
                    Ok(Ok(Err(err))) => return Err(err.into_call_error()),
                    Ok(Err(_)) => continue,
                    Err(_) => {
                        return Err(CallError::not_sent(
                            "call deadline elapsed waiting for route.open",
                        ));
                    }
                },
                RouteOpenAction::Lead => {
                    let mut guard = OpeningGuard::new(Arc::clone(self), key.clone());
                    let result = self
                        .open_route_with_retry(key, route_open, opts, call_deadline)
                        .await
                        .map_err(SharedCallFailure::from);
                    guard.finish(result.clone());
                    return result.map_err(SharedCallFailure::into_call_error);
                }
            }
        }
    }

    async fn open_route_with_retry(
        self: &Arc<Self>,
        key: &RouteKey,
        route_open: &RouteOpenParams<'_>,
        opts: &CallOptions,
        call_deadline: Instant,
    ) -> Result<RouteState, CallError> {
        let route_deadline = (Instant::now() + opts.route_retry_deadline).min(call_deadline);
        let mut attempt = 0usize;
        // The retryable refusals seen so far. When the deadline ends the retries,
        // the caller gets the most informative of them rather than a bare
        // "deadline elapsed", so "the module was reloading" stays
        // distinguishable from "the connection failed".
        let mut refusals = RouteOpenRefusals::default();
        // An attempt that ends because the deadline passed hands back the kept
        // refusal. That covers an attempt that never left the client (NotSent)
        // and one the daemon received but had not answered by the deadline
        // (OutcomeUnknown with the Deadline cause): a busy daemon can answer
        // the final retry a few milliseconds late, and the refusals before it
        // still say why the route never opened. Dropping the unanswered
        // attempt's own outcome is safe: route.open requests are sent with
        // `retain_late_route_open`, so a late acceptance is closed again with
        // a GOODBYE instead of being handed to anyone.
        let expired = |err: CallError, refusals: &mut RouteOpenRefusals| {
            let ended_by_deadline =
                err.is_not_sent() || err.outcome_cause() == Some(OutcomeUnknownCause::Deadline);
            if ended_by_deadline && Instant::now() >= route_deadline {
                if let Some(refused) = std::mem::take(refusals).into_error(key.target_label()) {
                    return refused;
                }
            }
            err
        };
        loop {
            attempt = attempt.saturating_add(1);
            let body = serde_json::to_vec(&ClientControlRequest::RouteOpen {
                target: route_open.target.clone(),
                identity: route_open.identity.clone(),
                consumer_identity: route_open.consumer_identity.clone(),
                consumer_capabilities: route_open.consumer_capabilities.clone(),
                role_versions: route_open.role_versions.clone(),
                admission_facts: None,
                scope: route_open.scope.cloned(),
            })
            .map_err(|err| CallError::not_sent(format!("failed to encode route.open: {err}")))?;
            match self
                .paced_route_open(
                    body,
                    route_deadline,
                    Some(route_open.reverse_requests.clone()),
                )
                .await
            {
                Ok(TerminalFrame::Response {
                    generation, body, ..
                }) => {
                    let response =
                        serde_json::from_slice::<ClientControlResponse>(&body).map_err(|err| {
                            CallError::not_sent(format!(
                                "failed to decode route.open response: {err}"
                            ))
                        })?;
                    let ClientControlResponse::RouteOpen {
                        route_channel,
                        route_epoch,
                    } = response
                    else {
                        return Err(CallError::not_sent(
                            "route.open returned an unexpected control response",
                        ));
                    };
                    let handle = self
                        .ingress_handle(generation, route_channel, route_epoch)
                        .unwrap_or_else(|| {
                            RouteHandle::new_consumer(
                                route_channel,
                                route_epoch,
                                generation,
                                route_open.reverse_requests.clone(),
                            )
                        });
                    let route = RouteState {
                        handle,
                        sem: Arc::new(Semaphore::new(DEFAULT_ROUTE_WINDOW)),
                    };
                    let install = {
                        let mut inner = self.lock_inner();
                        if inner.closed {
                            return Err(CallError::not_sent("consumer closed"));
                        }
                        // Close-beats-reopen guard: a close_route may have flipped this
                        // opening's `closed` flag WHILE this route.open was in flight. If
                        // so, close wins — do NOT cache the channel; GOODBYE it below and
                        // fail as NotSent (the route was closed before the open landed).
                        let closed_during_open = inner.openings.get(key).is_some_and(|o| o.closed);
                        if closed_during_open
                            || inner.generation != generation
                            || inner.writer.is_none()
                        {
                            RouteInstall::Discard {
                                closed: closed_during_open,
                            }
                        } else {
                            let cached = inner.cache_route(key.clone(), route.clone());
                            RouteInstall::Cached(cached)
                        }
                    };
                    match install {
                        RouteInstall::Cached(cached) => return Ok(cached),
                        RouteInstall::Discard { closed } => {
                            if closed {
                                // GOODBYE the channel we opened so the daemon/module don't
                                // leak it, then report the close as a NotSent failure.
                                self.send_route_goodbye(route.handle, true);
                                self.uninstall_route_handle(route.handle);
                                return Err(CallError::not_sent(
                                    "route was closed before route.open completed",
                                ));
                            }
                            // Stale generation / writer gone: fall through to retry.
                        }
                    }
                    self.sleep_until_retry(route_deadline, self.jittered(opts.route_retry.base))
                        .await?;
                }
                Ok(TerminalFrame::Error { body, .. }) => {
                    // The deadline is the ONLY binder for retryable refusals.
                    // An attempt cap used to share this condition, and because
                    // the capped backoff sums to seconds it strictly dominated
                    // the deadline — the advertised reload patience was never
                    // delivered, and module restarts whose reload exceeded a
                    // few seconds failed every managed caller. A restart
                    // legitimately keeps routes refused for about a minute;
                    // capped per-attempt backoff bounds pressure.
                    if !is_retryable_route_open_code(&body.code) {
                        return Err(CallError::route_open_refused(key.target_label(), body));
                    }
                    refusals.record(body);
                    if Instant::now() >= route_deadline {
                        // A refusal was just recorded, so the fallback is unreachable.
                        return Err(std::mem::take(&mut refusals)
                            .into_error(key.target_label())
                            .unwrap_or_else(|| {
                                CallError::not_sent("route.open retry deadline elapsed")
                            }));
                    }
                    let delay = self.jittered(opts.route_retry.delay_after_attempt(attempt));
                    if let Err(err) = self.sleep_until_retry(route_deadline, delay).await {
                        return Err(expired(err, &mut refusals));
                    }
                    continue;
                }
                Ok(TerminalFrame::StreamEnd) => {
                    return Err(CallError::not_sent("route.open returned StreamEnd"));
                }
                Err(err) if err.is_not_sent() && Instant::now() < route_deadline => {
                    let delay = self.jittered(opts.route_retry.delay_after_attempt(attempt));
                    if let Err(err) = self.sleep_until_retry(route_deadline, delay).await {
                        return Err(expired(err, &mut refusals));
                    }
                }
                Err(err) => return Err(expired(err, &mut refusals)),
            }
        }

        #[allow(unreachable_code)]
        Err(CallError::not_sent(format!(
            "route.open retry deadline elapsed for target {}",
            key.target_label()
        )))
    }

    async fn sleep_until_retry(&self, deadline: Instant, delay: Duration) -> Result<(), CallError> {
        if Instant::now() >= deadline {
            return Err(CallError::not_sent("retry deadline elapsed"));
        }
        let bounded = delay.min(deadline.saturating_duration_since(Instant::now()));
        tokio::select! {
            () = self.close_token.cancelled() => Err(CallError::not_sent("consumer closed")),
            () = sleep(bounded) => Ok(()),
        }
    }

    async fn control_call(
        self: &Arc<Self>,
        body: Vec<u8>,
        deadline: Instant,
        retain_late_route_open: bool,
        route_open_reverse_requests: Option<ReverseRequestRegistry>,
    ) -> Result<TerminalFrame, CallError> {
        self.ensure_connected_for_call(deadline).await?;
        self.send_request(RequestSend {
            binary: false,
            expected_handle: None,
            channel: 0,
            epoch: 0,
            body,
            priority: Priority::Interactive,
            admission_class: AdmissionClass::Normal,
            deadline,
            retain_late_route_open,
            route_open_reverse_requests,
        })
        .await
    }

    async fn send_request(
        self: &Arc<Self>,
        request: RequestSend,
    ) -> Result<TerminalFrame, CallError> {
        self.send_request_cancellable(request, None).await
    }

    async fn send_request_cancellable(
        self: &Arc<Self>,
        request: RequestSend,
        cancel: Option<Arc<UnaryCancel>>,
    ) -> Result<TerminalFrame, CallError> {
        let RequestSend {
            expected_handle,
            channel,
            epoch,
            body,
            binary,
            priority,
            admission_class,
            deadline,
            retain_late_route_open,
            route_open_reverse_requests,
        } = request;
        if Instant::now() >= deadline {
            return Err(CallError::not_sent(
                "call deadline elapsed before request was sent",
            ));
        }
        let (generation, corr, writer) = {
            let mut inner = self.lock_inner();
            if inner.closed {
                return Err(CallError::not_sent("consumer closed"));
            }
            let generation = inner.generation;
            if let Some(expected) = expected_handle {
                let route_pair_matches =
                    channel == 0 || (expected.channel == channel && expected.epoch == epoch);
                if expected.connection_token() != generation
                    || !route_pair_matches
                    || inner.route_epochs.get(&expected.channel) != Some(&expected)
                    || inner.retired_routes.contains(&expected)
                {
                    return Err(CallError::StaleRouteHandle(expected));
                }
            }
            let Some(writer) = inner.writer.clone() else {
                return Err(CallError::not_sent("subc connection is down before send"));
            };
            let Some(corr) = inner.next_corr else {
                drop(inner);
                self.handle_generation_drop(
                    generation,
                    "channel-0 correlation allocator exhausted".to_string(),
                );
                return Err(CallError::not_sent(
                    "correlation allocator exhausted; connection closed",
                ));
            };
            inner.next_corr = corr.checked_add(1);
            (generation, corr, writer)
        };

        let frame = Frame::build(
            FrameType::Request,
            Flags::new(binary, priority, false).with_admission_class(admission_class),
            channel,
            epoch,
            corr,
            body,
        )
        .map_err(|err| CallError::not_sent(format!("failed to build request frame: {err}")))?;
        let key = PendingKey {
            generation,
            channel,
            epoch,
            corr,
        };
        let (tx, rx) = oneshot::channel();
        {
            let mut inner = self.lock_inner();
            if inner.closed || inner.generation != generation || inner.writer.is_none() {
                return Err(CallError::not_sent(
                    "connection changed before request registration",
                ));
            }
            if let Some(expected) = expected_handle {
                if inner.route_epochs.get(&expected.channel) != Some(&expected)
                    || inner.retired_routes.contains(&expected)
                {
                    return Err(CallError::StaleRouteHandle(expected));
                }
            }
            let expected_control_handle = (channel == 0 && !retain_late_route_open)
                .then_some(expected_handle)
                .flatten();
            inner.pending.insert(
                key,
                PendingEntry::unary(
                    tx,
                    retain_late_route_open,
                    expected_control_handle,
                    route_open_reverse_requests,
                ),
            );
            if retain_late_route_open {
                inner.pending.get_mut(&key).unwrap().route_open_module =
                    serde_json::from_slice::<serde_json::Value>(&frame.body)
                        .ok()
                        .and_then(|body| {
                            body.get("target")?
                                .get("module_id")?
                                .as_str()
                                .map(str::to_string)
                        });
            }
        }
        let mut registration =
            PendingRegistration::new(Arc::clone(self), key, retain_late_route_open);

        match timeout_at(
            deadline,
            writer.send(WriteCommand {
                frame,
                pending: Some(key),
            }),
        )
        .await
        {
            Ok(Ok(())) => {}
            Ok(Err(_)) => {
                let accepted = registration.remove_pending().unwrap_or(false);
                return Err(classify_failure(
                    accepted,
                    "writer task closed before accepting request",
                    OutcomeUnknownCause::WriterClosed,
                ));
            }
            Err(_) => {
                let _ = registration.remove_pending();
                return Err(CallError::not_sent(
                    "call deadline elapsed waiting for writer capacity",
                ));
            }
        }

        if let Some(cancel) = cancel {
            cancel.activate(key, priority, deadline);
            if cancel.requested() {
                cancel.cancel().await;
            }
        }

        tokio::select! {
            result = timeout_at(deadline, rx) => match result {
                Ok(Ok(result)) => {
                    registration.disarm();
                    result.into_call_result()
                }
                Ok(Err(_)) => {
                    registration.disarm();
                    Err(CallError::not_sent("pending response channel closed"))
                }
                Err(_) => {
                    let accepted = if retain_late_route_open {
                        registration.disarm();
                        self.pending_accepted(key).unwrap_or(false)
                    } else {
                        registration.remove_pending().unwrap_or(false)
                    };
                    if accepted {
                        self.spawn_liveness_probe();
                    }
                    Err(classify_failure(
                        accepted,
                        format!("request on channel {channel} timed out at its deadline"),
                        OutcomeUnknownCause::Deadline,
                    ))
                }
            },
            () = self.close_token.cancelled() => {
                let accepted = registration.remove_pending().unwrap_or(false);
                Err(classify_failure(accepted, "consumer closed while request was pending", OutcomeUnknownCause::ConsumerClosed))
            }
        }
    }

    /// Probe a connection retained after an accepted request reaches its reply deadline.
    ///
    /// Deadline timeouts deliberately keep a connection because scheduler pressure can delay
    /// an otherwise healthy reply. A channel-0 Ping plus any later inbound frame separates that
    /// case from a half-open socket, which would otherwise pin every subsequent request.
    fn spawn_liveness_probe(self: &Arc<Self>) {
        if self.liveness_probe_running.swap(true, Ordering::AcqRel) {
            return;
        }

        let allocation = {
            let mut inner = self.lock_inner();
            // A pending CHANNEL-0 request suspends the probe: the daemon's
            // connection loop is FIFO and some channel-0 handlers park it
            // inline for seconds (route.open awaits the module bind ack for up
            // to route_bind_relay_timeout, ~12s in production), during which
            // our Ping sits unread in the daemon's socket buffer. Silence is
            // then explained by our own control op, and convicting would tear
            // down a healthy connection mid-bind. The gate is local knowledge
            // (we always know our own pendings) and re-arms on the next
            // deadline settle; the same check runs again before conviction.
            let control_pending = inner
                .pending
                .keys()
                .any(|key| key.generation == inner.generation && key.channel == 0);
            if inner.closed || control_pending || !matches!(&inner.reconnect, ReconnectState::Idle)
            {
                None
            } else {
                match (inner.next_corr, inner.writer.clone()) {
                    (Some(corr), Some(writer)) => {
                        inner.next_corr = corr.checked_add(1);
                        Some((inner.generation, corr, writer))
                    }
                    (None, _) | (_, None) => None,
                }
            }
        };
        let Some((generation, corr, writer)) = allocation else {
            self.liveness_probe_running.store(false, Ordering::Release);
            return;
        };

        let t0 = epoch_millis();
        let ping = match Frame::build(
            FrameType::Ping,
            Flags::new(false, Priority::Interactive, false),
            0,
            0,
            corr,
            Vec::new(),
        ) {
            Ok(ping) => ping,
            Err(_) => {
                self.liveness_probe_running.store(false, Ordering::Release);
                return;
            }
        };
        let window = self.opts.liveness_probe_window;
        let shared = Arc::clone(self);
        tokio::spawn(async move {
            let window_end = Instant::now() + window;
            // A write failure proves nothing in the healthy direction: it may be the
            // first sign of the same broken transport. Let the inbound window decide.
            let _ = timeout_at(
                window_end,
                writer.send(WriteCommand {
                    frame: ping,
                    pending: None,
                }),
            )
            .await;
            sleep_until(window_end).await;

            let control_pending_now = {
                let inner = shared.lock_inner();
                inner
                    .pending
                    .keys()
                    .any(|key| key.generation == generation && key.channel == 0)
            };
            if !shared.close_token.is_cancelled()
                && !control_pending_now // a control op begun during the window explains the silence
                && shared.generation_is_current(generation)
                && shared.last_inbound_ms.load(Ordering::Acquire) < t0
            {
                shared.handle_generation_drop(
                    generation,
                    format!(
                        "liveness probe convicted a half-open socket: no inbound frame for {}ms after a channel-0 Ping",
                        window.as_millis()
                    ),
                );
            }
            shared
                .liveness_probe_running
                .store(false, Ordering::Release);
        });
    }

    async fn send_subscription(
        self: &Arc<Self>,
        subscription: SubscriptionSend,
    ) -> Result<Subscription, CallError> {
        let SubscriptionSend {
            expected_handle,
            channel,
            epoch,
            body,
            priority,
            admission_class,
            event_buffer,
            deadline,
            permit,
        } = subscription;
        if Instant::now() >= deadline {
            return Err(CallError::not_sent(
                "subscription deadline elapsed before request was sent",
            ));
        }
        let (generation, corr, writer) = {
            let mut inner = self.lock_inner();
            if inner.closed {
                return Err(CallError::not_sent("consumer closed"));
            }
            let generation = inner.generation;
            if let Some(expected) = expected_handle {
                if expected.connection_token() != generation
                    || expected.channel != channel
                    || expected.epoch != epoch
                    || inner.route_epochs.get(&channel) != Some(&expected)
                    || inner.retired_routes.contains(&expected)
                {
                    return Err(CallError::StaleRouteHandle(expected));
                }
            }
            let Some(writer) = inner.writer.clone() else {
                return Err(CallError::not_sent("subc connection is down before send"));
            };
            let Some(corr) = inner.next_corr else {
                drop(inner);
                self.handle_generation_drop(
                    generation,
                    "correlation allocator exhausted".to_string(),
                );
                return Err(CallError::not_sent(
                    "correlation allocator exhausted; connection closed",
                ));
            };
            inner.next_corr = corr.checked_add(1);
            (generation, corr, writer)
        };

        // Mark held subscriptions so module drains leave them out of the quiescence wait.
        let frame = Frame::build(
            FrameType::Request,
            Flags(
                Flags::new(false, priority, false)
                    .with_admission_class(admission_class)
                    .0
                    | FLAG_SUBSCRIPTION,
            ),
            channel,
            epoch,
            corr,
            body,
        )
        .map_err(|err| CallError::not_sent(format!("failed to build request frame: {err}")))?;
        let key = PendingKey {
            generation,
            channel,
            epoch,
            corr,
        };
        let (events_tx, events_rx) = mpsc::channel(event_buffer.max(1));
        let (closed_tx, closed_rx) = oneshot::channel();
        let (ended_tx, ended_rx) = watch::channel(None);
        {
            let mut inner = self.lock_inner();
            if inner.closed || inner.generation != generation || inner.writer.is_none() {
                return Err(CallError::not_sent(
                    "connection changed before subscription registration",
                ));
            }
            if let Some(expected) = expected_handle {
                if inner.route_epochs.get(&expected.channel) != Some(&expected)
                    || inner.retired_routes.contains(&expected)
                {
                    return Err(CallError::StaleRouteHandle(expected));
                }
            }
            inner.pending.insert(
                key,
                PendingEntry::subscription(events_tx, closed_tx, ended_tx, permit, priority),
            );
        }
        let mut registration = PendingRegistration::new(Arc::clone(self), key, false);

        match timeout_at(
            deadline,
            writer.send(WriteCommand {
                frame,
                pending: Some(key),
            }),
        )
        .await
        {
            Ok(Ok(())) => {}
            Ok(Err(_)) => {
                let accepted = registration.remove_pending().unwrap_or(false);
                return Err(classify_failure(
                    accepted,
                    "writer task closed before accepting subscription request",
                    OutcomeUnknownCause::WriterClosed,
                ));
            }
            Err(_) => {
                let _ = registration.remove_pending();
                return Err(CallError::not_sent(
                    "subscription deadline elapsed waiting for writer capacity",
                ));
            }
        }

        registration.disarm();
        Ok(Subscription {
            events: events_rx,
            closed: SubscriptionClosed { rx: closed_rx },
            ended: ended_rx,
            cancel: SubscriptionCancel::new(Arc::clone(self), key, priority),
        })
    }

    fn unsubscribe_subscription(
        &self,
        key: PendingKey,
        priority: Priority,
    ) -> Result<(), CallError> {
        let handle = RouteHandle::new(key.channel, key.epoch, key.generation);
        self.validate_current_handle(handle)?;
        let entry = self.lock_inner().pending.remove(&key);
        if let Some(entry) = entry {
            entry.settle_subscription_result(Ok(()));
            self.send_cancel(handle, key.corr, priority);
            self.lock_inner().reap_retired_route(handle);
        }
        Ok(())
    }

    fn route_stream_data(&self, key: PendingKey, body: Vec<u8>) {
        let overflow = {
            let mut inner = self.lock_inner();
            let Some(entry) = inner.pending.get(&key) else {
                return;
            };
            match entry.try_send_stream_data(body) {
                Ok(()) | Err(StreamDataDelivery::NotSubscription) => return,
                Err(StreamDataDelivery::Full) => {
                    let priority = entry
                        .subscription_priority()
                        .unwrap_or(Priority::Interactive);
                    let entry = inner.pending.remove(&key);
                    entry.map(|entry| {
                        (
                            entry,
                            priority,
                            "subscription event channel filled; reader dropped the stream instead of blocking",
                        )
                    })
                }
                Err(StreamDataDelivery::Closed) => {
                    let priority = entry
                        .subscription_priority()
                        .unwrap_or(Priority::Interactive);
                    let entry = inner.pending.remove(&key);
                    entry.map(|entry| {
                        (
                            entry,
                            priority,
                            "subscription event receiver closed before the stream ended",
                        )
                    })
                }
            }
        };

        if let Some((entry, priority, reason)) = overflow {
            entry.settle_call_error(CallError::subscription_backpressure(reason));
            self.send_cancel(
                RouteHandle::new(key.channel, key.epoch, key.generation),
                key.corr,
                priority,
            );
            self.lock_inner().reap_retired_route(RouteHandle::new(
                key.channel,
                key.epoch,
                key.generation,
            ));
        }
    }

    fn register_push_events(
        &self,
        handle: RouteHandle,
    ) -> Result<mpsc::Receiver<PushEvent>, CallError> {
        let (events_tx, events_rx) = mpsc::channel(DEFAULT_PUSH_EVENT_BUFFER);
        let mut inner = self.lock_inner();
        if inner.closed
            || inner.generation != handle.connection_token()
            || inner.writer.is_none()
            || inner.route_epochs.get(&handle.channel) != Some(&handle)
        {
            return Err(CallError::StaleRouteHandle(handle));
        }
        inner.push_event_receivers.insert(handle, events_tx);
        Ok(events_rx)
    }

    fn route_push(&self, handle: RouteHandle, body: Vec<u8>) {
        let should_count_drop = {
            let mut inner = self.lock_inner();
            if inner.closed
                || inner.generation != handle.connection_token()
                || inner.route_epochs.get(&handle.channel) != Some(&handle)
            {
                // Deliberately uncounted: a push against a stale epoch or dead
                // generation has no live subscriber by definition, and the
                // counters below claim delivery loss on LIVE routes only.
                return;
            }
            match inner.push_event_receivers.get(&handle) {
                None => DroppedPush::NoReceiver,
                Some(events) => match events.try_send(PushEvent { handle, body }) {
                    Ok(()) => DroppedPush::Delivered,
                    Err(mpsc::error::TrySendError::Closed(_)) => {
                        inner.push_event_receivers.remove(&handle);
                        DroppedPush::NoReceiver
                    }
                    // A burst KEEPS the subscription (issue #40). This used to
                    // remove the receiver -- documented as loss-signaling via
                    // recv()->None -- but the fleet's real push consumers are
                    // idempotent wake nudges, where one missed event costs a
                    // poll cycle and a lost subscription costs every later wake
                    // until a re-register path that history says is where bugs
                    // live. Matches control_push below; the drop is counted on
                    // its own counter so a too-slow consumer is diagnosable as
                    // such rather than filed under "never subscribed".
                    Err(mpsc::error::TrySendError::Full(_)) => DroppedPush::ReceiverFull,
                },
            }
        };
        match should_count_drop {
            DroppedPush::Delivered => {}
            DroppedPush::NoReceiver => {
                self.pushes_dropped_no_receiver
                    .fetch_add(1, Ordering::Relaxed);
            }
            DroppedPush::ReceiverFull => {
                self.pushes_dropped_receiver_full
                    .fetch_add(1, Ordering::Relaxed);
            }
        }
    }

    /// Deliver a daemon-originated channel-0 control push to the registered
    /// consumer receiver, or count the drop. Never blocks the reader.
    fn control_push(&self, body: &[u8]) {
        let parsed = serde_json::from_slice::<serde_json::Value>(body)
            .ok()
            .and_then(|value| {
                let op = value.get("op")?.as_str()?.to_string();
                Some(ControlPush { op, body: value })
            });
        let delivered = match parsed {
            None => false,
            Some(push) => {
                let mut inner = self.lock_inner();
                inner.record_route_end(&push);
                match inner.control_push_receiver.as_ref() {
                    None => false,
                    Some(sender) => match sender.try_send(push) {
                        Ok(()) => true,
                        Err(mpsc::error::TrySendError::Closed(_)) => {
                            inner.control_push_receiver = None;
                            false
                        }
                        Err(mpsc::error::TrySendError::Full(_)) => false,
                    },
                }
            }
        };
        if !delivered {
            self.control_pushes_dropped.fetch_add(1, Ordering::Relaxed);
        }
    }

    fn send_cancel(&self, handle: RouteHandle, corr: u64, priority: Priority) {
        let writer = {
            let inner = self.lock_inner();
            if inner.closed
                || inner.generation != handle.connection_token()
                || !route_is_installed(&inner, handle)
            {
                return;
            }
            inner.writer.clone()
        };
        let Some(writer) = writer else {
            return;
        };
        let Ok(frame) = Frame::build(
            FrameType::Cancel,
            Flags::new(false, priority, false),
            handle.channel,
            handle.epoch,
            corr,
            Vec::new(),
        ) else {
            return;
        };
        let _ = writer.try_send(WriteCommand {
            frame,
            pending: None,
        });
    }

    fn mark_pending_accepted(&self, key: PendingKey) -> bool {
        let mut inner = self.lock_inner();
        if inner.closed || inner.generation != key.generation {
            return false;
        }
        let Some(entry) = inner.pending.get_mut(&key) else {
            return false;
        };
        entry.accepted = true;
        true
    }

    fn settle_pending(self: &Arc<Self>, key: PendingKey, terminal: PendingTerminal) {
        let entry = self.lock_inner().remove_pending(&key);
        let Some(entry) = entry else {
            return;
        };
        if entry.retain_late_route_open && entry.completion_is_closed() {
            if let PendingTerminal::Response {
                generation, body, ..
            } = &terminal
            {
                if let Ok(ClientControlResponse::RouteOpen {
                    route_channel,
                    route_epoch,
                }) = serde_json::from_slice::<ClientControlResponse>(body)
                {
                    let handle = RouteHandle::new(route_channel, route_epoch, *generation);
                    self.send_route_goodbye(handle, true);
                    self.uninstall_route_handle(handle);
                }
            }
            return;
        }
        entry.settle_terminal(terminal);
    }

    fn pending_accepted(&self, key: PendingKey) -> Option<bool> {
        self.lock_inner()
            .pending
            .get(&key)
            .map(|entry| entry.accepted)
    }

    fn handle_generation_drop(self: &Arc<Self>, generation: u64, reason: String) {
        self.handle_generation_drop_with_cause(
            generation,
            reason,
            OutcomeUnknownCause::ConnectionFailed,
        );
    }

    fn handle_generation_drop_with_cause(
        self: &Arc<Self>,
        generation: u64,
        reason: String,
        cause: OutcomeUnknownCause,
    ) {
        let (should_emit, pending, callbacks) = {
            let mut inner = self.lock_inner();
            if inner.closed || inner.generation != generation || inner.writer.is_none() {
                return;
            }
            inner.writer = None;
            inner.restored_token = inner.restored_token.saturating_add(1);
            inner.close_routes();
            inner.route_epochs.clear();
            inner.route_modules.clear();
            inner.route_end_reasons.clear();
            inner.legacy_channel_reasons.clear();
            let pending = drain_pending_generation(&mut inner.pending, generation);
            // An opening belongs to its lead caller, not to a socket generation:
            // the caller may still be retrying after this transport is replaced.
            // Keep its waiters and close flag until its OpeningGuard finishes, so
            // a new caller cannot start a competing open for the same key.
            let callbacks = inner.callbacks.clone();
            (true, pending, callbacks)
        };

        if should_emit {
            settle_route_pending_entries_with_cause(
                pending,
                reason.clone(),
                RouteEndReason::ConnectionLost,
                cause,
            );
            emit_callbacks(callbacks, ConnectionState::Dropped);
            self.notify.notify_waiters();
            let _ = self.spawn_reconnect(generation);
        }
    }

    fn close_sync(&self, reason: &str) {
        let (pending, openings, routes, reader, writer, reconnect) = {
            let mut inner = self.lock_inner();
            if inner.closed {
                return;
            }
            inner.closed = true;
            inner.writer = None;
            inner.route_epochs.clear();
            inner.route_modules.clear();
            inner.route_end_reasons.clear();
            inner.legacy_channel_reasons.clear();
            inner.push_event_receivers.clear();
            self.close_token.cancel();
            let reconnect = match std::mem::replace(&mut inner.reconnect, ReconnectState::Idle) {
                ReconnectState::Background { task, .. } => Some(task),
                ReconnectState::Idle | ReconnectState::Inline { .. } => None,
            };
            (
                inner
                    .pending
                    .drain()
                    .map(|(_, entry)| entry)
                    .collect::<Vec<_>>(),
                inner
                    .openings
                    .drain()
                    .map(|(_, opening)| opening.waiters)
                    .collect::<Vec<_>>(),
                inner.drain_routes(),
                inner.reader_task.take(),
                inner.writer_task.take(),
                reconnect,
            )
        };
        for route in routes {
            route.sem.close();
        }
        if let Some(handle) = reader {
            handle.abort();
        }
        if let Some(handle) = writer {
            handle.abort();
        }
        if let Some(handle) = reconnect {
            handle.abort();
        }
        settle_pending_entries(pending, reason.to_string());
        fail_openings(openings, SharedCallFailure::not_sent(reason.to_string()));
        self.notify.notify_waiters();
    }

    fn validate_current_handle(&self, handle: RouteHandle) -> Result<(), CallError> {
        let inner = self.lock_inner();
        if inner.closed
            || inner.generation != handle.connection_token()
            || inner.writer.is_none()
            || !route_is_installed(&inner, handle)
        {
            Err(CallError::StaleRouteHandle(handle))
        } else {
            Ok(())
        }
    }

    fn route_state(&self, handle: RouteHandle) -> Result<RouteState, CallError> {
        let inner = self.lock_inner();
        if inner.closed
            || inner.generation != handle.connection_token()
            || inner.writer.is_none()
            || inner.route_epochs.get(&handle.channel) != Some(&handle)
        {
            return Err(CallError::StaleRouteHandle(handle));
        }

        let route = inner
            .route_by_channel
            .get(&handle.channel)
            .and_then(|key| inner.routes.get(key))
            .or_else(|| inner.one_shot_routes.get(&handle.channel));
        debug_assert!(route.is_none_or(|route| route.handle == handle));
        route
            .filter(|route| route.handle == handle)
            .cloned()
            .ok_or(CallError::StaleRouteHandle(handle))
    }

    fn route_is_current(&self, key: &RouteKey, route: &RouteState) -> bool {
        let inner = self.lock_inner();
        if inner.closed
            || inner.generation != route.handle.connection_token()
            || inner.writer.is_none()
        {
            return false;
        }
        inner.routes.get(key).is_some_and(|cached| {
            cached.handle == route.handle && Arc::ptr_eq(&cached.sem, &route.sem)
        })
    }

    fn invalidate_route(&self, key: &RouteKey, expected_handle: Option<RouteHandle>) {
        let removed = {
            let mut inner = self.lock_inner();
            match inner.routes.get(key) {
                Some(route) if expected_handle.is_none_or(|expected| expected == route.handle) => {
                    let removed = inner.evict_route(key);
                    if let Some(route) = &removed {
                        // Eviction stops new calls, but siblings may already be
                        // executing or awaiting their own refusal. Keep ingress
                        // until those pending entries settle; never resend them
                        // merely because another call was refused.
                        inner.retired_routes.insert(route.handle);
                        inner.reap_retired_route(route.handle);
                    }
                    removed
                }
                _ => None,
            }
        };
        if let Some(route) = removed {
            route.sem.close();
        }
    }

    fn finish_opening(&self, key: &RouteKey, result: Result<RouteState, SharedCallFailure>) {
        let opening = self.lock_inner().openings.remove(key);
        for waiter in opening.map(|o| o.waiters).unwrap_or_default() {
            let _ = waiter.send(result.clone());
        }
    }

    async fn close_handle(
        self: &Arc<Self>,
        handle: RouteHandle,
        opts: &CloseRouteOptions,
    ) -> Result<(), CallError> {
        self.validate_current_handle(handle)?;
        let routes = {
            let mut inner = self.lock_inner();
            inner
                .route_end_reasons
                .insert(handle.channel, (RouteEndReason::ClosedByCaller, true));
            inner
                .remove_route_by_handle(handle)
                .into_iter()
                .collect::<Vec<_>>()
        };
        if opts.drain {
            self.drain_channel(handle, opts.drain_timeout).await;
        }
        for route in routes {
            route.sem.close();
        }
        self.fail_channel_pending(
            handle,
            "route closed by close_handle",
            RouteEndReason::ClosedByCaller,
        );
        self.send_route_goodbye(handle, false);
        self.uninstall_route_handle(handle);
        Ok(())
    }

    /// Tear down one route by key. See [`SubcConsumer::close_route`].
    async fn close_route(self: &Arc<Self>, key: &RouteKey, opts: &CloseRouteOptions) {
        // Under the lock: flip the close-beats-reopen flag on any in-flight open for
        // this key (so a lead-opener whose channel hasn't been cached yet refuses to
        // install it), and remove the cached route if one exists.
        let route = {
            let mut inner = self.lock_inner();
            if let Some(opening) = inner.openings.get_mut(key) {
                opening.closed = true;
            }
            let route = inner.remove_route(key);
            if let Some(route) = &route {
                inner
                    .route_end_reasons
                    .insert(route.handle.channel, (RouteEndReason::ClosedByCaller, true));
            }
            route
        };

        // Nothing cached: either never opened (idempotent no-op) or still opening (the
        // racing lead-opener will see the flag and GOODBYE whatever channel it opens).
        let Some(route) = route else {
            return;
        };

        if opts.drain {
            // Wait for in-flight UNARY requests on this channel to settle naturally,
            // bounded by drain_timeout, before tearing the route down.
            self.drain_channel(route.handle, opts.drain_timeout).await;
        }

        // Closing the semaphore makes any not-yet-sent acquire() return Err -> the
        // caller classifies it NotSent. Already-sent pending requests are settled
        // at-most-once (OutcomeUnknown if the writer accepted their bytes).
        route.sem.close();
        self.fail_channel_pending(
            route.handle,
            "route closed by close_route",
            RouteEndReason::ClosedByCaller,
        );

        // Best-effort route GOODBYE: the daemon releases the route + relays the module
        // route-gone GOODBYE the module's reaper consumes. One-way, no ack.
        self.send_route_goodbye(route.handle, false);
        self.uninstall_route_handle(route.handle);
    }

    fn uninstall_route_handle(&self, handle: RouteHandle) {
        let mut inner = self.lock_inner();
        inner.retired_routes.remove(&handle);
        if inner.route_epochs.get(&handle.channel) == Some(&handle) {
            let installed = inner.route_epochs.remove(&handle.channel).unwrap();
            inner.push_event_receivers.remove(&handle);
            release_reverse_request_registry(installed);
        }
    }

    fn route_not_sent_error(&self, handle: RouteHandle) -> CallError {
        let inner = self.lock_inner();
        let reason = if inner.generation != handle.connection_token() || inner.writer.is_none() {
            RouteEndReason::ConnectionLost
        } else {
            inner.route_end_reason(handle.channel)
        };
        CallError::NotSent(Box::new(RouteEnded {
            message: "route flow-control semaphore closed".into(),
            reason,
        }))
    }

    /// Settle every pending request on this handle as OutcomeUnknown if the writer
    /// accepted its bytes, or NotSent otherwise, preserving the route ending cause.
    fn fail_channel_pending(
        &self,
        handle: RouteHandle,
        reason: &str,
        close_reason: RouteEndReason,
    ) {
        let entries = {
            let mut inner = self.lock_inner();
            inner
                .route_end_reasons
                .insert(handle.channel, (close_reason.clone(), true));
            drain_pending_handle(&mut inner.pending, handle, true)
        };
        settle_route_pending_entries(entries, reason.to_string(), close_reason);
    }

    /// Resolve once every in-flight unary pending on `channel` has settled, or the
    /// timeout elapses. Polls the pending map (entries are removed on settle); the
    /// volume here is tiny (a route window is small) so a short poll is adequate.
    async fn drain_channel(&self, handle: RouteHandle, timeout: Duration) {
        let deadline = Instant::now() + timeout;
        loop {
            let has_inflight = {
                let inner = self.lock_inner();
                inner.pending.iter().any(|(key, entry)| {
                    key.generation == handle.connection_token()
                        && key.channel == handle.channel
                        && key.epoch == handle.epoch
                        && !entry.is_subscription()
                })
            };
            if !has_inflight || Instant::now() >= deadline {
                return;
            }
            sleep(Duration::from_millis(5)).await;
        }
    }

    /// Queue a header-only route GOODBYE if `handle` is still live on this connection.
    /// Late successful route.open cleanup sets `close_on_failure`: orphan prevention then
    /// requires closing the connection when the GOODBYE cannot enter the writer queue.
    fn send_route_goodbye(self: &Arc<Self>, handle: RouteHandle, close_on_failure: bool) -> bool {
        let writer = {
            let inner = self.lock_inner();
            if inner.closed
                || inner.generation != handle.connection_token()
                || inner.route_epochs.get(&handle.channel) != Some(&handle)
            {
                return false;
            }
            inner.writer.clone()
        };
        let Some(writer) = writer else {
            return false;
        };
        let Ok(frame) = Frame::build(
            FrameType::Goodbye,
            Flags::new(false, Priority::Interactive, false),
            handle.channel,
            handle.epoch,
            0,
            Vec::new(),
        ) else {
            return false;
        };
        if writer
            .try_send(WriteCommand {
                frame,
                pending: None,
            })
            .is_ok()
        {
            return true;
        }
        if close_on_failure {
            self.handle_generation_drop(
                handle.connection_token(),
                "failed to queue late route.open cleanup GOODBYE".to_string(),
            );
        }
        false
    }

    fn emit_connection_state(&self, state: ConnectionState) {
        let callbacks = self.lock_inner().callbacks.clone();
        emit_callbacks(callbacks, state);
    }
}

#[derive(Clone, Copy)]
enum InstallKind {
    Initial,
    Reconnect,
}

enum EnsureAction {
    Wait,
    Lead {
        generation: u64,
        stale_task: Option<JoinHandle<()>>,
    },
}

/// The reconnect state is fenced by the generation whose transport failed. A
/// newer generation can replace an older attempt, and completion only changes
/// the state when its generation still owns the slot.
enum ReconnectState {
    Idle,
    Inline {
        generation: u64,
    },
    Background {
        generation: u64,
        task: JoinHandle<()>,
    },
}

/// Outcome of the install decision after a route.open response arrives, taken under
/// the inner lock so a racing close_route is observed atomically.
enum RouteInstall {
    /// Install (or reuse) the cached route and return it.
    Cached(RouteState),
    /// Do not install. `closed` => a close_route won the race (GOODBYE + NotSent);
    /// otherwise the generation moved (retry the open).
    Discard { closed: bool },
}

enum RouteOpenAction {
    Wait(oneshot::Receiver<Result<RouteState, SharedCallFailure>>),
    Lead,
}

struct RouteOpenParams<'a> {
    target: &'a RouteTarget,
    identity: &'a BindIdentity,
    consumer_identity: &'a Option<ConsumerIdentity>,
    consumer_capabilities: &'a Option<Vec<String>>,
    /// Already normalized: an empty map is `None` here, as in the route key.
    role_versions: &'a Option<BTreeMap<String, String>>,
    reverse_requests: &'a ReverseRequestRegistry,
    /// The scope every route.open for this key asks to be admitted under, so a
    /// reopen after the route drops carries the same selector as the first open.
    scope: Option<&'a ScopeSelector>,
}

struct RequestSend {
    expected_handle: Option<RouteHandle>,
    channel: u16,
    epoch: u32,
    body: Vec<u8>,
    binary: bool,
    priority: Priority,
    admission_class: AdmissionClass,
    deadline: Instant,
    retain_late_route_open: bool,
    route_open_reverse_requests: Option<ReverseRequestRegistry>,
}

struct SubscriptionSend {
    expected_handle: Option<RouteHandle>,
    channel: u16,
    epoch: u32,
    body: Vec<u8>,
    priority: Priority,
    admission_class: AdmissionClass,
    event_buffer: usize,
    deadline: Instant,
    permit: OwnedSemaphorePermit,
}

struct OpeningGuard {
    shared: Arc<Shared>,
    key: RouteKey,
    finished: bool,
}

impl OpeningGuard {
    fn new(shared: Arc<Shared>, key: RouteKey) -> Self {
        Self {
            shared,
            key,
            finished: false,
        }
    }

    fn finish(&mut self, result: Result<RouteState, SharedCallFailure>) {
        self.shared.finish_opening(&self.key, result);
        self.finished = true;
    }
}

impl Drop for OpeningGuard {
    fn drop(&mut self) {
        if !self.finished {
            self.shared.finish_opening(
                &self.key,
                Err(SharedCallFailure::not_sent(
                    "route.open future was cancelled",
                )),
            );
        }
    }
}

struct InlineReconnectGuard {
    shared: Arc<Shared>,
    generation: u64,
    finished: bool,
}

impl InlineReconnectGuard {
    fn new(shared: Arc<Shared>, generation: u64) -> Self {
        Self {
            shared,
            generation,
            finished: false,
        }
    }

    fn finish(&mut self) {
        self.shared.finish_inline_reconnect(self.generation);
        self.finished = true;
    }
}

impl Drop for InlineReconnectGuard {
    fn drop(&mut self) {
        if !self.finished {
            self.shared.finish_inline_reconnect(self.generation);
        }
    }
}

#[derive(Clone)]
struct RouteState {
    handle: RouteHandle,
    sem: Arc<Semaphore>,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct RouteKey {
    target: RouteTargetKey,
    project_root: PathBuf,
    harness: String,
    session: String,
    consumer_identity: Option<ConsumerIdentityKey>,
    consumer_capabilities: Option<ConsumerCapabilitiesKey>,
    /// The role versions the route was opened with; `None` for a route that
    /// declared none. Part of the key so a legacy route and a versioned one to
    /// the same target are never shared: the provider chose its wire shape
    /// from these at bind. A `BTreeMap` is already in canonical order.
    role_versions: Option<BTreeMap<String, String>>,
    /// The scope the route was admitted under; `None` for an unscoped route.
    /// Part of the key so a route bound to one session's scope (or one epoch
    /// of it) is never reused for another, nor for an unscoped caller.
    scope: Option<ScopeKey>,
}

impl RouteKey {
    fn new(
        target: &RouteTarget,
        identity: &BindIdentity,
        consumer_identity: Option<&ConsumerIdentity>,
        consumer_capabilities: Option<&[String]>,
    ) -> Self {
        Self {
            target: RouteTargetKey::from(target),
            project_root: identity.project_root.clone(),
            harness: identity.harness.clone(),
            session: identity.session.clone(),
            consumer_identity: consumer_identity.map(ConsumerIdentityKey::from),
            consumer_capabilities: consumer_capabilities.map(ConsumerCapabilitiesKey::from_slice),
            role_versions: None,
            scope: None,
        }
    }

    fn with_role_versions(mut self, role_versions: Option<&BTreeMap<String, String>>) -> Self {
        self.role_versions = role_versions.cloned();
        self
    }

    fn with_scope(mut self, scope: Option<&ScopeSelector>) -> Self {
        self.scope = scope.map(ScopeKey::from);
        self
    }

    fn target_label(&self) -> String {
        match &self.target {
            RouteTargetKey::ToolProvider { module_id } => format!("tool_provider:{module_id}"),
            RouteTargetKey::ManagementSurface { module_id } => {
                format!("management_surface:{module_id}")
            }
            RouteTargetKey::InternalService {
                module_id,
                service_id,
            } => format!("internal_service:{module_id}:{service_id}"),
        }
    }
}

#[derive(Clone, Hash, PartialEq, Eq)]
struct ConsumerIdentityKey {
    module_id: String,
    launch_nonce: String,
}

// Hand-written so the launch nonce is never printed. The nonce is the credential
// that attributes a connection to a supervised module, and a derived Debug would
// write it into any log line or panic message that formats this value. This key sits
// inside the route cache key, which is formatted in logs.
impl fmt::Debug for ConsumerIdentityKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ConsumerIdentityKey")
            .field("module_id", &self.module_id)
            .field(
                "launch_nonce",
                &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
            )
            .finish()
    }
}

impl From<&ConsumerIdentity> for ConsumerIdentityKey {
    fn from(value: &ConsumerIdentity) -> Self {
        Self {
            module_id: value.module_id.clone(),
            launch_nonce: value.launch_nonce.clone(),
        }
    }
}

/// Every field of a [`ScopeSelector`], in hashable form.
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct ScopeKey {
    /// The owner principal as its JSON encoding. `Principal` is not `Hash`,
    /// and matching on its variants here would stop compiling when the
    /// protocol crate adds one; the tagged encoding is unique per principal.
    owner: String,
    scope_ref: String,
    scope_epoch: Option<u64>,
    bind_proof_digest: Option<[u8; 32]>,
}

impl From<&ScopeSelector> for ScopeKey {
    fn from(value: &ScopeSelector) -> Self {
        Self {
            owner: serde_json::to_string(&value.owner)
                .unwrap_or_else(|_| format!("{:?}", value.owner)),
            scope_ref: value.scope_ref.clone(),
            scope_epoch: value.scope_epoch,
            bind_proof_digest: value
                .bind_proof
                .as_ref()
                .map(|proof| Sha256::digest(proof.as_bytes()).into()),
        }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct ConsumerCapabilitiesKey {
    values: Vec<String>,
}

impl ConsumerCapabilitiesKey {
    fn from_slice(values: &[String]) -> Self {
        let mut values = values.to_vec();
        values.sort();
        values.dedup();
        Self { values }
    }
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
enum RouteTargetKey {
    ToolProvider {
        module_id: String,
    },
    ManagementSurface {
        module_id: String,
    },
    InternalService {
        module_id: String,
        service_id: String,
    },
}

impl From<&RouteTarget> for RouteTargetKey {
    fn from(value: &RouteTarget) -> Self {
        match value {
            RouteTarget::ToolProvider { module_id } => Self::ToolProvider {
                module_id: module_id.clone(),
            },
            RouteTarget::ManagementSurface { module_id } => Self::ManagementSurface {
                module_id: module_id.clone(),
            },
            RouteTarget::InternalService {
                module_id,
                service_id,
            } => Self::InternalService {
                module_id: module_id.clone(),
                service_id: service_id.clone(),
            },
        }
    }
}

#[derive(Debug, Clone)]
struct SharedCallFailure {
    kind: FailureKind,
    message: String,
    /// A route.open refusal travels typed, so every caller sharing this
    /// failure (the single-flight leader and its waiters) still gets
    /// `CallError::route_open_refusal`, not just the message text.
    refusal: Option<RouteOpenRefused>,
}

impl SharedCallFailure {
    fn not_sent(message: impl Into<String>) -> Self {
        Self {
            kind: FailureKind::NotSent,
            message: message.into(),
            refusal: None,
        }
    }

    fn into_call_error(self) -> CallError {
        match (self.kind, self.refusal) {
            (FailureKind::NotSent, Some(refused)) => CallError::NotSent(Box::new(refused)),
            (FailureKind::NotSent, None) => CallError::not_sent(self.message),
            (FailureKind::OutcomeUnknown(source), _) => CallError::outcome_unknown_source(source),
        }
    }
}

impl From<CallError> for SharedCallFailure {
    fn from(value: CallError) -> Self {
        match value {
            CallError::NotSent(err) => Self {
                kind: FailureKind::NotSent,
                message: err.to_string(),
                refusal: err.downcast_ref::<RouteOpenRefused>().cloned(),
            },
            CallError::OutcomeUnknown(err) => Self {
                kind: FailureKind::OutcomeUnknown(
                    err.downcast_ref::<OutcomeUnknownSource>()
                        .cloned()
                        .unwrap_or_else(|| OutcomeUnknownSource {
                            message: err.to_string(),
                            cause: OutcomeUnknownCause::CompletionFailed,
                            route_reason: None,
                        }),
                ),
                message: err.to_string(),
                refusal: None,
            },
            CallError::Module(body) => Self {
                kind: FailureKind::OutcomeUnknown(OutcomeUnknownSource {
                    message: format!(
                        "unexpected module error during route.open: {} ({})",
                        body.code, body.message
                    ),
                    cause: OutcomeUnknownCause::CompletionFailed,
                    route_reason: None,
                }),
                message: format!(
                    "unexpected module error during route.open: {} ({})",
                    body.code, body.message
                ),
                refusal: None,
            },
            CallError::SubscriptionBackpressure(err) => Self {
                kind: FailureKind::OutcomeUnknown(OutcomeUnknownSource {
                    message: err.to_string(),
                    cause: OutcomeUnknownCause::CompletionFailed,
                    route_reason: None,
                }),
                message: err.to_string(),
                refusal: None,
            },
            CallError::StaleRouteHandle(handle) => Self {
                kind: FailureKind::NotSent,
                message: format!("stale route handle: {handle:?}"),
                refusal: None,
            },
            error @ (CallError::CapabilityUnprovided { .. }
            | CallError::CapabilityAmbiguous { .. }
            | CallError::InvalidCapabilityIdentifier { .. }) => Self {
                kind: FailureKind::NotSent,
                message: error.to_string(),
                refusal: None,
            },
        }
    }
}

#[derive(Debug, Clone)]
enum FailureKind {
    NotSent,
    OutcomeUnknown(OutcomeUnknownSource),
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
struct PendingKey {
    generation: u64,
    channel: u16,
    epoch: u32,
    corr: u64,
}

struct PendingEntry {
    accepted: bool,
    retain_late_route_open: bool,
    expected_control_handle: Option<RouteHandle>,
    route_open_reverse_requests: Option<ReverseRequestRegistry>,
    route_open_module: Option<String>,
    completion: PendingCompletion,
}

enum PendingCompletion {
    Unary(oneshot::Sender<PendingResult>),
    Subscription {
        events: mpsc::Sender<Vec<u8>>,
        closed: oneshot::Sender<Result<(), CallError>>,
        ended: watch::Sender<Option<SubscriptionEnd>>,
        _permit: OwnedSemaphorePermit,
        priority: Priority,
    },
}

enum StreamDataDelivery {
    NotSubscription,
    Full,
    Closed,
}

impl PendingEntry {
    fn unary(
        tx: oneshot::Sender<PendingResult>,
        retain_late_route_open: bool,
        expected_control_handle: Option<RouteHandle>,
        route_open_reverse_requests: Option<ReverseRequestRegistry>,
    ) -> Self {
        Self {
            accepted: false,
            retain_late_route_open,
            expected_control_handle,
            route_open_reverse_requests,
            route_open_module: None,
            completion: PendingCompletion::Unary(tx),
        }
    }

    fn subscription(
        events: mpsc::Sender<Vec<u8>>,
        closed: oneshot::Sender<Result<(), CallError>>,
        ended: watch::Sender<Option<SubscriptionEnd>>,
        permit: OwnedSemaphorePermit,
        priority: Priority,
    ) -> Self {
        Self {
            accepted: false,
            retain_late_route_open: false,
            expected_control_handle: None,
            route_open_reverse_requests: None,
            route_open_module: None,
            completion: PendingCompletion::Subscription {
                events,
                closed,
                ended,
                _permit: permit,
                priority,
            },
        }
    }

    fn completion_is_closed(&self) -> bool {
        match &self.completion {
            PendingCompletion::Unary(tx) => tx.is_closed(),
            PendingCompletion::Subscription { closed, .. } => closed.is_closed(),
        }
    }

    fn is_subscription(&self) -> bool {
        matches!(&self.completion, PendingCompletion::Subscription { .. })
    }

    fn subscription_priority(&self) -> Option<Priority> {
        match &self.completion {
            PendingCompletion::Subscription { priority, .. } => Some(*priority),
            PendingCompletion::Unary(_) => None,
        }
    }

    fn try_send_stream_data(&self, body: Vec<u8>) -> Result<(), StreamDataDelivery> {
        let PendingCompletion::Subscription { events, .. } = &self.completion else {
            return Err(StreamDataDelivery::NotSubscription);
        };
        events.try_send(body).map_err(|err| match err {
            mpsc::error::TrySendError::Full(_) => StreamDataDelivery::Full,
            mpsc::error::TrySendError::Closed(_) => StreamDataDelivery::Closed,
        })
    }

    fn settle_terminal(self, terminal: PendingTerminal) {
        match self.completion {
            PendingCompletion::Unary(tx) => {
                let _ = tx.send(PendingResult::Terminal(terminal));
            }
            PendingCompletion::Subscription { closed, ended, .. } => {
                let (end, result) = match terminal {
                    PendingTerminal::Response { body, .. } => {
                        (SubscriptionEnd::Response(body), Ok(()))
                    }
                    PendingTerminal::StreamEnd => (SubscriptionEnd::StreamEnd, Ok(())),
                    PendingTerminal::Error { body, .. } => (
                        SubscriptionEnd::Error(body.clone()),
                        Err(CallError::Module(body)),
                    ),
                };
                let _ = ended.send(Some(end));
                let _ = closed.send(result);
            }
        }
    }

    fn settle_failure(self, reason: String) {
        let err = classify_failure(self.accepted, reason, OutcomeUnknownCause::ConsumerClosed);
        match self.completion {
            PendingCompletion::Unary(tx) => {
                let _ = tx.send(PendingResult::CallError(err));
            }
            PendingCompletion::Subscription { closed, ended, .. } => {
                let _ = ended.send(Some(SubscriptionEnd::RouteClosed {
                    reason: RouteEndReason::ClosedByCaller,
                }));
                let _ = closed.send(Err(err));
            }
        }
    }

    fn settle_call_error(self, err: CallError) {
        match self.completion {
            PendingCompletion::Unary(tx) => {
                let _ = tx.send(PendingResult::CallError(err));
            }
            PendingCompletion::Subscription { closed, ended, .. } => {
                let end = if let Some(reason) = err.close_reason() {
                    match reason {
                        RouteEndReason::ConnectionLost => SubscriptionEnd::ConnectionLost,
                        reason => SubscriptionEnd::RouteClosed {
                            reason: reason.clone(),
                        },
                    }
                } else if matches!(err, CallError::SubscriptionBackpressure(_)) {
                    SubscriptionEnd::Backpressure
                } else {
                    SubscriptionEnd::ConnectionLost
                };
                let _ = ended.send(Some(end));
                let _ = closed.send(Err(err));
            }
        }
    }

    fn settle_subscription_result(self, result: Result<(), CallError>) {
        match self.completion {
            PendingCompletion::Subscription { closed, ended, .. } => {
                let _ = ended.send(Some(SubscriptionEnd::Cancelled));
                let _ = closed.send(result);
            }
            PendingCompletion::Unary(tx) => {
                let _ = tx.send(PendingResult::Failure {
                    accepted: self.accepted,
                    reason: "subscription cancel matched a unary request".to_string(),
                });
            }
        }
    }
}

struct PendingRegistration {
    shared: Arc<Shared>,
    key: PendingKey,
    active: bool,
    retain_on_drop: bool,
}

impl PendingRegistration {
    fn new(shared: Arc<Shared>, key: PendingKey, retain_on_drop: bool) -> Self {
        Self {
            shared,
            key,
            active: true,
            retain_on_drop,
        }
    }

    fn remove_pending(&mut self) -> Option<bool> {
        if !self.active {
            return None;
        }
        self.active = false;
        self.shared
            .lock_inner()
            .remove_pending(&self.key)
            .map(|entry| entry.accepted)
    }

    fn disarm(&mut self) {
        self.active = false;
    }
}

impl Drop for PendingRegistration {
    fn drop(&mut self) {
        if self.retain_on_drop {
            self.disarm();
        } else {
            let _ = self.remove_pending();
        }
    }
}

enum PendingResult {
    Terminal(PendingTerminal),
    CallError(CallError),
    Failure { accepted: bool, reason: String },
}

impl PendingResult {
    fn into_call_result(self) -> Result<TerminalFrame, CallError> {
        match self {
            Self::Terminal(terminal) => Ok(terminal.into_terminal_frame()),
            Self::CallError(err) => Err(err),
            Self::Failure { accepted, reason } => Err(classify_failure(
                accepted,
                reason,
                OutcomeUnknownCause::CompletionFailed,
            )),
        }
    }
}

enum PendingTerminal {
    Response {
        generation: u64,
        body: Vec<u8>,
        flags: Flags,
    },
    Error {
        body: ErrorBody,
        flags: Flags,
    },
    StreamEnd,
}

impl PendingTerminal {
    fn into_terminal_frame(self) -> TerminalFrame {
        match self {
            Self::Response {
                generation,
                body,
                flags,
            } => TerminalFrame::Response {
                generation,
                body,
                flags,
            },
            Self::Error { body, flags } => TerminalFrame::Error { body, flags },
            Self::StreamEnd => TerminalFrame::StreamEnd,
        }
    }
}

#[derive(Debug)]
enum TerminalFrame {
    Response {
        generation: u64,
        body: Vec<u8>,
        flags: Flags,
    },
    Error {
        body: ErrorBody,
        flags: Flags,
    },
    StreamEnd,
}

struct WriteCommand {
    frame: Frame,
    pending: Option<PendingKey>,
}

struct OpenedConnection {
    stream: TcpStream,
}

async fn open_connection(
    path: &Path,
    deadline: Duration,
) -> Result<OpenedConnection, ConsumerError> {
    let conn =
        connection_file::read_for_client(path).map_err(|source| ConsumerError::ConnectionFile {
            path: path.to_path_buf(),
            source,
        })?;
    open_connection_with_info(path, &conn, deadline).await
}

async fn open_connection_with_info(
    path: &Path,
    conn: &connection_file::ConnectionInfo,
    deadline: Duration,
) -> Result<OpenedConnection, ConsumerError> {
    let endpoint = conn
        .endpoints
        .first()
        .ok_or_else(|| ConsumerError::NoEndpoint {
            path: path.to_path_buf(),
        })?;
    let endpoint_label = format!("{}:{}", endpoint.host, endpoint.port);
    let mut stream = TcpStream::connect(&endpoint_label)
        .await
        .map_err(|source| ConsumerError::Connect {
            path: path.to_path_buf(),
            endpoint: endpoint_label.clone(),
            source,
        })?;
    // Consumers send a request and wait for its reply, so there is no following
    // write for Nagle to coalesce with -- it can only hold the request back until
    // an ACK returns. Both ends of the hop must disable it for either to help.
    //
    // Dropped rather than logged for the same reason as the module path: no logging
    // dependency here, and a socket too broken to take the option fails the
    // handshake on the next line with a typed error.
    let _ = stream.set_nodelay(true);
    authenticate_client(&mut stream, conn, deadline)
        .await
        .map_err(|source| ConsumerError::Auth {
            path: path.to_path_buf(),
            endpoint: endpoint_label,
            source,
        })?;
    Ok(OpenedConnection { stream })
}

fn dispatch_reverse_request(shared: &Arc<Shared>, frame: Frame, handle: RouteHandle) {
    let method = serde_json::from_slice::<serde_json::Value>(&frame.body)
        .ok()
        .and_then(|body| body.get("method")?.as_str().map(str::to_string));
    let method_family = method
        .as_deref()
        .and_then(|method| method.split('/').next())
        .filter(|family| !family.is_empty())
        .map(str::to_string);
    let handler = method_family.as_deref().and_then(|family| {
        route_reverse_request_registry(handle.reverse_request_registry_id())
            .ok()?
            .handler(family)
    });
    let generation = handle.connection_token();
    let shared = Arc::clone(shared);

    tokio::spawn(async move {
        let (frame_type, body) = if let (Some(handler), Some(method)) = (handler, method) {
            let request_body = frame.body.clone();
            let corr = frame.header.corr;
            match tokio::spawn(async move {
                handler(request_body, ReverseRequestContext { corr, method }).await
            })
            .await
            {
                Ok(Ok(body)) => (FrameType::Response, body),
                Ok(Err(err)) => (
                    FrameType::Error,
                    serde_json::to_vec(&ErrorBody::new(REVERSE_REQUEST_UNHANDLED, err.to_string()))
                        .unwrap_or_default(),
                ),
                Err(err) => (
                    FrameType::Error,
                    serde_json::to_vec(&ErrorBody::new(
                        REVERSE_REQUEST_UNHANDLED,
                        join_error_message(err),
                    ))
                    .unwrap_or_default(),
                ),
            }
        } else {
            let message = method_family.map_or_else(
                || "reverse request has no valid method".to_string(),
                |family| format!("no reverse-request handler is registered for {family}"),
            );
            (
                FrameType::Error,
                serde_json::to_vec(&ErrorBody::new(REVERSE_REQUEST_UNHANDLED, message))
                    .unwrap_or_default(),
            )
        };

        if shared.ingress_handle(generation, handle.channel, handle.epoch) != Some(handle) {
            return;
        }
        let reply = match Frame::build_with_version(
            frame.header.ver,
            frame_type,
            Flags::new(false, Priority::Interactive, false),
            handle.channel,
            handle.epoch,
            frame.header.corr,
            body,
        ) {
            Ok(reply) => reply,
            Err(_) => return,
        };
        let writer = shared.lock_inner().writer.clone();
        if let Some(writer) = writer {
            let _ = writer
                .send(WriteCommand {
                    frame: reply,
                    pending: None,
                })
                .await;
        }
    });
}

fn join_error_message(error: tokio::task::JoinError) -> String {
    if !error.is_panic() {
        return error.to_string();
    }
    let payload = error.into_panic();
    if let Some(message) = payload.downcast_ref::<String>() {
        return message.clone();
    }
    if let Some(message) = payload.downcast_ref::<&str>() {
        return (*message).to_string();
    }
    "reverse-request handler panicked".to_string()
}

async fn reader_loop(shared: Arc<Shared>, mut reader: OwnedReadHalf, generation: u64) {
    loop {
        match read_frame(&mut reader).await {
            Ok(Some(frame)) => {
                if !dispatch_frame(&shared, generation, frame).await {
                    return;
                }
            }
            Ok(None) => {
                shared.handle_generation_drop(generation, "subc connection closed".to_string());
                return;
            }
            Err(err) => {
                shared.handle_generation_drop(generation, err.to_string());
                return;
            }
        }
    }
}

async fn dispatch_frame(shared: &Arc<Shared>, generation: u64, frame: Frame) -> bool {
    if !shared.record_inbound_if_current(generation) {
        return false;
    }
    if frame.header.channel != 0
        && !shared.validate_ingress_handle(generation, frame.header.channel, frame.header.epoch)
    {
        return true;
    }

    if frame.header.ty == FrameType::Request && frame.header.channel != 0 {
        if let Some(handle) =
            shared.ingress_handle(generation, frame.header.channel, frame.header.epoch)
        {
            dispatch_reverse_request(shared, frame, handle);
        }
        return true;
    }

    let key = PendingKey {
        generation,
        channel: frame.header.channel,
        epoch: frame.header.epoch,
        corr: frame.header.corr,
    };

    if frame.header.channel == 0 && frame.header.ty == FrameType::Response {
        if let Some(expected) = shared.pending_expected_control_handle(key) {
            let echoes_expected = matches!(
                serde_json::from_slice::<ClientControlResponse>(&frame.body),
                Ok(ClientControlResponse::RoutePoll {
                    route_channel,
                    route_epoch,
                    ..
                }) if route_channel == expected.channel && route_epoch == expected.epoch
            );
            if !echoes_expected {
                shared.count_dropped_route_frame();
                return true;
            }
        }
    }

    // A route.open handle is published before its waiter is resolved. The socket reader
    // cannot consume a following same-route frame until this synchronous install finishes.
    if frame.header.channel == 0
        && frame.header.ty == FrameType::Response
        && shared.pending_expects_route_open(key)
    {
        if let Ok(ClientControlResponse::RouteOpen {
            route_channel,
            route_epoch,
        }) = serde_json::from_slice::<ClientControlResponse>(&frame.body)
        {
            let reverse_requests = shared
                .pending_route_open_reverse_requests(key)
                .unwrap_or_default();
            let module = shared
                .lock_inner()
                .pending
                .get(&key)
                .and_then(|entry| entry.route_open_module.clone());
            shared.install_ingress_handle(RouteHandle::new_consumer(
                route_channel,
                route_epoch,
                generation,
                reverse_requests,
            ));
            if let Some(module) = module {
                shared
                    .lock_inner()
                    .route_modules
                    .insert(route_channel, module);
            }
        }
    }

    match frame.header.ty {
        FrameType::Response => shared.settle_pending(
            key,
            PendingTerminal::Response {
                generation,
                body: frame.body,
                flags: frame.header.flags,
            },
        ),
        FrameType::Error => {
            let body =
                serde_json::from_slice::<ErrorBody>(&frame.body).unwrap_or_else(|err| ErrorBody {
                    code: "invalid_error_body".to_string(),
                    message: err.to_string(),
                    detail: None,
                });
            shared.settle_pending(
                key,
                PendingTerminal::Error {
                    body,
                    flags: frame.header.flags,
                },
            );
        }
        FrameType::StreamEnd => shared.settle_pending(key, PendingTerminal::StreamEnd),
        FrameType::StreamData => shared.route_stream_data(key, frame.body),
        FrameType::Push if frame.header.channel == 0 => {
            shared.control_push(&frame.body);
        }
        FrameType::Push => shared.route_push(
            RouteHandle::new(frame.header.channel, frame.header.epoch, generation),
            frame.body,
        ),
        FrameType::Goodbye if frame.header.channel == 0 => {
            shared.handle_generation_drop(generation, "subc sent GOODBYE".to_string());
            return false;
        }
        FrameType::Goodbye => {
            let handle = RouteHandle::new(frame.header.channel, frame.header.epoch, generation);
            let close_reason = shared.lock_inner().route_end_reason(handle.channel);
            shared.invalidate_routes_for_handle(handle);
            let pending = {
                let mut inner = shared.lock_inner();
                drain_pending_handle(&mut inner.pending, handle, true)
            };
            settle_route_pending_entries(pending, "route closed by subc".to_string(), close_reason);
        }
        FrameType::Ping if frame.header.channel == 0 => {
            if let Ok(pong) = Frame::build_with_version(
                frame.header.ver,
                FrameType::Pong,
                frame.header.flags,
                0,
                0,
                frame.header.corr,
                Vec::new(),
            ) {
                let writer = shared.lock_inner().writer.clone();
                if let Some(writer) = writer {
                    let _ = writer
                        .send(WriteCommand {
                            frame: pong,
                            pending: None,
                        })
                        .await;
                }
            }
        }
        _ => {}
    }
    true
}

impl Shared {
    /// Stamp after holding the same state lock that guards generation changes, so a
    /// late frame from an older reader can never vouch for a newly installed socket.
    ///
    /// PLACEMENT IS LOAD-BEARING: the single caller sits on the frame-read
    /// return, the one point every inbound frame passes before demux -- which
    /// is why one stamp suffices. A future fast path or drain-and-dispatch
    /// refactor that hands frames onward without crossing that point makes the
    /// stamp skippable, and the liveness watermark quietly stops meaning "the
    /// link delivered bytes": the cheapest correctness property in this file
    /// and the easiest to lose in a refactor.
    fn record_inbound_if_current(&self, generation: u64) -> bool {
        let inner = self.lock_inner();
        if inner.closed || inner.generation != generation || inner.writer.is_none() {
            return false;
        }
        self.last_inbound_ms
            .store(epoch_millis(), Ordering::Release);
        true
    }

    fn generation_is_current(&self, generation: u64) -> bool {
        let inner = self.lock_inner();
        !inner.closed && inner.generation == generation && inner.writer.is_some()
    }

    fn pending_expected_control_handle(&self, key: PendingKey) -> Option<RouteHandle> {
        self.lock_inner()
            .pending
            .get(&key)
            .and_then(|entry| entry.expected_control_handle)
    }

    fn count_dropped_route_frame(&self) {
        let mut inner = self.lock_inner();
        inner.dropped_route_frames = inner.dropped_route_frames.saturating_add(1);
    }

    fn pending_expects_route_open(&self, key: PendingKey) -> bool {
        self.lock_inner()
            .pending
            .get(&key)
            .is_some_and(|entry| entry.retain_late_route_open)
    }

    fn pending_route_open_reverse_requests(
        &self,
        key: PendingKey,
    ) -> Option<ReverseRequestRegistry> {
        self.lock_inner()
            .pending
            .get(&key)
            .and_then(|entry| entry.route_open_reverse_requests.clone())
    }

    fn ingress_handle(&self, generation: u64, channel: u16, epoch: u32) -> Option<RouteHandle> {
        let inner = self.lock_inner();
        let handle = inner.route_epochs.get(&channel).copied()?;
        (handle.connection_token() == generation && handle.epoch == epoch).then_some(handle)
    }

    fn validate_ingress_handle(&self, generation: u64, channel: u16, epoch: u32) -> bool {
        let mut inner = self.lock_inner();
        let expected = RouteHandle::new(channel, epoch, generation);
        if inner.route_epochs.get(&channel) == Some(&expected) {
            true
        } else {
            inner.dropped_route_frames = inner.dropped_route_frames.saturating_add(1);
            false
        }
    }

    fn install_ingress_handle(&self, handle: RouteHandle) {
        let mut inner = self.lock_inner();
        if !inner.closed && inner.generation == handle.connection_token() && inner.writer.is_some()
        {
            inner.route_end_reasons.remove(&handle.channel);
            inner.legacy_channel_reasons.remove(&handle.channel);
            inner.route_modules.remove(&handle.channel);
            if let Some(previous) = inner.route_epochs.insert(handle.channel, handle) {
                if previous.reverse_request_registry_id() != handle.reverse_request_registry_id() {
                    release_reverse_request_registry(previous);
                }
            }
        }
    }

    fn invalidate_routes_for_handle(&self, handle: RouteHandle) {
        let removed = {
            let mut inner = self.lock_inner();
            if inner.route_epochs.get(&handle.channel) != Some(&handle) {
                return;
            }
            let installed = inner.route_epochs.remove(&handle.channel).unwrap();
            inner.retired_routes.remove(&handle);
            inner.push_event_receivers.remove(&handle);
            release_reverse_request_registry(installed);
            inner
                .remove_route_by_handle(handle)
                .into_iter()
                .collect::<Vec<_>>()
        };
        for route in removed {
            route.sem.close();
        }
    }
}

async fn writer_loop<W>(
    shared: Arc<Shared>,
    writer: W,
    mut rx: mpsc::Receiver<WriteCommand>,
    generation: u64,
) where
    W: AsyncWrite + Unpin,
{
    let mut writer = BufWriter::new(writer);
    while let Some(command) = rx.recv().await {
        if let Some(key) = command.pending {
            if !shared.mark_pending_accepted(key) {
                continue;
            }
        }
        if let Err(err) = write_frame(&mut writer, &command.frame).await {
            shared.handle_generation_drop_with_cause(
                generation,
                err.to_string(),
                OutcomeUnknownCause::WriterClosed,
            );
            return;
        }
        while let Ok(command) = rx.try_recv() {
            if let Some(key) = command.pending {
                if !shared.mark_pending_accepted(key) {
                    continue;
                }
            }
            if let Err(err) = write_frame(&mut writer, &command.frame).await {
                shared.handle_generation_drop_with_cause(
                    generation,
                    err.to_string(),
                    OutcomeUnknownCause::WriterClosed,
                );
                return;
            }
        }
        if let Err(err) = writer.flush().await.map_err(FrameIoError::Io) {
            shared.handle_generation_drop_with_cause(
                generation,
                err.to_string(),
                OutcomeUnknownCause::WriterClosed,
            );
            return;
        }
    }
}

fn activity_read_body(request: impl serde::Serialize) -> Result<Vec<u8>, CallError> {
    #[derive(serde::Serialize)]
    struct ReadRequest<T> {
        #[serde(flatten)]
        request: T,
        #[serde(skip_serializing_if = "Option::is_none")]
        consumer_identity: Option<ConsumerIdentity>,
    }
    serde_json::to_vec(&ReadRequest {
        request,
        consumer_identity: consumer_identity_from_env(),
    })
    .map_err(|err| CallError::not_sent(format!("failed to encode activity read: {err}")))
}

fn route_open_consumer_identity(opts: &CallOptions) -> Option<ConsumerIdentity> {
    opts.consumer_identity
        .clone()
        .or_else(consumer_identity_from_env)
}

fn close_route_consumer_identity(opts: &CloseRouteOptions) -> Option<ConsumerIdentity> {
    opts.consumer_identity
        .clone()
        .or_else(consumer_identity_from_env)
}

fn route_open_consumer_capabilities(opts: &CallOptions) -> Option<Vec<String>> {
    opts.reverse_requests.seal();
    let mut capabilities = opts.reverse_requests.capabilities();
    capabilities.extend(opts.consumer_capabilities());
    capabilities.sort();
    capabilities.dedup();
    (!capabilities.is_empty()).then_some(capabilities)
}

/// The role versions a route is opened and keyed with. An empty map declares
/// nothing, and the daemon forwards it as no field at all, so it is folded
/// into `None` here: otherwise `Some({})` and `None` would key two routes the
/// provider cannot tell apart.
fn route_open_role_versions(
    role_versions: Option<&BTreeMap<String, String>>,
) -> Option<BTreeMap<String, String>> {
    role_versions
        .filter(|role_versions| !role_versions.is_empty())
        .cloned()
}

fn close_route_consumer_capabilities(opts: &CloseRouteOptions) -> Option<Vec<String>> {
    opts.reverse_requests.seal();
    let mut capabilities = opts.reverse_requests.capabilities();
    capabilities.extend(opts.consumer_capabilities());
    capabilities.sort();
    capabilities.dedup();
    (!capabilities.is_empty()).then_some(capabilities)
}

fn consumer_identity_from_env() -> Option<ConsumerIdentity> {
    let module_id = std::env::var(SUBC_MODULE_ID_ENV)
        .ok()
        .filter(|value| !value.is_empty())?;
    // Through the process's one cached accessor, never a second read of the
    // descriptor. An accessor error (for example a process a module spawned,
    // which inherits the descriptor variable but not the pipe) opens the
    // route without identity: it never falls back to the environment copy,
    // because presenting the module's nonce is exactly what such a process
    // must no longer be able to do.
    let launch_nonce = crate::launch_nonce()
        .ok()
        .flatten()
        .map(|nonce| nonce.value().to_string())?;
    Some(ConsumerIdentity {
        module_id,
        launch_nonce,
    })
}

fn validate_capability_for_resolution(capability: &str) -> Result<(), CallError> {
    if is_valid_capability_identifier(capability) {
        Ok(())
    } else {
        Err(CallError::InvalidCapabilityIdentifier {
            capability: capability.to_string(),
        })
    }
}

fn capability_claimants(catalog: &CatalogList, capability: &str) -> Vec<String> {
    let mut claimants = catalog
        .modules
        .iter()
        .filter(|module| {
            module.capabilities.as_ref().is_some_and(|capabilities| {
                capabilities
                    .provides
                    .iter()
                    .any(|claim| claim == capability)
            })
        })
        .map(|module| module.module_id.clone())
        .collect::<Vec<_>>();
    claimants.sort();
    claimants
}

fn epoch_millis() -> u64 {
    u64::try_from(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis(),
    )
    .unwrap_or(u64::MAX)
}

/// Reclassify a route-open failure seen by a managed `call` or `subscribe`.
///
/// `ensure_route` reports the route.open control request's own outcome, which
/// is `OutcomeUnknown` when that request was written but its reply did not
/// arrive before the deadline: the daemon may or may not have opened the
/// channel. The caller's request body, however, is only written after a route
/// is in hand, so when no route came back the body provably never left the
/// client. From the caller's point of view that is `NotSent`, and reporting
/// `OutcomeUnknown` would wrongly tell it a non-idempotent operation might
/// have run. A route.open reply that arrives after its waiter gave up is still
/// cleaned up: `settle_pending` sends that channel a GOODBYE instead of caching
/// it, so reporting `NotSent` here leaves no route open behind.
/// A uniform value in [0, 1) for retry jitter. Jitter needs spread, not
/// unpredictability, so this hashes a counter with std's randomly keyed hasher
/// instead of taking a dependency on a random-number crate.
fn default_random_unit() -> f64 {
    use std::hash::{BuildHasher, RandomState};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let bits = RandomState::new().hash_one(COUNTER.fetch_add(1, Ordering::Relaxed));
    // The top 53 bits fill an f64 mantissa exactly.
    (bits >> 11) as f64 / (1u64 << 53) as f64
}

fn request_not_sent_after_route_open_failure(err: CallError) -> CallError {
    match err {
        CallError::OutcomeUnknown(source) => CallError::not_sent(format!(
            "request not sent: route.open did not complete ({source})"
        )),
        other => other,
    }
}

fn classify_failure(
    accepted: bool,
    reason: impl Into<String>,
    cause: OutcomeUnknownCause,
) -> CallError {
    if accepted {
        CallError::outcome_unknown(reason, cause)
    } else {
        CallError::not_sent(reason)
    }
}

fn settle_route_pending_entries(
    entries: Vec<PendingEntry>,
    message: String,
    reason: RouteEndReason,
) {
    let cause = if reason == RouteEndReason::ConnectionLost {
        OutcomeUnknownCause::ConnectionFailed
    } else {
        OutcomeUnknownCause::RouteEnded
    };
    settle_route_pending_entries_with_cause(entries, message, reason, cause);
}

fn settle_route_pending_entries_with_cause(
    entries: Vec<PendingEntry>,
    message: String,
    reason: RouteEndReason,
    cause: OutcomeUnknownCause,
) {
    for entry in entries {
        let source = Box::new(RouteEnded {
            message: message.clone(),
            reason: reason.clone(),
        });
        let err = if entry.accepted {
            CallError::outcome_unknown_source(OutcomeUnknownSource {
                message: source.message.clone(),
                cause,
                route_reason: Some(reason.clone()),
            })
        } else {
            CallError::NotSent(source)
        };
        entry.settle_call_error(err);
    }
}

fn settle_pending_entries(entries: Vec<PendingEntry>, reason: String) {
    for entry in entries {
        entry.settle_failure(reason.clone());
    }
}

fn drain_pending_generation(
    pending: &mut HashMap<PendingKey, PendingEntry>,
    generation: u64,
) -> Vec<PendingEntry> {
    let keys = pending
        .keys()
        .copied()
        .filter(|key| key.generation == generation)
        .collect::<Vec<_>>();
    keys.into_iter()
        .filter_map(|key| pending.remove(&key))
        .collect()
}

fn drain_pending_handle(
    pending: &mut HashMap<PendingKey, PendingEntry>,
    handle: RouteHandle,
    include_subscriptions: bool,
) -> Vec<PendingEntry> {
    let keys = pending
        .iter()
        .filter_map(|(key, entry)| {
            (key.generation == handle.connection_token()
                && key.channel == handle.channel
                && key.epoch == handle.epoch
                && (include_subscriptions || !entry.is_subscription()))
            .then_some(*key)
        })
        .collect::<Vec<_>>();
    keys.into_iter()
        .filter_map(|key| pending.remove(&key))
        .collect()
}

fn fail_openings(openings: Vec<Vec<OpeningWaiter>>, failure: SharedCallFailure) {
    for waiters in openings {
        for waiter in waiters {
            let _ = waiter.send(Err(failure.clone()));
        }
    }
}

fn emit_callbacks(callbacks: Vec<Callback>, state: ConnectionState) {
    for callback in callbacks {
        if let Ok(callback) = callback.lock() {
            callback(state.clone());
        }
    }
}

/// The route-open retry predicate, defined once in `subc_protocol::error_codes`
/// so consumers with their own connection layer share it rather than copy it.
pub fn is_retryable_route_open_code(code: &str) -> bool {
    error_codes::is_retryable_route_open(code)
}

/// Whether a data-plane ERROR answering a managed call's request is the
/// daemon's drain refusal, `module_reloading`, which the call may resend once
/// after reopening the route.
///
/// On an established route the daemon answers `module_reloading` only when the
/// module's endpoint is draining and the request could not take a route
/// credit, and it answers BEFORE forwarding (`ForwardBackend::handle_bound` in
/// subc-daemon's `router.rs`), so the module never received the request and a
/// resend cannot run it twice. The protocol documents that guarantee on
/// `error_codes::MODULE_RELOADING`.
///
/// Kept apart from `error_codes::is_established_route_dead` on purpose. That
/// shared predicate decides route DEATH, and other consumers map it to their
/// own custody, provider or suspect verdicts; adding a drain code there would
/// change those verdicts on a protocol bump. Here the code only earns the same
/// remedy (evict, reopen, resend once) inside this client's unary call path.
fn is_data_plane_drain_refusal(code: &str) -> bool {
    code == error_codes::MODULE_RELOADING
}

/// Whether `handle` names a route installed on the current connection. Channel 0 is the
/// connection's own control channel: it is never installed as a route and is current for
/// as long as the connection is, so a held channel-0 request (the spawn stream) can be
/// cancelled like a route subscription.
fn route_is_installed(inner: &Inner, handle: RouteHandle) -> bool {
    handle.channel == 0 || inner.route_epochs.get(&handle.channel) == Some(&handle)
}

fn is_retryable_catalog_transport_error(err: &CallError) -> bool {
    matches!(err, CallError::NotSent(_) | CallError::OutcomeUnknown(_))
}

fn is_reconnect_transient(err: &ConsumerError) -> bool {
    match err {
        ConsumerError::Connect { source, .. } => matches!(
            source.kind(),
            io::ErrorKind::ConnectionRefused
                | io::ErrorKind::ConnectionReset
                | io::ErrorKind::ConnectionAborted
                | io::ErrorKind::TimedOut
                | io::ErrorKind::NotConnected
                | io::ErrorKind::AddrNotAvailable
        ),
        ConsumerError::ConnectionFile { source, .. } => match source {
            ConnectionFileError::Io { source, .. } => source.kind() == io::ErrorKind::NotFound,
            _ => false,
        },
        // Auth failure is transient during reconnect: the daemon rotates its key
        // on every restart, and with a fixed port a client racing the restart can
        // read the pre-rotation connection file yet still connect — the proof
        // mismatch then means "stale key mid-rotation", not "impostor". Each
        // retry re-reads the connection file (open_connection), so the next
        // attempt picks up the rotated key, and server-proves-first protects
        // every attempt. First-connect auth failures stay permanent: connect()
        // surfaces them directly without entering the reconnect classifier.
        ConsumerError::Auth { .. } => true,
        ConsumerError::Discovery { .. }
        | ConsumerError::NoEndpoint { .. }
        | ConsumerError::Closed => false,
    }
}

impl From<FrameBuildError> for CallError {
    fn from(err: FrameBuildError) -> Self {
        Self::not_sent(err.to_string())
    }
}

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

    #[derive(Clone)]
    struct InstrumentedWriter {
        state: Arc<InstrumentedWriterState>,
        fail_flush: bool,
    }

    #[derive(Default)]
    struct InstrumentedWriterState {
        bytes: Mutex<Vec<u8>>,
        flushes: std::sync::atomic::AtomicUsize,
    }

    impl InstrumentedWriter {
        fn new(fail_flush: bool) -> Self {
            Self {
                state: Arc::new(InstrumentedWriterState::default()),
                fail_flush,
            }
        }

        fn bytes(&self) -> Vec<u8> {
            self.state
                .bytes
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .clone()
        }

        fn flush_count(&self) -> usize {
            self.state.flushes.load(Ordering::SeqCst)
        }
    }

    impl AsyncWrite for InstrumentedWriter {
        fn poll_write(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<io::Result<usize>> {
            self.state
                .bytes
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .extend_from_slice(buf);
            Poll::Ready(Ok(buf.len()))
        }

        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            self.state.flushes.fetch_add(1, Ordering::SeqCst);
            if self.fail_flush {
                Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::BrokenPipe,
                    "instrumented flush failure",
                )))
            } else {
                Poll::Ready(Ok(()))
            }
        }

        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
            Poll::Ready(Ok(()))
        }
    }

    fn writer_test_shared() -> Arc<Shared> {
        Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions {
                reconnect_backoff: RetryBackoff {
                    max_attempts: 1,
                    ..RetryBackoff::default()
                },
                ..ConsumerOptions::default()
            },
        ))
    }

    fn reverse_test_shared(
        reverse_requests: ReverseRequestRegistry,
    ) -> (Arc<Shared>, mpsc::Receiver<WriteCommand>, RouteHandle) {
        let shared = writer_test_shared();
        let (writer, receiver) = mpsc::channel(16);
        let handle = RouteHandle::new_consumer(17, 3, 1, reverse_requests);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.route_epochs.insert(handle.channel, handle);
        }
        (shared, receiver, handle)
    }

    fn reverse_request_frame(handle: RouteHandle, corr: u64, body: Vec<u8>) -> Frame {
        Frame::build(
            FrameType::Request,
            Flags::new(false, Priority::Interactive, false),
            handle.channel,
            handle.epoch,
            corr,
            body,
        )
        .unwrap()
    }

    #[tokio::test]
    async fn binary_reply_request_preserves_flagged_non_utf8_bytes() {
        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        shared
            .install_one_shot_route(RouteState {
                handle,
                sem: Arc::new(Semaphore::new(1)),
            })
            .unwrap();
        let request = tokio::spawn(async move {
            consumer
                .request(&handle, b"bytes".to_vec(), CallOptions::default())
                .await
        });
        let command = receiver.recv().await.unwrap();
        let bytes = vec![0, 0xff, 0x80, b'{'];
        let frame = Frame::build(
            FrameType::Response,
            Flags::new(true, Priority::Interactive, false),
            handle.channel,
            handle.epoch,
            command.frame.header.corr,
            bytes.clone(),
        )
        .unwrap();
        assert!(dispatch_frame(&shared, 1, frame).await);
        assert_eq!(request.await.unwrap().unwrap(), bytes);
    }

    async fn capture_route_open(
        reverse_requests: ReverseRequestRegistry,
    ) -> (serde_json::Value, RouteHandle) {
        capture_route_open_with_options(CallOptions {
            reverse_requests,
            ..CallOptions::default()
        })
        .await
    }

    async fn capture_route_open_with_options(
        opts: CallOptions,
    ) -> (serde_json::Value, RouteHandle) {
        let shared = writer_test_shared();
        let (writer, mut receiver) = mpsc::channel(4);
        shared.lock_inner().writer = Some(writer);
        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let task = tokio::spawn(async move {
            consumer
                .open_route(
                    RouteTarget::ToolProvider {
                        module_id: "reverse-provider".to_string(),
                    },
                    BindIdentity::new(
                        PathBuf::from("/tmp/project"),
                        "test".to_string(),
                        "reverse".to_string(),
                    ),
                    opts,
                )
                .await
        });
        let command = receiver.recv().await.expect("route.open frame");
        let request = serde_json::from_slice(&command.frame.body).unwrap();
        let response_body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
            route_channel: 17,
            route_epoch: 3,
        })
        .unwrap();
        assert!(
            dispatch_frame(
                &shared,
                1,
                response_frame(0, 0, command.frame.header.corr, response_body),
            )
            .await
        );
        let handle = task.await.unwrap().unwrap();
        (request, handle)
    }

    /// Keep held subscriptions marked for drain accounting without marking ordinary requests.
    #[tokio::test]
    async fn held_subscriptions_set_the_flag_but_ordinary_requests_do_not() {
        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
        let call_shared = Arc::clone(&shared);
        let call = tokio::spawn(async move {
            call_shared
                .send_request(RequestSend {
                    binary: false,
                    expected_handle: Some(handle),
                    channel: handle.channel,
                    epoch: handle.epoch,
                    body: b"ordinary".to_vec(),
                    priority: Priority::Interactive,
                    admission_class: AdmissionClass::Normal,
                    deadline: Instant::now() + Duration::from_secs(1),
                    retain_late_route_open: false,
                    route_open_reverse_requests: None,
                })
                .await
        });
        let ordinary = receiver.recv().await.unwrap();
        assert_eq!(ordinary.frame.header.encode()[6] & FLAG_SUBSCRIPTION, 0);
        assert!(
            dispatch_frame(
                &shared,
                1,
                response_frame(
                    handle.channel,
                    handle.epoch,
                    ordinary.frame.header.corr,
                    Vec::new()
                ),
            )
            .await
        );
        assert!(call.await.unwrap().is_ok());

        let permit = Arc::new(Semaphore::new(1)).acquire_owned().await.unwrap();
        let subscription = Arc::clone(&shared)
            .send_subscription(SubscriptionSend {
                expected_handle: Some(handle),
                channel: handle.channel,
                epoch: handle.epoch,
                body: b"held".to_vec(),
                priority: Priority::Interactive,
                admission_class: AdmissionClass::Normal,
                event_buffer: 1,
                deadline: Instant::now() + Duration::from_secs(1),
                permit,
            })
            .await
            .unwrap();
        let held = receiver.recv().await.unwrap();
        assert_ne!(
            held.frame.header.encode()[6] & FLAG_SUBSCRIPTION,
            0,
            "a held-open subscription must be marked for drain accounting"
        );
        drop(subscription);
        release_reverse_request_registry(handle);
    }

    #[tokio::test]
    async fn registered_handlers_derive_route_open_consumer_capabilities() {
        let registry = ReverseRequestRegistry::new();
        registry
            .on_request("elicitation", |_body, _ctx| async { Vec::new() })
            .unwrap();
        let (request, handle) = capture_route_open(registry).await;
        assert_eq!(
            request.get("consumer_capabilities"),
            Some(&serde_json::json!(["elicitation"]))
        );
        release_reverse_request_registry(handle);
    }

    #[tokio::test]
    async fn declared_consumer_capabilities_merge_with_handler_families_on_route_open() {
        let registry = ReverseRequestRegistry::new();
        registry
            .on_request("elicitation", |_body, _ctx| async { Vec::new() })
            .unwrap();
        let opts = CallOptions {
            reverse_requests: registry,
            ..CallOptions::default()
        }
        .with_consumer_capability("tool-result/v1")
        .unwrap()
        .with_consumer_capability("elicitation")
        .unwrap()
        .with_consumer_capability("tool-result/v1")
        .unwrap();

        let (request, handle) = capture_route_open_with_options(opts).await;
        assert_eq!(
            request.get("consumer_capabilities"),
            Some(&serde_json::json!(["elicitation", "tool-result/v1"]))
        );
        release_reverse_request_registry(handle);
    }

    #[test]
    fn invalid_consumer_capability_declarations_are_rejected_before_route_open() {
        let (shared, mut receiver) = {
            let shared = writer_test_shared();
            let (writer, receiver) = mpsc::channel(4);
            shared.lock_inner().writer = Some(writer);
            (shared, receiver)
        };
        let too_long = "x".repeat(65);
        for invalid in [
            String::new(),
            "content v1".to_string(),
            "content\tv1".to_string(),
            "content\nv1".to_string(),
            "cöntent/v1".to_string(),
            "content/\u{7f}v1".to_string(),
            too_long,
        ] {
            let error = CallOptions::default()
                .with_consumer_capability(invalid.clone())
                .expect_err("invalid declarations must not produce route options");
            assert_eq!(error.capability(), invalid);
            assert!(
                receiver.try_recv().is_err(),
                "invalid declaration {invalid:?} must be rejected before any frame is queued"
            );
        }
        let close_error = CloseRouteOptions::default()
            .with_consumer_capability("bad value")
            .expect_err("close-route declarations use the same validation");
        assert_eq!(close_error.capability(), "bad value");
        let call_options = CallOptions::default()
            .with_consumer_capability("tool-result/v1")
            .unwrap();
        assert_eq!(
            call_options.consumer_capabilities(),
            vec!["tool-result/v1".to_string()]
        );
        let close_options = CloseRouteOptions::default()
            .with_consumer_capability("tool-result/v1")
            .unwrap();
        assert_eq!(
            close_options.consumer_capabilities(),
            vec!["tool-result/v1".to_string()]
        );
        shared.close_sync("test complete");
    }

    #[tokio::test]
    async fn no_handlers_omit_consumer_capabilities_from_route_open() {
        let (request, handle) = capture_route_open(ReverseRequestRegistry::new()).await;
        assert!(!request
            .as_object()
            .unwrap()
            .contains_key("consumer_capabilities"));
        release_reverse_request_registry(handle);
    }

    #[tokio::test]
    async fn reverse_request_without_handler_returns_typed_error_instead_of_silence() {
        let (shared, mut receiver, handle) = reverse_test_shared(ReverseRequestRegistry::new());
        let body = serde_json::to_vec(&serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "elicitation/create",
            "params": {}
        }))
        .unwrap();
        assert!(dispatch_frame(&shared, 1, reverse_request_frame(handle, 800, body)).await);
        let reply = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
            .await
            .unwrap()
            .unwrap()
            .frame;
        assert_eq!(reply.header.ty, FrameType::Error);
        assert_eq!(reply.header.corr, 800);
        let error: ErrorBody = serde_json::from_slice(&reply.body).unwrap();
        assert_eq!(error.code, REVERSE_REQUEST_UNHANDLED);
        release_reverse_request_registry(handle);
    }

    #[tokio::test]
    async fn reverse_request_round_trip_preserves_raw_body_corr_and_response() {
        let registry = ReverseRequestRegistry::new();
        let seen = Arc::new(Mutex::new(None));
        let seen_by_handler = Arc::clone(&seen);
        let response = br#"{"jsonrpc":"2.0","id":9,"result":{"accepted":true}}"#.to_vec();
        let expected_response = response.clone();
        registry
            .on_request("elicitation", move |body, ctx| {
                *seen_by_handler
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner()) =
                    Some((body, ctx.corr, ctx.method));
                let response = response.clone();
                async move { response }
            })
            .unwrap();
        let (shared, mut receiver, handle) = reverse_test_shared(registry);
        let request_body =
            br#"{"jsonrpc":"2.0","id":9,"method":"elicitation/create","params":{"z":1,"a":2}}"#
                .to_vec();
        assert!(
            dispatch_frame(
                &shared,
                1,
                reverse_request_frame(handle, 801, request_body.clone()),
            )
            .await
        );
        let reply = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
            .await
            .unwrap()
            .unwrap()
            .frame;
        assert_eq!(reply.header.ty, FrameType::Response);
        assert_eq!(reply.header.corr, 801);
        assert_eq!(reply.body, expected_response);
        assert_eq!(
            seen.lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .clone(),
            Some((request_body, 801, "elicitation/create".to_string()))
        );
        release_reverse_request_registry(handle);
    }

    #[tokio::test]
    async fn panicking_reverse_handler_returns_typed_refusal_and_sibling_request_resolves() {
        let registry = ReverseRequestRegistry::new();
        registry
            .on_request("sampling", |_body, _ctx| async move {
                panic!("person prompt exploded");
            })
            .unwrap();
        let (shared, mut receiver, handle) = reverse_test_shared(registry);
        let sibling_shared = Arc::clone(&shared);
        let sibling = tokio::spawn(async move {
            sibling_shared
                .send_request(RequestSend {
                    binary: false,
                    expected_handle: Some(handle),
                    channel: handle.channel,
                    epoch: handle.epoch,
                    body: b"sibling".to_vec(),
                    priority: Priority::Interactive,
                    admission_class: AdmissionClass::Normal,
                    deadline: Instant::now() + Duration::from_secs(1),
                    retain_late_route_open: false,
                    route_open_reverse_requests: None,
                })
                .await
        });
        let sibling_request = receiver.recv().await.unwrap();
        let reverse_body = serde_json::to_vec(&serde_json::json!({
            "method": "sampling/createMessage",
            "params": {}
        }))
        .unwrap();
        assert!(
            dispatch_frame(&shared, 1, reverse_request_frame(handle, 802, reverse_body),).await
        );
        assert!(
            dispatch_frame(
                &shared,
                1,
                response_frame(
                    handle.channel,
                    handle.epoch,
                    sibling_request.frame.header.corr,
                    b"ok".to_vec(),
                ),
            )
            .await
        );
        assert!(matches!(
            sibling.await.unwrap().unwrap(),
            TerminalFrame::Response { body, .. } if body == b"ok"
        ));
        let refusal = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
            .await
            .unwrap()
            .unwrap()
            .frame;
        assert_eq!(refusal.header.ty, FrameType::Error);
        let error: ErrorBody = serde_json::from_slice(&refusal.body).unwrap();
        assert_eq!(error.code, REVERSE_REQUEST_UNHANDLED);
        assert!(error.message.contains("person prompt exploded"));
        assert!(shared.generation_is_current(1));
        release_reverse_request_registry(handle);
    }

    #[tokio::test]
    async fn writer_batches_ready_frames_into_one_flush() {
        const FRAME_COUNT: usize = 8;

        let shared = writer_test_shared();
        let (live_writer, _live_rx) = mpsc::channel(1);
        let (tx, rx) = mpsc::channel(FRAME_COUNT + 1);
        let instrumented = InstrumentedWriter::new(false);
        let observer = instrumented.clone();
        let mut expected = Vec::with_capacity(FRAME_COUNT);
        let mut keys = Vec::with_capacity(FRAME_COUNT);

        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(live_writer);
            for index in 0..FRAME_COUNT {
                let corr = index as u64 + 1;
                let frame = response_frame(7, 1, corr, vec![index as u8; index + 1]);
                let key = PendingKey {
                    generation: 1,
                    channel: 7,
                    epoch: 1,
                    corr,
                };
                let (pending_tx, _pending_rx) = oneshot::channel();
                inner
                    .pending
                    .insert(key, PendingEntry::unary(pending_tx, false, None, None));
                expected.push(frame.clone());
                keys.push(key);
                tx.try_send(WriteCommand {
                    frame,
                    pending: Some(key),
                })
                .expect("the burst should fit in the writer queue");
                if index == 0 {
                    tx.try_send(WriteCommand {
                        frame: response_frame(7, 1, 999, b"skip".to_vec()),
                        pending: Some(PendingKey {
                            generation: 1,
                            channel: 7,
                            epoch: 1,
                            corr: 999,
                        }),
                    })
                    .expect("the skipped command should fit in the writer queue");
                }
            }
        }
        drop(tx);

        writer_loop(Arc::clone(&shared), instrumented, rx, 1).await;

        {
            let inner = shared.lock_inner();
            for key in keys {
                assert!(
                    inner.pending.get(&key).is_some_and(|entry| entry.accepted),
                    "every written command must be marked accepted"
                );
            }
        }

        let mut wire = std::io::Cursor::new(observer.bytes());
        for expected_frame in expected {
            let actual = read_frame(&mut wire)
                .await
                .expect("the emitted frame should decode")
                .expect("the emitted frame should be present");
            assert_eq!(actual, expected_frame);
        }
        assert!(
            read_frame(&mut wire)
                .await
                .expect("the end of the emitted burst should be clean")
                .is_none(),
            "the writer must not emit extra frames"
        );

        let flush_count = observer.flush_count();
        assert_eq!(
            flush_count, 1,
            "a ready burst must be coalesced into one flush"
        );
        shared.close_sync("test complete");
    }

    #[tokio::test]
    async fn writer_flush_failure_drops_generation_and_preserves_acceptance_classification() {
        let shared = writer_test_shared();
        let (live_writer, _live_rx) = mpsc::channel(1);
        let accepted_key = PendingKey {
            generation: 1,
            channel: 3,
            epoch: 1,
            corr: 1,
        };
        let not_sent_key = PendingKey {
            corr: 2,
            ..accepted_key
        };
        let (accepted_tx, accepted_rx) = oneshot::channel();
        let (not_sent_tx, not_sent_rx) = oneshot::channel();
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(live_writer);
            inner.pending.insert(
                accepted_key,
                PendingEntry::unary(accepted_tx, false, None, None),
            );
            inner.pending.insert(
                not_sent_key,
                PendingEntry::unary(not_sent_tx, false, None, None),
            );
        }

        let (tx, rx) = mpsc::channel(1);
        tx.send(WriteCommand {
            frame: response_frame(3, 1, accepted_key.corr, b"accepted".to_vec()),
            pending: Some(accepted_key),
        })
        .await
        .unwrap();
        drop(tx);

        writer_loop(Arc::clone(&shared), InstrumentedWriter::new(true), rx, 1).await;

        assert!(
            shared.lock_inner().writer.is_none(),
            "a flush failure must drop the active generation"
        );
        let accepted_error = accepted_rx
            .await
            .expect("the accepted request should be settled")
            .into_call_result()
            .unwrap_err();
        assert!(matches!(accepted_error, CallError::OutcomeUnknown(_)));
        assert_eq!(
            accepted_error.outcome_cause(),
            Some(OutcomeUnknownCause::WriterClosed)
        );
        let not_sent_error = not_sent_rx
            .await
            .expect("the unwritten request should be settled")
            .into_call_result()
            .unwrap_err();
        assert!(matches!(not_sent_error, CallError::NotSent(_)));
        assert_eq!(not_sent_error.outcome_cause(), None);
        shared.close_sync("test complete");
    }

    #[tokio::test]
    async fn consumer_close_attaches_outcome_cause_to_pending_call() {
        let shared = writer_test_shared();
        let (writer, _writer_rx) = mpsc::channel(1);
        shared.lock_inner().writer = Some(writer);
        let (tx, rx) = oneshot::channel();
        let mut entry = PendingEntry::unary(tx, false, None, None);
        entry.accepted = true;
        shared.lock_inner().pending.insert(
            PendingKey {
                generation: 1,
                channel: 3,
                epoch: 1,
                corr: 1,
            },
            entry,
        );
        let consumer = SubcConsumer { shared };
        consumer.close().await;
        let err = rx.await.unwrap().into_call_result().unwrap_err();
        assert_eq!(
            err.outcome_cause(),
            Some(OutcomeUnknownCause::ConsumerClosed)
        );
        assert_eq!(err.to_string(), "request outcome unknown: consumer closed");
        assert_eq!(err.close_reason(), None);
    }

    #[tokio::test]
    async fn subscription_completion_drop_attaches_outcome_cause() {
        let (tx, rx) = oneshot::channel();
        let closed = SubscriptionClosed { rx };
        drop(tx);
        let err = closed.await.unwrap_err();
        assert_eq!(
            err.outcome_cause(),
            Some(OutcomeUnknownCause::CompletionFailed)
        );
        assert_eq!(
            err.to_string(),
            "request outcome unknown: subscription closed result channel dropped"
        );
    }

    #[test]
    fn reconnect_classifier_treats_auth_failure_as_transient() {
        // Key rotation across a daemon restart on the fixed port: a client racing
        // the restart reads the pre-rotation file, connects, and fails the proof.
        // That must be retryable — each retry re-reads the file, so the next
        // attempt picks up the rotated key. Treating it as a permanent impostor
        // verdict would turn every daemon restart into a permanent client wedge.
        let auth = ConsumerError::Auth {
            path: PathBuf::from("/tmp/subc-connection.json"),
            endpoint: "127.0.0.1:8757".to_string(),
            source: subc_transport::AuthError::InvalidServerProof,
        };
        assert!(is_reconnect_transient(&auth), "rotation race must retry");

        // Absent file mid-restart stays transient; malformed file stays permanent.
        let absent = ConsumerError::ConnectionFile {
            path: PathBuf::from("/tmp/subc-connection.json"),
            source: ConnectionFileError::Io {
                op: "read",
                path: PathBuf::from("/tmp/subc-connection.json"),
                source: io::Error::new(io::ErrorKind::NotFound, "gone"),
            },
        };
        assert!(is_reconnect_transient(&absent));
    }

    #[tokio::test]
    async fn newer_drop_supersedes_reconnect_and_ignores_stale_completion() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let stale_task = tokio::spawn(std::future::pending::<()>());
        {
            let mut inner = shared.lock_inner();
            inner.generation = 2;
            inner.reconnect = ReconnectState::Background {
                generation: 1,
                task: stale_task,
            };
        }

        assert!(shared.spawn_reconnect(2));
        assert!(matches!(
            &shared.lock_inner().reconnect,
            ReconnectState::Background { generation, .. } if *generation == 2
        ));

        shared.finish_background_reconnect(1);
        assert!(matches!(
            &shared.lock_inner().reconnect,
            ReconnectState::Background { generation, .. } if *generation == 2
        ));
        shared.close_sync("test complete");
    }

    #[test]
    fn retryable_route_open_codes_are_code_specific() {
        for code in [
            "module_reloading",
            "module_warming",
            "target_unavailable",
            "module_timeout",
        ] {
            assert!(is_retryable_route_open_code(code), "{code} should retry");
        }
        // "No module of this id is registered or supervised here" is a typo or
        // an undeployed peer: the daemon reports a configured-but-late target
        // with module_warming/target_unavailable, so retrying unknown_module
        // in place only papers over an unsupervised module's HELLO race.
        assert!(
            !is_retryable_route_open_code(error_codes::UNKNOWN_MODULE),
            "unknown_module is terminal"
        );
        assert!(!is_retryable_route_open_code(error_codes::MODULE_REMOVED));
        assert!(!is_retryable_route_open_code("invalid_project_root"));
        assert!(!is_retryable_route_open_code("route_rejected"));
        assert!(
            !is_retryable_route_open_code("capability_forbidden"),
            "a capability policy refusal must not enter the route.open retry set"
        );
    }

    #[test]
    fn two_routes_record_distinct_reasons_and_reuse_clears_channel() {
        let shared = Arc::new(Shared::new(PathBuf::new(), ConsumerOptions::default()));
        let (writer, _rx) = mpsc::channel(8);
        shared.lock_inner().writer = Some(writer);
        shared.install_ingress_handle(RouteHandle::new(7, 1, 1));
        shared.install_ingress_handle(RouteHandle::new(9, 1, 1));
        {
            let mut inner = shared.lock_inner();
            inner.route_modules.insert(7, "provider".into());
            inner.route_modules.insert(9, "provider".into());
        }
        shared.control_push(br#"{"op":"route.closed","module_id":"provider","channels":[7],"reason":"scope_ended"}"#);
        shared.control_push(
            br#"{"op":"route.closing","module_id":"provider","channels":[9],"reason":"restart"}"#,
        );
        shared.control_push(
            br#"{"op":"route.closing","module_id":"provider","channels":[7],"reason":"crash"}"#,
        );
        assert_eq!(
            shared.lock_inner().route_end_reason(7),
            RouteEndReason::Daemon(RouteCloseReason::ScopeEnded)
        );
        assert_eq!(
            shared.lock_inner().route_end_reason(9),
            RouteEndReason::Daemon(RouteCloseReason::Restart)
        );
        shared.control_push(
            br#"{"op":"route.closed","module_id":"provider","channels":[9],"reason":"crash"}"#,
        );
        assert_eq!(
            shared.lock_inner().route_end_reason(9),
            RouteEndReason::Daemon(RouteCloseReason::Crash)
        );
        shared.control_push(br#"{"op":"route.closed","module_id":"provider","reason":"disable"}"#);
        shared.install_ingress_handle(RouteHandle::new(7, 2, 1));
        assert_eq!(
            shared.lock_inner().route_end_reason(7),
            RouteEndReason::Unknown
        );
    }

    #[test]
    fn legacy_route_push_falls_back_only_when_channels_are_absent() {
        let shared = Shared::new(PathBuf::new(), ConsumerOptions::default());
        shared
            .lock_inner()
            .route_modules
            .insert(7, "provider".into());
        shared.control_push(
            br#"{"op":"route.closed","module_id":"provider","channels":[],"reason":"crash"}"#,
        );
        assert_eq!(
            shared.lock_inner().route_end_reason(7),
            RouteEndReason::Unknown
        );
        shared.control_push(br#"{"op":"route.closing","module_id":"provider","reason":"restart"}"#);
        assert_eq!(
            shared.lock_inner().route_end_reason(7),
            RouteEndReason::Daemon(RouteCloseReason::Restart)
        );
        shared.control_push(br#"{"op":"route.closed","module_id":"provider","reason":"crash"}"#);
        assert_eq!(
            shared.lock_inner().route_end_reason(7),
            RouteEndReason::Daemon(RouteCloseReason::Crash)
        );
    }

    #[tokio::test]
    async fn sdk_teardown_paths_attach_caller_and_connection_loss_reasons() {
        for local in [true, false] {
            let shared = Arc::new(Shared::new(PathBuf::new(), ConsumerOptions::default()));
            let (writer, _writer_rx) = mpsc::channel(8);
            shared.lock_inner().writer = Some(writer);
            let handle = RouteHandle::new(7, 1, 1);
            shared.install_ingress_handle(handle);
            let (tx, rx) = oneshot::channel();
            let mut entry = PendingEntry::unary(tx, false, None, None);
            entry.accepted = true;
            shared.lock_inner().pending.insert(
                PendingKey {
                    generation: 1,
                    channel: 7,
                    epoch: 1,
                    corr: 1,
                },
                entry,
            );
            if local {
                shared
                    .close_handle(handle, &CloseRouteOptions::default())
                    .await
                    .unwrap();
            } else {
                shared.handle_generation_drop(1, "connection gone".into());
            }
            let err = rx.await.unwrap().into_call_result().err().unwrap();
            assert!(matches!(err, CallError::OutcomeUnknown(_)));
            assert_eq!(
                err.outcome_cause(),
                Some(if local {
                    OutcomeUnknownCause::RouteEnded
                } else {
                    OutcomeUnknownCause::ConnectionFailed
                })
            );
            let shared_failure = SharedCallFailure::from(err);
            let err = shared_failure.into_call_error();
            assert_eq!(
                err.close_reason(),
                Some(&if local {
                    RouteEndReason::ClosedByCaller
                } else {
                    RouteEndReason::ConnectionLost
                })
            );
            shared.close_sync("test complete");
        }
    }

    #[tokio::test]
    async fn route_end_reasons_preserve_pending_retry_classes() {
        for reason in [
            RouteEndReason::ClosedByCaller,
            RouteEndReason::ConnectionLost,
            RouteEndReason::Daemon(RouteCloseReason::ScopeEnded),
            RouteEndReason::Unknown,
        ] {
            for accepted in [false, true] {
                let (tx, rx) = oneshot::channel();
                let mut entry = PendingEntry::unary(tx, false, None, None);
                entry.accepted = accepted;
                settle_route_pending_entries(vec![entry], "route ended".into(), reason.clone());
                let err = rx.await.unwrap().into_call_result().err().unwrap();
                assert_eq!(err.close_reason(), Some(&reason));
                assert_eq!(matches!(err, CallError::OutcomeUnknown(_)), accepted);
                assert_eq!(matches!(err, CallError::NotSent(_)), !accepted);
            }
        }
    }

    #[test]
    fn route_close_reason_classifier_accepts_capability_denied_and_fails_closed_for_unknown() {
        assert_eq!(
            RouteCloseReason::from_wire("capability_denied"),
            RouteCloseReason::CapabilityDenied
        );
        assert_eq!(
            RouteCloseReason::from_wire("capability_denied").disposition(),
            RouteCloseDisposition::MustNotReopen
        );
        assert_eq!(
            RouteCloseReason::from_wire("future_policy_reason").disposition(),
            RouteCloseDisposition::MustNotReopen,
            "an unknown close reason must receive the strictest handling"
        );
        assert_eq!(
            RouteCloseReason::from_wire("reload").disposition(),
            RouteCloseDisposition::MayReopen,
            "control proves the classifier can distinguish a conservative default"
        );
    }

    #[tokio::test]
    async fn module_removed_fails_fast_while_module_reloading_retries_at_the_same_route_open_call_site(
    ) {
        // Serves rejections with `code` until the caller settles, returning
        // (attempts_served, result). The retryable arm must keep retrying past
        // any attempt count until the DEADLINE binds — the attempt cap in the
        // options below is deliberately tiny so a regression that re-couples
        // attempts into the retry condition (the 3.1s-effective-budget defect)
        // stops the loop at 2 and fails the `> 2` assertion by name.
        async fn reject_route_open_attempts(code: &str, deadline: Duration) -> (usize, CallError) {
            let shared = Arc::new(Shared::new(
                PathBuf::from("/tmp/does-not-exist"),
                ConsumerOptions::default(),
            ));
            let (writer, mut receiver) = mpsc::channel(4);
            {
                let mut inner = shared.lock_inner();
                inner.writer = Some(writer);
            }
            let consumer = SubcConsumer {
                shared: Arc::clone(&shared),
            };
            let target = RouteTarget::ToolProvider {
                module_id: "retry-polarity".to_string(),
            };
            let identity = BindIdentity::new(
                PathBuf::from("/tmp/project"),
                "test".to_string(),
                code.to_string(),
            );
            let options = CallOptions {
                timeout: Duration::from_secs(2),
                route_retry: RetryBackoff {
                    base: Duration::ZERO,
                    cap: Duration::ZERO,
                    max_attempts: 2,
                },
                route_retry_deadline: deadline,
                ..CallOptions::default()
            };
            let mut task =
                tokio::spawn(async move { consumer.open_route(target, identity, options).await });

            let mut attempts = 0usize;
            let result = loop {
                tokio::select! {
                    command = receiver.recv() => {
                        // The consumer tears the writer down when the open
                        // settles, so a closed channel here means the task is
                        // finishing — join it rather than treating the race as
                        // a broken harness.
                        let Some(command) = command else {
                            break task.await.unwrap().expect_err("route.open must reject");
                        };
                        attempts += 1;
                        let body =
                            serde_json::to_vec(&ErrorBody::new(code, "test rejection")).unwrap();
                        assert!(
                            dispatch_frame(
                                &shared,
                                1,
                                Frame::build(
                                    FrameType::Error,
                                    Flags::new(false, Priority::Interactive, false),
                                    0,
                                    0,
                                    command.frame.header.corr,
                                    body,
                                )
                                .unwrap(),
                            )
                            .await
                        );
                    }
                    joined = &mut task => {
                        break joined.unwrap().expect_err("route.open must reject");
                    }
                }
            };
            assert!(
                receiver.try_recv().is_err(),
                "a settled route.open must not queue another attempt"
            );
            (attempts, result)
        }

        let (reloading_attempts, reloading) =
            reject_route_open_attempts(error_codes::MODULE_RELOADING, Duration::from_millis(150))
                .await;
        assert!(matches!(reloading, CallError::NotSent(_)));
        assert!(
            reloading_attempts > 2,
            "reloading retries must run until the deadline, not an attempt cap \
             (served {reloading_attempts} attempts against max_attempts=2)"
        );

        let (removed_attempts, removed) =
            reject_route_open_attempts(error_codes::MODULE_REMOVED, Duration::from_millis(150))
                .await;
        assert!(matches!(removed, CallError::NotSent(_)));
        assert_eq!(
            removed_attempts, 1,
            "terminal codes settle on the first answer"
        );
    }

    /// splitmix64 over a counter: a seeded stand-in for the consumer's random
    /// source, so jittered delays are reproducible.
    fn seeded_random(seed: u64) -> Box<dyn Fn() -> f64 + Send + Sync> {
        let state = AtomicU64::new(seed);
        Box::new(move || {
            let mut z = state
                .fetch_add(0x9E37_79B9_7F4A_7C15, Ordering::Relaxed)
                .wrapping_add(0x9E37_79B9_7F4A_7C15);
            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
            z ^= z >> 31;
            (z >> 11) as f64 / (1u64 << 53) as f64
        })
    }

    /// A consumer wired to an in-memory writer, standing in for a daemon that
    /// the test answers by hand.
    fn route_open_stand_in(
        random_unit: Box<dyn Fn() -> f64 + Send + Sync>,
    ) -> (Arc<Shared>, Arc<SubcConsumer>, mpsc::Receiver<WriteCommand>) {
        let mut shared = Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        );
        shared.random_unit = random_unit;
        let shared = Arc::new(shared);
        let (writer, receiver) = mpsc::channel(64);
        shared.lock_inner().writer = Some(writer);
        let consumer = Arc::new(SubcConsumer {
            shared: Arc::clone(&shared),
        });
        (shared, consumer, receiver)
    }

    fn restart_target(module_id: &str) -> RouteTarget {
        RouteTarget::ToolProvider {
            module_id: module_id.to_string(),
        }
    }

    fn restart_identity() -> BindIdentity {
        BindIdentity::new(
            PathBuf::from("/tmp/project"),
            "test".to_string(),
            "restart".to_string(),
        )
    }

    /// The daemon's answer to one route.open: accept it on `channel`, or refuse
    /// it with `refusal`.
    fn route_open_answer(corr: u64, channel: u16, refusal: Option<ErrorBody>) -> Frame {
        match refusal {
            None => response_frame(
                0,
                0,
                corr,
                serde_json::to_vec(&ClientControlResponse::RouteOpen {
                    route_channel: channel,
                    route_epoch: 1,
                })
                .unwrap(),
            ),
            Some(body) => Frame::build(
                FrameType::Error,
                Flags::new(false, Priority::Interactive, false),
                0,
                0,
                corr,
                serde_json::to_vec(&body).unwrap(),
            )
            .unwrap(),
        }
    }

    /// Answer every route.open the consumer writes, as `answer` decides from the
    /// open's target module, until `task` finishes.
    async fn answer_route_opens<T>(
        shared: &Arc<Shared>,
        receiver: &mut mpsc::Receiver<WriteCommand>,
        task: &mut JoinHandle<T>,
        mut answer: impl FnMut(&str) -> Option<ErrorBody>,
    ) -> T {
        let mut next_channel = 40u16;
        loop {
            tokio::select! {
                command = receiver.recv() => {
                    let Some(command) = command else {
                        return (&mut *task).await.unwrap();
                    };
                    let request: serde_json::Value =
                        serde_json::from_slice(&command.frame.body).unwrap();
                    let module_id = request["target"]["module_id"].as_str().unwrap().to_string();
                    next_channel += 1;
                    let frame = route_open_answer(
                        command.frame.header.corr,
                        next_channel,
                        answer(&module_id),
                    );
                    assert!(dispatch_frame(shared, 1, frame).await);
                }
                joined = &mut *task => return joined.unwrap(),
            }
        }
    }

    fn reloading() -> ErrorBody {
        ErrorBody::new(error_codes::MODULE_RELOADING, "module is reloading")
    }

    fn drain_call<'a>(
        consumer: &'a SubcConsumer,
        body: &'static [u8],
    ) -> impl Future<Output = Result<Vec<u8>, CallError>> + 'a {
        consumer.call(
            restart_target("plexus"),
            restart_identity(),
            body.to_vec(),
            CallOptions {
                timeout: Duration::from_secs(5),
                ..CallOptions::default()
            },
        )
    }

    async fn refuse_during_drain(shared: &Arc<Shared>, request: &Frame) {
        let frame = Frame::build(
            FrameType::Error,
            request.header.flags,
            request.header.channel,
            request.header.epoch,
            request.header.corr,
            serde_json::to_vec(&reloading()).unwrap(),
        )
        .unwrap();
        assert!(dispatch_frame(shared, 1, frame).await);
    }

    async fn reply_to_drain_call(shared: &Arc<Shared>, request: Frame) {
        assert_eq!(request.header.ty, FrameType::Request);
        assert!(
            dispatch_frame(
                shared,
                1,
                response_frame(
                    request.header.channel,
                    request.header.epoch,
                    request.header.corr,
                    request.body,
                ),
            )
            .await
        );
    }

    #[tokio::test(start_paused = true)]
    async fn shared_route_drain_delivers_both_refusals_and_resends_both_calls() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
        let (_, old) = open_answered(
            &shared,
            &consumer,
            &mut receiver,
            None,
            41,
            "initial shared route",
        )
        .await;
        let mut seed = Box::pin(drain_call(&consumer, b"seed"));
        assert_pending(seed.as_mut()).await;
        reply_to_drain_call(&shared, receiver.recv().await.unwrap().frame).await;
        assert_eq!(seed.await.unwrap(), b"seed");
        shared.control_push(
            &serde_json::to_vec(&serde_json::json!({
                "op": "route.closing", "module_id": "plexus",
                "channels": [old.channel], "terminal": false
            }))
            .unwrap(),
        );
        let mut first = Box::pin(drain_call(&consumer, b"first"));
        let mut second = Box::pin(drain_call(&consumer, b"second"));
        assert_pending(first.as_mut()).await;
        assert_pending(second.as_mut()).await;
        let first_command = receiver.recv().await.unwrap();
        let second_command = receiver.recv().await.unwrap();
        // Observing a frame at the daemon means the real writer accepted it.
        assert!(shared.mark_pending_accepted(first_command.pending.unwrap()));
        assert!(shared.mark_pending_accepted(second_command.pending.unwrap()));
        let first_request = first_command.frame;
        let second_request = second_command.frame;
        assert_eq!(first_request.header.channel, old.channel);
        assert_eq!(second_request.header.channel, old.channel);

        refuse_during_drain(&shared, &first_request).await;
        assert_pending(first.as_mut()).await;
        // Holding route.open unanswered is the barrier: the first call has
        // invalidated the old route before its sibling's refusal arrives.
        let (open_corr, _) = next_route_open(&mut receiver, "replacement route barrier").await;
        refuse_during_drain(&shared, &second_request).await;
        for (ty, channel, epoch, corr) in [
            (FrameType::Goodbye, old.channel, old.epoch, 0),
            (FrameType::Ping, 0, 0, 991),
        ] {
            let frame = Frame::build(
                ty,
                Flags::new(false, Priority::Interactive, false),
                channel,
                epoch,
                corr,
                Vec::new(),
            )
            .unwrap();
            assert!(dispatch_frame(&shared, 1, frame).await);
        }
        // The same dispatcher used by the socket reader emits Pong only after
        // processing the second refusal and the old-route GOODBYE.
        let pong = receiver.recv().await.unwrap().frame;
        assert_eq!(pong.header.ty, FrameType::Pong);
        assert_eq!(pong.header.corr, 991);
        assert_pending(second.as_mut()).await;
        assert!(dispatch_frame(&shared, 1, route_open_answer(open_corr, 42, None)).await);
        assert_pending(first.as_mut()).await;
        assert_pending(second.as_mut()).await;
        while let Ok(command) = receiver.try_recv() {
            assert_eq!(command.frame.header.channel, 42);
            reply_to_drain_call(&shared, command.frame).await;
        }
        assert_eq!(first.await.expect("first call resends"), b"first");
        assert_eq!(
            second.await.expect("second refusal must not time out"),
            b"second"
        );
        assert!(shared.lock_inner().pending.is_empty());
    }

    #[tokio::test(start_paused = true)]
    async fn shared_route_drain_preserves_unrefused_reply_without_resending() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
        let (_, old) = open_answered(
            &shared,
            &consumer,
            &mut receiver,
            None,
            41,
            "initial shared route",
        )
        .await;
        let mut first = Box::pin(drain_call(&consumer, b"refused"));
        let mut second = Box::pin(drain_call(&consumer, b"executing"));
        assert_pending(first.as_mut()).await;
        assert_pending(second.as_mut()).await;
        let first_request = receiver.recv().await.unwrap().frame;
        let second_request = receiver.recv().await.unwrap().frame;
        let executing_corr = second_request.header.corr;
        assert_eq!(second_request.header.channel, old.channel);
        let mut executing_requests = 1;

        refuse_during_drain(&shared, &first_request).await;
        assert_pending(first.as_mut()).await;
        let (open_corr, _) = next_route_open(&mut receiver, "replacement route barrier").await;
        assert_pending(second.as_mut()).await;
        assert!(dispatch_frame(&shared, 1, route_open_answer(open_corr, 42, None)).await);
        assert_pending(first.as_mut()).await;
        assert_pending(second.as_mut()).await;
        while let Ok(command) = receiver.try_recv() {
            assert_eq!(command.frame.header.ty, FrameType::Request);
            // Managed resends allocate a new corr; count the logical request's
            // body as well so an unsafe resend cannot hide behind a new corr.
            if command.frame.header.corr == executing_corr || command.frame.body == b"executing" {
                executing_requests += 1;
            }
            reply_to_drain_call(&shared, command.frame).await;
        }
        reply_to_drain_call(&shared, second_request).await;
        assert_eq!(first.await.expect("refused call resends"), b"refused");
        assert_eq!(
            second.await.expect("real old-route reply arrives"),
            b"executing"
        );
        assert_eq!(executing_requests, 1, "unrefused call must never resend");
    }

    #[tokio::test(start_paused = true)]
    async fn invalidated_route_ingress_is_uninstalled_after_last_pending_settles() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
        let (_, old) = open_answered(
            &shared,
            &consumer,
            &mut receiver,
            None,
            41,
            "initial shared route",
        )
        .await;
        let mut first = Box::pin(drain_call(&consumer, b"first"));
        let mut second = Box::pin(drain_call(&consumer, b"second"));
        assert_pending(first.as_mut()).await;
        assert_pending(second.as_mut()).await;
        let first_request = receiver.recv().await.unwrap().frame;
        let second_request = receiver.recv().await.unwrap().frame;
        refuse_during_drain(&shared, &first_request).await;
        assert_pending(first.as_mut()).await;
        let _ = next_route_open(&mut receiver, "replacement route barrier").await;
        assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), Some(old));
        assert!(route_reverse_request_registry(old.reverse_request_registry_id()).is_ok());
        reply_to_drain_call(&shared, second_request).await;
        assert_eq!(second.await.unwrap(), b"second");
        assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), None);
        assert!(shared.lock_inner().retired_routes.is_empty());
        assert!(route_reverse_request_registry(old.reverse_request_registry_id()).is_err());
        drop(first);
    }

    #[tokio::test(start_paused = true)]
    async fn invalidated_route_ingress_cleans_up_on_drop_deadline_goodbye_and_disconnect() {
        for ending in ["drop", "deadline", "goodbye", "disconnect"] {
            let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
            let (_, old) = open_answered(
                &shared,
                &consumer,
                &mut receiver,
                None,
                41,
                "initial shared route",
            )
            .await;
            let mut first = Box::pin(drain_call(&consumer, b"refused"));
            let mut second = Box::pin(drain_call(&consumer, b"executing"));
            assert_pending(first.as_mut()).await;
            assert_pending(second.as_mut()).await;
            let first_request = receiver.recv().await.unwrap().frame;
            let second_command = receiver.recv().await.unwrap();
            assert!(shared.mark_pending_accepted(second_command.pending.unwrap()));
            refuse_during_drain(&shared, &first_request).await;
            assert_pending(first.as_mut()).await;
            let _ = next_route_open(&mut receiver, "replacement route barrier").await;
            match ending {
                "drop" => drop(second),
                "deadline" => {
                    assert_eq!(
                        second.await.unwrap_err().outcome_cause(),
                        Some(OutcomeUnknownCause::Deadline)
                    );
                }
                "goodbye" => {
                    let frame = Frame::build(
                        FrameType::Goodbye,
                        Flags::new(false, Priority::Interactive, false),
                        old.channel,
                        old.epoch,
                        0,
                        Vec::new(),
                    )
                    .unwrap();
                    assert!(dispatch_frame(&shared, 1, frame).await);
                    assert_eq!(
                        second.await.unwrap_err().outcome_cause(),
                        Some(OutcomeUnknownCause::RouteEnded)
                    );
                }
                "disconnect" => {
                    shared.handle_generation_drop(1, "test disconnect".into());
                    assert_eq!(
                        second.await.unwrap_err().outcome_cause(),
                        Some(OutcomeUnknownCause::ConnectionFailed)
                    );
                }
                _ => unreachable!(),
            }
            assert_eq!(
                shared.ingress_handle(1, old.channel, old.epoch),
                None,
                "{ending}"
            );
            assert!(shared.lock_inner().retired_routes.is_empty(), "{ending}");
            assert!(
                route_reverse_request_registry(old.reverse_request_registry_id()).is_err(),
                "{ending}"
            );
            drop(first);
        }
    }

    #[tokio::test(start_paused = true)]
    async fn invalidated_route_subscription_cancel_and_overflow_uninstall_ingress() {
        for overflow in [false, true] {
            let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
            let (_, old) = open_answered(
                &shared,
                &consumer,
                &mut receiver,
                None,
                41,
                "initial shared route",
            )
            .await;
            let mut subscription = consumer
                .subscribe_route(&old, b"watch".to_vec(), SubscribeOptions::default())
                .await
                .unwrap();
            let request = receiver.recv().await.unwrap().frame;
            let mut call = Box::pin(drain_call(&consumer, b"refused"));
            assert_pending(call.as_mut()).await;
            let refused = receiver.recv().await.unwrap().frame;
            refuse_during_drain(&shared, &refused).await;
            assert_pending(call.as_mut()).await;
            let _ = next_route_open(&mut receiver, "replacement route barrier").await;
            assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), Some(old));
            assert!(matches!(
                consumer
                    .request(&old, b"new".to_vec(), CallOptions::default())
                    .await,
                Err(CallError::StaleRouteHandle(_))
            ));
            if overflow {
                for _ in 0..=DEFAULT_SUBSCRIPTION_EVENT_BUFFER {
                    assert!(
                        dispatch_frame(
                            &shared,
                            1,
                            watch_terminal(&request, FrameType::StreamData, vec![1])
                        )
                        .await
                    );
                }
                assert_eq!(subscription.ended().await, SubscriptionEnd::Backpressure);
            } else {
                subscription.unsubscribe().unwrap();
                assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
            }
            assert_eq!(
                receiver.recv().await.unwrap().frame.header.ty,
                FrameType::Cancel
            );
            assert_eq!(shared.ingress_handle(1, old.channel, old.epoch), None);
            assert!(shared.lock_inner().retired_routes.is_empty());
            drop(call);
        }
    }

    #[tokio::test(start_paused = true)]
    async fn the_default_retry_deadline_outlasts_a_60s_restart_and_the_open_succeeds() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(1));
        let started = Instant::now();
        // A call deadline past the retry deadline, so the retry deadline is
        // the one under test.
        let options = CallOptions {
            timeout: Duration::from_secs(120),
            ..CallOptions::default()
        };
        let mut task = tokio::spawn(async move {
            consumer
                .open_route(restart_target("restarting"), restart_identity(), options)
                .await
        });
        let opened = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
            (started.elapsed() < Duration::from_secs(60)).then(reloading)
        })
        .await;
        let handle =
            opened.unwrap_or_else(|err| panic!("the open must survive the restart: {err}"));
        assert!(handle.channel > 40);
        assert!(started.elapsed() >= Duration::from_secs(60));
    }

    #[tokio::test(start_paused = true)]
    async fn a_call_timeout_shorter_than_the_retry_deadline_ends_the_retries_at_the_call_timeout() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(2));
        let started = Instant::now();
        let options = CallOptions {
            timeout: Duration::from_secs(10),
            ..CallOptions::default()
        };
        let mut task = tokio::spawn(async move {
            consumer
                .open_route(restart_target("restarting"), restart_identity(), options)
                .await
        });
        let err = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
            (started.elapsed() < Duration::from_secs(60)).then(reloading)
        })
        .await
        .expect_err("the call timeout must end the retries before the module is back");
        let elapsed = started.elapsed();
        assert!(matches!(err, CallError::NotSent(_)), "got {err:?}");
        assert!(
            elapsed >= Duration::from_secs(9) && elapsed <= Duration::from_secs(10),
            "the retries must stop at the 10s call timeout, stopped after {elapsed:?}"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn two_routes_refused_together_retry_at_different_jittered_times() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(42));
        let started = Instant::now();
        let mut task = tokio::spawn(async move {
            let alpha = consumer.open_route(
                restart_target("alpha"),
                restart_identity(),
                CallOptions::default(),
            );
            let beta = consumer.open_route(
                restart_target("beta"),
                restart_identity(),
                CallOptions::default(),
            );
            let (alpha, beta) = tokio::join!(alpha, beta);
            (alpha.is_ok(), beta.is_ok())
        });
        let mut first_open = HashMap::<String, Duration>::new();
        let mut retried_at = HashMap::<String, Duration>::new();
        let opened = answer_route_opens(&shared, &mut receiver, &mut task, |module_id| {
            let at = started.elapsed();
            if first_open.contains_key(module_id) {
                retried_at.insert(module_id.to_string(), at);
                None
            } else {
                first_open.insert(module_id.to_string(), at);
                Some(reloading())
            }
        })
        .await;
        assert_eq!(opened, (true, true));
        assert_eq!(first_open["alpha"], first_open["beta"], "refused together");
        // Equal jitter keeps half of the 100ms base delay and randomizes the rest.
        for at in retried_at.values() {
            assert!(
                *at >= Duration::from_millis(50) && *at <= Duration::from_millis(100),
                "retry at {at:?} is outside the jitter window"
            );
        }
        assert_ne!(
            retried_at["alpha"], retried_at["beta"],
            "routes refused together must not retry in lock step"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn twenty_concurrent_opens_never_have_more_than_eight_outstanding_at_the_daemon() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(3));
        let mut task = tokio::spawn(async move {
            let mut opens = tokio::task::JoinSet::new();
            for i in 0..20 {
                let consumer = Arc::clone(&consumer);
                opens.spawn(async move {
                    consumer
                        .open_route(
                            restart_target(&format!("module-{i}")),
                            restart_identity(),
                            CallOptions::default(),
                        )
                        .await
                });
            }
            let mut opened = 0usize;
            while let Some(result) = opens.join_next().await {
                result.unwrap().unwrap();
                opened += 1;
            }
            opened
        });
        // Hold every open until the consumer has gone quiet, so everything it
        // is willing to send at once is outstanding together; then answer them.
        let mut held = Vec::new();
        let mut max_outstanding = 0usize;
        let mut next_channel = 40u16;
        let opened = loop {
            tokio::select! {
                command = receiver.recv() => {
                    // The writer closes when the last consumer handle drops,
                    // which means every open has settled.
                    let Some(command) = command else {
                        break (&mut task).await.unwrap();
                    };
                    held.push(command.frame.header.corr);
                    max_outstanding = max_outstanding.max(held.len());
                }
                () = sleep(Duration::from_millis(25)), if !held.is_empty() => {
                    for corr in held.drain(..) {
                        next_channel += 1;
                        assert!(dispatch_frame(&shared, 1, route_open_answer(corr, next_channel, None)).await);
                    }
                }
                joined = &mut task => break joined.unwrap(),
            }
        };
        assert_eq!(opened, 20);
        assert_eq!(max_outstanding, MAX_ROUTE_OPENS_IN_FLIGHT);
    }

    #[tokio::test(start_paused = true)]
    async fn an_exhausted_deadline_names_module_reloading_not_the_later_admission_pressure() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(4));
        let options = CallOptions {
            route_retry_deadline: Duration::from_secs(5),
            ..CallOptions::default()
        };
        let mut task = tokio::spawn(async move {
            consumer
                .open_route(restart_target("restarting"), restart_identity(), options)
                .await
        });
        let mut opens = 0usize;
        let err = answer_route_opens(&shared, &mut receiver, &mut task, |_| {
            opens += 1;
            Some(if opens <= 2 {
                reloading().with_detail(serde_json::json!({ "reason": "restart" }))
            } else {
                ErrorBody::new(
                    error_codes::TARGET_UNAVAILABLE,
                    "connection already has 8 route.open binds in flight (limit 8); retry after one settles",
                )
            })
        })
        .await
        .expect_err("the module never comes back");
        assert!(opens > 2);
        assert!(matches!(err, CallError::NotSent(_)), "got {err:?}");
        assert_eq!(
            err.route_open_refusal().map(|body| body.code.as_str()),
            Some(error_codes::MODULE_RELOADING)
        );
        let message = err.to_string();
        assert!(
            message.starts_with(
                "request not sent: route.open failed for target tool_provider:restarting: \
                 module_reloading (reason restart) (module is reloading); \
                 the most recent refusal was target_unavailable"
            ),
            "got {message}"
        );
    }

    #[tokio::test]
    async fn close_route_flips_inflight_opening_so_a_racing_open_discards() {
        // The load-bearing close-beats-reopen guard, in isolation: a close that lands
        // while a route.open is in flight (channel not yet cached) must flip the
        // opening's `closed` flag, so the lead opener re-checks it before installing and
        // GOODBYEs the channel it opened instead of caching it.
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let key = RouteKey::new(
            &RouteTarget::ToolProvider {
                module_id: "m".into(),
            },
            &BindIdentity::new(PathBuf::from("/tmp/p"), "h", "s"),
            None,
            None,
        );
        // Simulate an in-flight lead open: an openings entry exists, not yet closed,
        // with no cached route (channel hasn't been installed yet).
        shared.lock_inner().openings.insert(
            key.clone(),
            Opening {
                waiters: Vec::new(),
                closed: false,
            },
        );

        // close_route with no cached route is an idempotent no-op on routes, but MUST
        // flip the in-flight opening's flag so the racing open discards.
        shared
            .close_route(&key, &CloseRouteOptions::default())
            .await;
        assert!(
            shared
                .lock_inner()
                .openings
                .get(&key)
                .is_some_and(|o| o.closed),
            "close_route must flip the in-flight opening's closed flag (close-beats-reopen)"
        );

        // And closing a key with neither a route nor an in-flight open is a no-op.
        let absent = RouteKey::new(
            &RouteTarget::ToolProvider {
                module_id: "absent".into(),
            },
            &BindIdentity::new(PathBuf::from("/tmp/p"), "h", "s"),
            None,
            None,
        );
        shared
            .close_route(&absent, &CloseRouteOptions::default())
            .await;
    }

    #[test]
    fn route_key_is_structured() {
        let target = RouteTarget::InternalService {
            module_id: "a\0b".into(),
            service_id: "svc".into(),
        };
        let identity = BindIdentity::new(PathBuf::from("/tmp/project"), "h", "s");
        let key = RouteKey::new(&target, &identity, None, None);
        assert_eq!(key.project_root, PathBuf::from("/tmp/project"));
        assert!(matches!(key.target, RouteTargetKey::InternalService { .. }));
    }

    async fn assert_pending(mut future: Pin<&mut impl Future>) {
        assert!(
            std::future::poll_fn(|cx| Poll::Ready(future.as_mut().poll(cx).is_pending())).await
        );
    }

    /// Replace only the transport, leaving the actual generation-drop cleanup in use.
    fn drop_and_replace_test_transport(shared: &Arc<Shared>) -> mpsc::Receiver<WriteCommand> {
        let generation = shared.lock_inner().generation;
        // Keep the background supervisor from touching a real connection file.
        shared.lock_inner().reconnect = ReconnectState::Inline { generation };
        shared.handle_generation_drop(generation, "test connection drop".into());
        let (writer, receiver) = mpsc::channel(64);
        let mut inner = shared.lock_inner();
        inner.generation += 1;
        inner.epoch += 1;
        inner.next_corr = Some(1);
        inner.writer = Some(writer);
        inner.reconnect = ReconnectState::Idle;
        receiver
    }

    #[tokio::test(start_paused = true)]
    async fn route_open_single_flight_survives_generation_drop_during_backoff() {
        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
        let opts = CallOptions::default();
        let opener = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
        tokio::pin!(opener);
        assert_pending(opener.as_mut()).await;
        let first = receiver.try_recv().unwrap();
        assert!(
            dispatch_frame(
                &shared,
                1,
                route_open_answer(first.frame.header.corr, 0, Some(reloading())),
            )
            .await
        );
        assert_pending(opener.as_mut()).await;

        // A caller already waiting and one arriving after the drop must both stay
        // behind the same lead opener, including its unfinished retry backoff.
        let waiting = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
        tokio::pin!(waiting);
        assert_pending(waiting.as_mut()).await;
        let mut receiver = drop_and_replace_test_transport(&shared);
        assert_pending(waiting.as_mut()).await;
        let arriving = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
        tokio::pin!(arriving);
        assert_pending(arriving.as_mut()).await;
        assert!(
            receiver.try_recv().is_err(),
            "a second opener bypassed the backoff"
        );

        tokio::time::advance(opts.route_retry.base).await;
        assert_pending(opener.as_mut()).await;
        let retry = receiver.try_recv().unwrap();
        assert!(
            dispatch_frame(
                &shared,
                2,
                route_open_answer(retry.frame.header.corr, 42, None),
            )
            .await
        );
        let handle = opener.await.unwrap();
        assert_eq!(waiting.await.unwrap(), handle);
        assert_eq!(arriving.await.unwrap(), handle);
        assert!(
            receiver.try_recv().is_err(),
            "more than one retry was emitted"
        );
        let inner = shared.lock_inner();
        assert!(inner.openings.is_empty());
        assert_eq!(inner.routes.len(), 1);
        assert_eq!(inner.route_epochs.len(), 1);
    }

    #[tokio::test(start_paused = true)]
    async fn close_route_during_backoff_survives_generation_drop() {
        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
        let opts = CallOptions::default();
        let opener = consumer.open_route(restart_target("m"), restart_identity(), opts.clone());
        tokio::pin!(opener);
        assert_pending(opener.as_mut()).await;
        let first = receiver.try_recv().unwrap();
        assert!(
            dispatch_frame(
                &shared,
                1,
                route_open_answer(first.frame.header.corr, 0, Some(reloading())),
            )
            .await
        );
        assert_pending(opener.as_mut()).await;
        consumer
            .close_route(
                restart_target("m"),
                restart_identity(),
                CloseRouteOptions::default(),
            )
            .await;
        let mut receiver = drop_and_replace_test_transport(&shared);
        tokio::time::advance(opts.route_retry.base).await;
        assert_pending(opener.as_mut()).await;
        let retry = receiver.try_recv().unwrap();
        assert!(
            dispatch_frame(
                &shared,
                2,
                route_open_answer(retry.frame.header.corr, 42, None),
            )
            .await
        );
        let err = opener.await.expect_err("close must win over the retry");
        assert!(matches!(err, CallError::NotSent(_)));
        let goodbye = receiver
            .try_recv()
            .expect("discarded route must get GOODBYE");
        assert_eq!(goodbye.frame.header.ty, FrameType::Goodbye);
        assert_eq!(goodbye.frame.header.channel, 42);
        assert!(receiver.try_recv().is_err());
        let inner = shared.lock_inner();
        assert!(inner.routes.is_empty());
        assert!(inner.route_epochs.is_empty());
        assert!(inner.openings.is_empty());
    }

    #[tokio::test]
    async fn route_channel_index_tracks_lookup_close_and_generation_drop() {
        let shared = writer_test_shared();
        let (writer, _rx) = mpsc::channel(32);
        let mut expected = Vec::new();
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            for channel in 1..=8 {
                let key = RouteKey::new(
                    &RouteTarget::ToolProvider {
                        module_id: format!("module-{channel}"),
                    },
                    &BindIdentity::new(
                        PathBuf::from("/tmp/project"),
                        "test",
                        format!("session-{channel}"),
                    ),
                    None,
                    None,
                );
                let route = RouteState {
                    handle: RouteHandle::new(channel, channel.into(), 1),
                    sem: Arc::new(Semaphore::new(DEFAULT_ROUTE_WINDOW)),
                };
                inner.cache_route(key.clone(), route.clone());
                expected.push((key, route));
            }
        }

        for (key, expected_route) in &expected {
            let resolved = shared
                .route_state(expected_route.handle)
                .expect("an indexed route handle should resolve");
            assert_eq!(resolved.handle, expected_route.handle);
            assert!(Arc::ptr_eq(&resolved.sem, &expected_route.sem));

            let inner = shared.lock_inner();
            assert_eq!(
                inner.route_by_channel.get(&expected_route.handle.channel),
                Some(key)
            );
            assert_eq!(
                inner.route_epochs.get(&expected_route.handle.channel),
                Some(&expected_route.handle)
            );
            assert!(inner
                .routes
                .get(key)
                .is_some_and(|route| route.handle == expected_route.handle));
        }

        let (closed_key, closed_route) = &expected[3];
        shared
            .close_route(closed_key, &CloseRouteOptions::default())
            .await;
        {
            let inner = shared.lock_inner();
            assert!(!inner.routes.contains_key(closed_key));
            assert!(!inner
                .route_by_channel
                .contains_key(&closed_route.handle.channel));
            assert!(!inner
                .route_epochs
                .contains_key(&closed_route.handle.channel));
        }
        assert!(matches!(
            shared.route_state(closed_route.handle),
            Err(CallError::StaleRouteHandle(handle)) if handle == closed_route.handle
        ));

        shared.handle_generation_drop(1, "test generation dropped".into());
        {
            let inner = shared.lock_inner();
            assert!(inner.routes.is_empty());
            assert!(inner.route_by_channel.is_empty());
            assert!(inner.route_epochs.is_empty());
        }
        shared.close_sync("test complete");
    }

    #[tokio::test]
    async fn stale_push_is_not_delivered_after_connection_generation_changes() {
        let shared = writer_test_shared();
        let old_handle = RouteHandle::new(7, 1, 1);
        let (writer, _writer_rx) = mpsc::channel(1);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.route_epochs.insert(old_handle.channel, old_handle);
        }
        let mut pushes = shared
            .register_push_events(old_handle)
            .expect("the old live route should accept a receiver");

        {
            let mut inner = shared.lock_inner();
            inner.generation = 2;
            inner.close_routes();
            inner.route_epochs.clear();
            inner.route_modules.clear();
            inner.route_end_reasons.clear();
            inner.legacy_channel_reasons.clear();
        }
        shared.route_push(old_handle, b"stale".to_vec());

        assert!(
            pushes.recv().await.is_none(),
            "connection teardown must end the old receiver before a stale Push can arrive"
        );
        shared.close_sync("test complete");
    }

    #[test]
    fn route_key_canonicalizes_consumer_capabilities() {
        let target = RouteTarget::ToolProvider {
            module_id: "aft".into(),
        };
        let identity = BindIdentity::new(PathBuf::from("/tmp/project"), "h", "s");
        let left = RouteKey::new(
            &target,
            &identity,
            None,
            Some(&["sampling".to_string(), "elicitation".to_string()]),
        );
        let right = RouteKey::new(
            &target,
            &identity,
            None,
            Some(&[
                "elicitation".to_string(),
                "sampling".to_string(),
                "sampling".to_string(),
            ]),
        );
        assert_eq!(left, right);
    }

    #[tokio::test]
    async fn routes_with_and_without_declared_consumer_capabilities_are_kept_apart() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(10));
        let (undeclared_request, undeclared) = open_answered_with(
            &shared,
            &consumer,
            &mut receiver,
            CallOptions::default(),
            74,
            "the undeclared route opens first",
        )
        .await;
        assert!(undeclared_request.get("consumer_capabilities").is_none());

        let declared_opts = CallOptions::default()
            .with_consumer_capability("tool-result/v1")
            .unwrap();
        let (declared_request, declared) = open_answered_with(
            &shared,
            &consumer,
            &mut receiver,
            declared_opts.clone(),
            75,
            "a declared open must not reuse the undeclared route",
        )
        .await;
        assert_eq!(
            declared_request["consumer_capabilities"],
            serde_json::json!(["tool-result/v1"])
        );
        assert_ne!(undeclared, declared);

        assert_eq!(
            consumer
                .open_route(restart_target("plexus"), restart_identity(), declared_opts)
                .await
                .unwrap(),
            declared,
            "the same declaration must reuse its cached route"
        );
        assert_eq!(
            consumer
                .open_route(
                    restart_target("plexus"),
                    restart_identity(),
                    CallOptions::default(),
                )
                .await
                .unwrap(),
            undeclared,
            "an undeclared open must continue to reuse only its own route"
        );
        assert!(
            receiver.try_recv().is_err(),
            "both subsequent opens are cache hits"
        );
        shared.close_sync("test complete");
    }

    fn scope_selector(owner: &str, scope_ref: &str, scope_epoch: u64) -> ScopeSelector {
        ScopeSelector::new(
            subc_protocol::Principal::Reserved {
                module_id: owner.to_string(),
            },
            scope_ref.to_string(),
            Some(scope_epoch),
        )
    }

    #[test]
    fn route_key_separates_scopes_by_owner_ref_and_epoch_and_from_unscoped() {
        let target = RouteTarget::ToolProvider {
            module_id: "plexus".into(),
        };
        let identity = BindIdentity::new(PathBuf::from("/tmp/project"), "h", "s");
        let key = |scope: Option<ScopeSelector>| {
            RouteKey::new(&target, &identity, None, None).with_scope(scope.as_ref())
        };
        let base = key(Some(scope_selector("owner", "session-a", 1)));
        assert_eq!(base, key(Some(scope_selector("owner", "session-a", 1))));
        for (label, other) in [
            ("epoch", key(Some(scope_selector("owner", "session-a", 2)))),
            ("ref", key(Some(scope_selector("owner", "session-b", 1)))),
            ("owner", key(Some(scope_selector("other", "session-a", 1)))),
            ("unscoped", key(None)),
        ] {
            assert_ne!(base, other, "a different {label} must be a different route");
        }
        let mut no_epoch = scope_selector("owner", "session-a", 1);
        no_epoch.scope_epoch = None;
        assert_ne!(base, key(Some(no_epoch)));
    }

    /// The next route.open the consumer writes, skipping any other frame
    /// (a GOODBYE, a cancel). Fails the test by name if none arrives, which is
    /// what a cache hit that should have been a miss looks like.
    async fn next_route_open(
        receiver: &mut mpsc::Receiver<WriteCommand>,
        why: &str,
    ) -> (u64, serde_json::Value) {
        loop {
            let command = tokio::time::timeout(Duration::from_secs(2), receiver.recv())
                .await
                .unwrap_or_else(|_| panic!("no route.open was sent: {why}"))
                .expect("writer channel open");
            if command.frame.header.channel != 0 || command.frame.header.ty != FrameType::Request {
                continue;
            }
            let request: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
            if request["op"] == "route.open" {
                return (command.frame.header.corr, request);
            }
        }
    }

    /// Open a route (scoped when `scope` is set) through the stand-in daemon,
    /// accept its route.open on `channel`, and return the open's body and handle.
    async fn open_answered(
        shared: &Arc<Shared>,
        consumer: &Arc<SubcConsumer>,
        receiver: &mut mpsc::Receiver<WriteCommand>,
        scope: Option<ScopeSelector>,
        channel: u16,
        why: &str,
    ) -> (serde_json::Value, RouteHandle) {
        let consumer = Arc::clone(consumer);
        let task = tokio::spawn(async move {
            match scope {
                Some(scope) => {
                    consumer
                        .open_route_scoped(
                            restart_target("plexus"),
                            restart_identity(),
                            scope,
                            CallOptions::default(),
                        )
                        .await
                }
                None => {
                    consumer
                        .open_route(
                            restart_target("plexus"),
                            restart_identity(),
                            CallOptions::default(),
                        )
                        .await
                }
            }
        });
        let (corr, request) = next_route_open(receiver, why).await;
        assert!(dispatch_frame(shared, 1, route_open_answer(corr, channel, None)).await);
        let handle = task.await.unwrap().expect("the stand-in accepted the open");
        (request, handle)
    }

    /// Open an unscoped `plexus` route with `opts` through the stand-in
    /// daemon, accept its route.open on `channel`, and return the open's body
    /// and handle.
    async fn open_answered_with(
        shared: &Arc<Shared>,
        consumer: &Arc<SubcConsumer>,
        receiver: &mut mpsc::Receiver<WriteCommand>,
        opts: CallOptions,
        channel: u16,
        why: &str,
    ) -> (serde_json::Value, RouteHandle) {
        let consumer = Arc::clone(consumer);
        let task = tokio::spawn(async move {
            consumer
                .open_route(restart_target("plexus"), restart_identity(), opts)
                .await
        });
        let (corr, request) = next_route_open(receiver, why).await;
        assert!(dispatch_frame(shared, 1, route_open_answer(corr, channel, None)).await);
        let handle = task.await.unwrap().expect("the stand-in accepted the open");
        (request, handle)
    }

    fn with_role_versions(entries: &[(&str, &str)]) -> CallOptions {
        CallOptions {
            role_versions: Some(
                entries
                    .iter()
                    .map(|(role, version)| (role.to_string(), version.to_string()))
                    .collect(),
            ),
            ..CallOptions::default()
        }
    }

    /// A provider picks its wire shape from the role versions at bind, so a
    /// legacy route and a versioned one to the same target must never be
    /// shared, while the same declaration again (and an empty map, which
    /// declares nothing) reuses the route it matches.
    #[tokio::test]
    async fn routes_differing_only_in_role_versions_are_kept_apart() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(9));
        let (legacy_request, legacy) = open_answered_with(
            &shared,
            &consumer,
            &mut receiver,
            CallOptions::default(),
            71,
            "first, legacy open",
        )
        .await;
        assert!(
            legacy_request.get("role_versions").is_none(),
            "{legacy_request}"
        );

        let (v1_request, v1) = open_answered_with(
            &shared,
            &consumer,
            &mut receiver,
            with_role_versions(&[("tool-provider", "v1")]),
            72,
            "a v1 open must not reuse the legacy route",
        )
        .await;
        assert_eq!(
            v1_request["role_versions"],
            serde_json::json!({ "tool-provider": "v1" })
        );
        assert_ne!(legacy, v1);

        let (v2_request, v2) = open_answered_with(
            &shared,
            &consumer,
            &mut receiver,
            with_role_versions(&[("tool-provider", "v2")]),
            73,
            "a v2 open must not reuse the v1 route",
        )
        .await;
        assert_eq!(
            v2_request["role_versions"],
            serde_json::json!({ "tool-provider": "v2" })
        );
        assert!(![legacy, v1].contains(&v2));

        let open = |opts: CallOptions| {
            let consumer = Arc::clone(&consumer);
            async move {
                consumer
                    .open_route(restart_target("plexus"), restart_identity(), opts)
                    .await
                    .unwrap()
            }
        };
        assert_eq!(
            open(with_role_versions(&[("tool-provider", "v1")])).await,
            v1
        );
        assert_eq!(open(CallOptions::default()).await, legacy);
        assert_eq!(
            open(CallOptions {
                role_versions: Some(BTreeMap::new()),
                ..CallOptions::default()
            })
            .await,
            legacy,
            "an empty map declares nothing and reuses the legacy route"
        );
        assert!(
            receiver.try_recv().is_err(),
            "a cache hit must not send a route.open"
        );
        shared.close_sync("test complete");
    }

    #[tokio::test]
    async fn scoped_routes_are_cached_per_owner_ref_and_epoch_and_apart_from_unscoped() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(8));
        let selector = scope_selector("owner", "session-a", 1);
        let (request, first) = open_answered(
            &shared,
            &consumer,
            &mut receiver,
            Some(selector.clone()),
            61,
            "first scoped open",
        )
        .await;
        assert_eq!(request["scope"], serde_json::to_value(&selector).unwrap());

        // The same selector again is a cache hit: no route.open, same handle.
        let again = consumer
            .open_route_scoped(
                restart_target("plexus"),
                restart_identity(),
                selector,
                CallOptions::default(),
            )
            .await
            .unwrap();
        assert_eq!(again, first);
        assert!(
            receiver.try_recv().is_err(),
            "a cache hit must not send a route.open"
        );

        let mut handles = vec![first];
        for (channel, scope, why) in [
            (
                62,
                Some(scope_selector("owner", "session-a", 2)),
                "another epoch of the same scope must open its own route",
            ),
            (
                63,
                Some(scope_selector("owner", "session-b", 1)),
                "another scope ref must open its own route",
            ),
            (
                64,
                Some(scope_selector("other-owner", "session-a", 1)),
                "another owner's scope must open its own route",
            ),
            (65, None, "an unscoped open must not reuse a scoped route"),
        ] {
            let expected_scope = scope
                .as_ref()
                .map(|scope| serde_json::to_value(scope).unwrap());
            let (request, handle) =
                open_answered(&shared, &consumer, &mut receiver, scope, channel, why).await;
            assert_eq!(
                request.get("scope").cloned(),
                expected_scope,
                "the route.open must carry exactly the requested scope: {why}"
            );
            assert!(!handles.contains(&handle), "{why}");
            handles.push(handle);
        }
        shared.close_sync("test complete");
    }

    #[tokio::test]
    async fn a_dropped_scoped_route_reopens_with_the_same_selector() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(7));
        let selector = scope_selector("owner", "session-a", 3);
        let (first_request, first) = open_answered(
            &shared,
            &consumer,
            &mut receiver,
            Some(selector.clone()),
            51,
            "first scoped open",
        )
        .await;

        // The daemon ends the route, as it does when the provider restarts.
        let goodbye = Frame::build(
            FrameType::Goodbye,
            Flags::new(false, Priority::Interactive, false),
            first.channel,
            first.epoch,
            0,
            Vec::new(),
        )
        .unwrap();
        assert!(dispatch_frame(&shared, 1, goodbye).await);
        assert!(matches!(
            shared.route_state(first),
            Err(CallError::StaleRouteHandle(_))
        ));

        let (second_request, second) = open_answered(
            &shared,
            &consumer,
            &mut receiver,
            Some(selector.clone()),
            52,
            "the reopen after the route dropped",
        )
        .await;
        assert_eq!(
            first_request["scope"],
            serde_json::to_value(&selector).unwrap()
        );
        assert_eq!(second_request["scope"], first_request["scope"]);
        assert_ne!(second, first);
        shared.close_sync("test complete");
    }

    /// Refuse every scoped route.open with `code` until the open settles, and
    /// return how many attempts were served and the error the caller got.
    async fn refuse_scoped_opens(code: &str) -> (usize, CallError) {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(9));
        let options = CallOptions {
            timeout: Duration::from_secs(2),
            route_retry: RetryBackoff {
                base: Duration::ZERO,
                cap: Duration::ZERO,
                max_attempts: 2,
            },
            route_retry_deadline: Duration::from_millis(150),
            ..CallOptions::default()
        };
        let mut task = tokio::spawn(async move {
            consumer
                .open_route_scoped(
                    restart_target("plexus"),
                    restart_identity(),
                    scope_selector("owner", "session-a", 1),
                    options,
                )
                .await
        });
        let mut attempts = 0usize;
        let err = loop {
            tokio::select! {
                command = receiver.recv() => {
                    let Some(command) = command else {
                        break task.await.unwrap().expect_err("route.open must be refused");
                    };
                    attempts += 1;
                    let frame = route_open_answer(
                        command.frame.header.corr,
                        0,
                        Some(ErrorBody::new(code, "test refusal")),
                    );
                    assert!(dispatch_frame(&shared, 1, frame).await);
                }
                joined = &mut task => {
                    break joined.unwrap().expect_err("route.open must be refused");
                }
            }
        };
        shared.close_sync("test complete");
        (attempts, err)
    }

    #[tokio::test]
    async fn scoped_open_retries_not_synced_and_changed_and_ends_on_the_terminal_scope_codes() {
        for code in [error_codes::SCOPE_NOT_SYNCED, error_codes::SCOPE_CHANGED] {
            let (attempts, err) = refuse_scoped_opens(code).await;
            assert!(attempts > 1, "{code} must be retried, served {attempts}");
            assert_eq!(
                err.route_open_refusal().map(|body| body.code.as_str()),
                Some(code)
            );
        }
        for code in [
            error_codes::SCOPE_ENDED,
            error_codes::SCOPE_NOT_LIVE,
            error_codes::SCOPE_EPOCH_REQUIRED,
            error_codes::SCOPE_NOT_CARRIER,
        ] {
            let (attempts, err) = refuse_scoped_opens(code).await;
            assert_eq!(attempts, 1, "{code} is terminal and must not be retried");
            assert!(matches!(err, CallError::NotSent(_)));
            assert_eq!(
                err.route_open_refusal().map(|body| body.code.as_str()),
                Some(code)
            );
        }
    }

    /// The daemon refuses the first route.open with `module_warming`, then the
    /// retry is written and accepted but never answered, so the retry deadline
    /// expires while that attempt is still waiting. The caller must still get
    /// the refusal it already received, as `NotSent`, rather than the bare
    /// "timed out at its deadline" of the unanswered attempt. A busy daemon
    /// that answers the final retry a few milliseconds late hits this path.
    #[tokio::test]
    async fn refusal_survives_a_retry_still_in_flight_at_the_deadline() {
        let (shared, consumer, mut receiver) = route_open_stand_in(seeded_random(11));
        let options = CallOptions {
            timeout: Duration::from_secs(5),
            route_retry: RetryBackoff {
                base: Duration::ZERO,
                cap: Duration::ZERO,
                max_attempts: 2,
            },
            route_retry_deadline: Duration::from_millis(300),
            ..CallOptions::default()
        };
        let mut task = tokio::spawn(async move {
            consumer
                .open_route(restart_target("warming"), restart_identity(), options)
                .await
        });
        let generation = shared.lock_inner().generation;
        let refusal = ErrorBody {
            code: error_codes::MODULE_WARMING.to_string(),
            message: "warming is not ready".to_string(),
            detail: Some(serde_json::json!({"reason": "required_capability_unprovided"})),
        };
        let mut attempts = 0usize;
        let mut held = false;
        let err = loop {
            tokio::select! {
                command = receiver.recv() => {
                    let Some(command) = command else {
                        break task.await.unwrap().expect_err("route.open must fail");
                    };
                    if command.frame.header.ty != FrameType::Request {
                        continue;
                    }
                    attempts += 1;
                    if attempts == 1 {
                        let frame = route_open_answer(
                            command.frame.header.corr,
                            0,
                            Some(refusal.clone()),
                        );
                        assert!(dispatch_frame(&shared, generation, frame).await);
                    } else {
                        // What the writer task does once the frame is on the
                        // socket: from here a timeout is OutcomeUnknown.
                        held = shared.mark_pending_accepted(
                            command.pending.expect("a route.open is a pending request"),
                        );
                    }
                }
                joined = &mut task => {
                    break joined.unwrap().expect_err("route.open must fail");
                }
            }
        };
        shared.close_sync("test complete");
        assert_eq!(
            attempts, 2,
            "one refused attempt, then one held past the deadline"
        );
        assert!(
            held,
            "the second attempt must be accepted and left unanswered"
        );
        assert!(
            err.is_not_sent(),
            "a refused route never delivered the request: {err}"
        );
        let body = err
            .route_open_refusal()
            .unwrap_or_else(|| panic!("the refusal must survive the deadline: {err}"));
        assert_eq!(body.code, error_codes::MODULE_WARMING);
        assert_eq!(body.detail, refusal.detail);
    }

    #[test]
    fn every_scope_close_reason_must_not_reopen() {
        for reason in [
            subc_protocol::RouteCloseReason::ScopeEnded,
            subc_protocol::RouteCloseReason::ScopeCarrierRemoved,
            subc_protocol::RouteCloseReason::ScopeDelegationChanged,
            subc_protocol::RouteCloseReason::ScopeParentEnded,
        ] {
            let wire = serde_json::to_value(reason).unwrap();
            let wire = wire.as_str().expect("a close reason is a string");
            assert!(wire.starts_with("scope_"), "{wire}");
            assert_eq!(
                RouteCloseReason::from_wire(wire).disposition(),
                RouteCloseDisposition::MustNotReopen,
                "a route closed for {wire} must not be reopened"
            );
        }
    }

    // The fake module receives the queued Request and injects frames through the
    // same dispatcher as the socket reader, without a daemon process.
    async fn watch_subscribed() -> (
        SubcConsumer,
        mpsc::Receiver<WriteCommand>,
        Subscription,
        Frame,
    ) {
        let (shared, mut rx, handle) = reverse_test_shared(ReverseRequestRegistry::new());
        shared.lock_inner().one_shot_routes.insert(
            handle.channel,
            RouteState {
                handle,
                sem: Arc::new(Semaphore::new(1)),
            },
        );
        let consumer = SubcConsumer { shared };
        let subscription = consumer
            .subscribe_route(&handle, b"watch".to_vec(), SubscribeOptions::default())
            .await
            .unwrap();
        let request = rx.recv().await.unwrap().frame;
        (consumer, rx, subscription, request)
    }

    fn watch_terminal(request: &Frame, ty: FrameType, body: Vec<u8>) -> Frame {
        Frame::build(
            ty,
            Flags::new(false, Priority::Interactive, false),
            request.header.channel,
            request.header.epoch,
            request.header.corr,
            body,
        )
        .unwrap()
    }

    #[tokio::test]
    async fn subscription_ended_preserves_response_body_and_closed_stays_ok() {
        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
        let body = vec![0, 255, 128, 1, 10];
        assert!(
            dispatch_frame(
                &consumer.shared,
                1,
                watch_terminal(&request, FrameType::Response, body.clone())
            )
            .await
        );
        subscription.closed().await.unwrap();
        assert_eq!(
            subscription.ended().await,
            SubscriptionEnd::Response(body.clone())
        );
        subscription.unsubscribe().unwrap();
        assert_eq!(subscription.ended().await, SubscriptionEnd::Response(body));
        assert_eq!(subscription.events().recv().await, None);
    }

    #[tokio::test]
    async fn subscription_ended_distinguishes_empty_response_from_stream_end() {
        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
        assert!(
            dispatch_frame(
                &consumer.shared,
                1,
                watch_terminal(&request, FrameType::Response, Vec::new())
            )
            .await
        );
        assert_eq!(
            subscription.ended().await,
            SubscriptionEnd::Response(Vec::new())
        );
        subscription.closed().await.unwrap();
    }

    #[tokio::test]
    async fn subscription_ended_reports_stream_end_and_closed_stays_ok() {
        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
        assert!(
            dispatch_frame(
                &consumer.shared,
                1,
                watch_terminal(&request, FrameType::StreamEnd, Vec::new())
            )
            .await
        );
        assert_eq!(subscription.ended().await, SubscriptionEnd::StreamEnd);
        subscription.closed().await.unwrap();
    }

    #[tokio::test]
    async fn subscription_ended_reports_module_error_code_and_detail() {
        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
        let error = ErrorBody {
            code: "no_grant".to_string(),
            message: "not accepted: no grant".to_string(),
            detail: Some(serde_json::json!({"capability": "watch"})),
        };
        assert!(
            dispatch_frame(
                &consumer.shared,
                1,
                watch_terminal(
                    &request,
                    FrameType::Error,
                    serde_json::to_vec(&error).unwrap()
                )
            )
            .await
        );
        assert_eq!(
            subscription.ended().await,
            SubscriptionEnd::Error(error.clone())
        );
        let CallError::Module(closed_error) = subscription.closed().await.unwrap_err() else {
            panic!("closed must still return the module error");
        };
        assert_eq!(closed_error, error);
        subscription.unsubscribe().unwrap();
        assert_eq!(subscription.ended().await, SubscriptionEnd::Error(error));
    }

    #[tokio::test]
    async fn subscription_ended_reports_unsubscribe_as_cancelled_and_ignores_late_terminal() {
        let (consumer, mut rx, mut subscription, request) = watch_subscribed().await;
        subscription.unsubscribe().unwrap();
        subscription.unsubscribe().unwrap();
        subscription.closed().await.unwrap();
        assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
        let cancel = rx.recv().await.unwrap().frame;
        assert_eq!(cancel.header.ty, FrameType::Cancel);
        assert_eq!(cancel.header.corr, request.header.corr);
        assert!(rx.try_recv().is_err());
        assert!(
            dispatch_frame(
                &consumer.shared,
                1,
                watch_terminal(&request, FrameType::Response, b"late".to_vec())
            )
            .await
        );
        assert_eq!(subscription.ended().await, SubscriptionEnd::Cancelled);
    }

    #[tokio::test]
    async fn subscription_ended_retains_route_close_reason() {
        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
        let push = Frame::build(FrameType::Push, Flags::new(false, Priority::Interactive, false), 0, 0, 0,
            serde_json::to_vec(&serde_json::json!({"op": "route.closed", "module_id": "watch", "reason": "capability_denied", "channels": [request.header.channel]})).unwrap()).unwrap();
        assert!(dispatch_frame(&consumer.shared, 1, push).await);
        assert!(
            dispatch_frame(
                &consumer.shared,
                1,
                watch_terminal(&request, FrameType::Goodbye, Vec::new())
            )
            .await
        );
        let reason = RouteEndReason::Daemon(RouteCloseReason::CapabilityDenied);
        assert_eq!(
            subscription.ended().await,
            SubscriptionEnd::RouteClosed {
                reason: reason.clone()
            }
        );
        assert_eq!(
            subscription.closed().await.unwrap_err().close_reason(),
            Some(&reason)
        );
    }

    #[tokio::test]
    async fn subscription_ended_reports_connection_loss() {
        let (consumer, _rx, mut subscription, _request) = watch_subscribed().await;
        consumer
            .shared
            .handle_generation_drop(1, "fake connection lost".to_string());
        assert_eq!(subscription.ended().await, SubscriptionEnd::ConnectionLost);
        assert!(subscription.closed().await.is_err());
    }

    #[tokio::test]
    async fn subscription_ended_waiter_wakes_on_stream_end() {
        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
        let (end, dispatched) = tokio::join!(subscription.ended(), async {
            tokio::task::yield_now().await;
            dispatch_frame(
                &consumer.shared,
                1,
                watch_terminal(&request, FrameType::StreamEnd, Vec::new()),
            )
            .await
        });
        assert!(dispatched);
        assert_eq!(end, SubscriptionEnd::StreamEnd);
        subscription.closed().await.unwrap();
    }

    #[tokio::test]
    async fn subscription_ended_reports_backpressure_without_hiding_closed_error() {
        let (consumer, _rx, mut subscription, request) = watch_subscribed().await;
        for _ in 0..=DEFAULT_SUBSCRIPTION_EVENT_BUFFER {
            assert!(
                dispatch_frame(
                    &consumer.shared,
                    1,
                    watch_terminal(&request, FrameType::StreamData, vec![1])
                )
                .await
            );
        }
        assert_eq!(subscription.ended().await, SubscriptionEnd::Backpressure);
        assert!(matches!(
            subscription.closed().await,
            Err(CallError::SubscriptionBackpressure(_))
        ));
    }

    #[tokio::test]
    async fn subscription_ended_reports_client_close_as_route_closed_by_caller() {
        let (consumer, _rx, mut subscription, _request) = watch_subscribed().await;
        consumer.close().await;
        assert_eq!(
            subscription.ended().await,
            SubscriptionEnd::RouteClosed {
                reason: RouteEndReason::ClosedByCaller
            }
        );
        assert!(subscription.closed().await.is_err());
    }

    #[test]
    fn drain_pending_channel_can_skip_subscriptions() {
        let mut pending = HashMap::new();
        let generation = 7;
        let channel = 11;
        let handle = RouteHandle::new(channel, 3, generation);
        let unary_key = PendingKey {
            generation,
            channel,
            epoch: handle.epoch,
            corr: 1,
        };
        let subscription_key = PendingKey {
            generation,
            channel,
            epoch: handle.epoch,
            corr: 2,
        };
        let (unary_tx, _unary_rx) = oneshot::channel();
        pending.insert(unary_key, PendingEntry::unary(unary_tx, false, None, None));

        let (events_tx, _events_rx) = mpsc::channel(1);
        let (closed_tx, _closed_rx) = oneshot::channel();
        let (ended_tx, _ended_rx) = watch::channel(None);
        let permit = Arc::new(Semaphore::new(1))
            .try_acquire_owned()
            .expect("test semaphore permit should be available");
        pending.insert(
            subscription_key,
            PendingEntry::subscription(
                events_tx,
                closed_tx,
                ended_tx,
                permit,
                Priority::Interactive,
            ),
        );

        let drained = drain_pending_handle(&mut pending, handle, false);
        assert_eq!(drained.len(), 1);
        assert!(pending.contains_key(&subscription_key));

        let drained = drain_pending_handle(&mut pending, handle, true);
        assert_eq!(drained.len(), 1);
        assert!(pending.is_empty());
    }

    fn response_frame(channel: u16, epoch: u32, corr: u64, body: Vec<u8>) -> Frame {
        Frame::build(
            FrameType::Response,
            Flags::new(false, Priority::Interactive, false),
            channel,
            epoch,
            corr,
            body,
        )
        .unwrap()
    }

    #[tokio::test]
    async fn stale_epoch_ingress_drops_without_settling_matching_corr() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, _rx) = mpsc::channel(4);
        let current = RouteHandle::new(9, 2, 1);
        let stale_key = PendingKey {
            generation: 1,
            channel: 9,
            epoch: 1,
            corr: 77,
        };
        let key = PendingKey {
            generation: 1,
            channel: 9,
            epoch: 2,
            corr: 77,
        };
        let (stale_tx, mut stale_response) = oneshot::channel();
        let (tx, mut response) = oneshot::channel();
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.route_epochs.insert(9, current);
            inner
                .pending
                .insert(stale_key, PendingEntry::unary(stale_tx, false, None, None));
            inner
                .pending
                .insert(key, PendingEntry::unary(tx, false, None, None));
        }

        assert!(dispatch_frame(&shared, 1, response_frame(9, 1, 77, b"stale".to_vec())).await);
        assert!(matches!(
            response.try_recv(),
            Err(oneshot::error::TryRecvError::Empty)
        ));
        assert!(matches!(
            stale_response.try_recv(),
            Err(oneshot::error::TryRecvError::Empty)
        ));
        assert!(shared.lock_inner().pending.contains_key(&stale_key));
        assert!(shared.lock_inner().pending.contains_key(&key));
        assert_eq!(shared.lock_inner().dropped_route_frames, 1);

        assert!(dispatch_frame(&shared, 1, response_frame(9, 2, 77, b"current".to_vec())).await);
        let PendingResult::Terminal(PendingTerminal::Response { body, .. }) =
            response.await.unwrap()
        else {
            panic!("current epoch must settle its own pending request");
        };
        assert_eq!(body, b"current");
        assert!(shared.lock_inner().pending.contains_key(&stale_key));
    }

    #[tokio::test]
    async fn route_poll_response_must_echo_expected_handle_before_settling() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, _rx) = mpsc::channel(4);
        let handle = RouteHandle::new(3, 9, 1);
        let key = PendingKey {
            generation: 1,
            channel: 0,
            epoch: 0,
            corr: 88,
        };
        let (tx, mut response) = oneshot::channel();
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.route_epochs.insert(handle.channel, handle);
            inner
                .pending
                .insert(key, PendingEntry::unary(tx, false, Some(handle), None));
        }
        let wrong = serde_json::to_vec(&ClientControlResponse::RoutePoll {
            route_channel: handle.channel,
            route_epoch: handle.epoch + 1,
            status: Some("wrong".to_string()),
            live: Some(true),
        })
        .unwrap();
        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, key.corr, wrong)).await);
        assert!(matches!(
            response.try_recv(),
            Err(oneshot::error::TryRecvError::Empty)
        ));
        assert!(shared.lock_inner().pending.contains_key(&key));

        let correct = serde_json::to_vec(&ClientControlResponse::RoutePoll {
            route_channel: handle.channel,
            route_epoch: handle.epoch,
            status: Some("ready".to_string()),
            live: Some(true),
        })
        .unwrap();
        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, key.corr, correct)).await);
        assert!(matches!(
            response.await.unwrap(),
            PendingResult::Terminal(PendingTerminal::Response { .. })
        ));
    }

    #[tokio::test]
    async fn stale_connection_handle_emits_no_request_cancel_or_goodbye() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(4);
        let stale = RouteHandle::new(4, 1, 1);
        let current = RouteHandle::new(4, 1, 2);
        {
            let mut inner = shared.lock_inner();
            inner.generation = 2;
            inner.writer = Some(writer);
            inner.route_epochs.insert(4, current);
        }

        let err = shared
            .send_request(RequestSend {
                binary: false,
                expected_handle: Some(stale),
                channel: stale.channel,
                epoch: stale.epoch,
                body: b"request".to_vec(),
                priority: Priority::Interactive,
                admission_class: AdmissionClass::Normal,
                deadline: Instant::now() + Duration::from_millis(10),
                retain_late_route_open: false,
                route_open_reverse_requests: None,
            })
            .await
            .unwrap_err();
        assert!(matches!(err, CallError::StaleRouteHandle(handle) if handle == stale));
        shared.send_cancel(stale, 8, Priority::Interactive);
        assert!(!shared.send_route_goodbye(stale, false));
        assert!(
            rx.try_recv().is_err(),
            "stale operations must not queue frames"
        );
    }

    #[tokio::test]
    async fn route_poll_refusal_preserves_daemon_code_message_and_detail() {
        let (shared, consumer, mut receiver) = route_open_stand_in(Box::new(|| 0.5));
        let handle = RouteHandle::new(3, 9, 1);
        shared
            .lock_inner()
            .route_epochs
            .insert(handle.channel, handle);
        let poll = consumer.poll_route(&handle, PollKind::Liveness, Duration::from_secs(1));
        tokio::pin!(poll);
        assert_pending(poll.as_mut()).await;
        let request = receiver.try_recv().unwrap();
        let refusal = ErrorBody {
            code: "unknown_route".into(),
            message: "the route is no longer present".into(),
            detail: Some(serde_json::json!({ "route_channel": 3, "route_epoch": 9 })),
        };
        assert!(
            dispatch_frame(
                &shared,
                1,
                channel_zero_frame(
                    FrameType::Error,
                    request.frame.header.corr,
                    serde_json::to_vec(&refusal).unwrap(),
                ),
            )
            .await
        );
        let err = poll.await.unwrap_err();
        assert_eq!(err.code(), Some("unknown_route"));
        let CallError::Module(body) = err else {
            panic!("a delivered refusal must not be classified as a send failure");
        };
        assert_eq!(body.code, refusal.code);
        assert_eq!(body.message, refusal.message);
        assert_eq!(body.detail, refusal.detail);
    }

    #[tokio::test]
    async fn late_route_open_queues_goodbye_and_full_queue_closes_connection() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(2);
        let key = PendingKey {
            generation: 1,
            channel: 0,
            epoch: 0,
            corr: 41,
        };
        let (tx, response) = oneshot::channel();
        drop(response);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner
                .pending
                .insert(key, PendingEntry::unary(tx, true, None, None));
        }
        let body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
            route_channel: 12,
            route_epoch: 7,
        })
        .unwrap();
        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, 41, body)).await);
        let cleanup = rx.recv().await.unwrap().frame;
        assert_eq!(cleanup.header.ty, FrameType::Goodbye);
        assert_eq!((cleanup.header.channel, cleanup.header.epoch), (12, 7));

        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions {
                reconnect_backoff: RetryBackoff {
                    max_attempts: 1,
                    ..RetryBackoff::default()
                },
                ..ConsumerOptions::default()
            },
        ));
        let (writer, _rx) = mpsc::channel(1);
        let filler = response_frame(0, 0, 1, Vec::new());
        writer
            .try_send(WriteCommand {
                frame: filler,
                pending: None,
            })
            .unwrap();
        let key = PendingKey {
            generation: 1,
            channel: 0,
            epoch: 0,
            corr: 42,
        };
        let (tx, response) = oneshot::channel();
        drop(response);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner
                .pending
                .insert(key, PendingEntry::unary(tx, true, None, None));
        }
        let body = serde_json::to_vec(&ClientControlResponse::RouteOpen {
            route_channel: 13,
            route_epoch: 8,
        })
        .unwrap();
        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, 42, body)).await);
        assert!(shared.lock_inner().writer.is_none());
    }

    #[tokio::test]
    async fn correlation_allocator_emits_max_once_then_closes_without_reuse() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions {
                reconnect_backoff: RetryBackoff {
                    max_attempts: 1,
                    ..RetryBackoff::default()
                },
                ..ConsumerOptions::default()
            },
        ));
        let (writer, mut rx) = mpsc::channel(4);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.next_corr = Some(u64::MAX);
        }
        let request_shared = Arc::clone(&shared);
        let request = tokio::spawn(async move {
            request_shared
                .send_request(RequestSend {
                    binary: false,
                    expected_handle: None,
                    channel: 0,
                    epoch: 0,
                    body: Vec::new(),
                    priority: Priority::Interactive,
                    admission_class: AdmissionClass::Normal,
                    deadline: Instant::now() + Duration::from_secs(1),
                    retain_late_route_open: false,
                    route_open_reverse_requests: None,
                })
                .await
        });
        let command = rx.recv().await.unwrap();
        assert_eq!(command.frame.header.corr, u64::MAX);
        assert!(dispatch_frame(&shared, 1, response_frame(0, 0, u64::MAX, Vec::new()),).await);
        assert!(request.await.unwrap().is_ok());

        let exhausted = shared
            .send_request(RequestSend {
                binary: false,
                expected_handle: None,
                channel: 0,
                epoch: 0,
                body: Vec::new(),
                priority: Priority::Interactive,
                admission_class: AdmissionClass::Normal,
                deadline: Instant::now() + Duration::from_millis(10),
                retain_late_route_open: false,
                route_open_reverse_requests: None,
            })
            .await
            .unwrap_err();
        assert!(matches!(exhausted, CallError::NotSent(_)));
        assert!(rx.try_recv().is_err());
        assert!(shared.lock_inner().writer.is_none());
    }

    #[tokio::test]
    async fn managed_call_deadline_bounds_flow_control_wait() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(4);
        let target = RouteTarget::ToolProvider {
            module_id: "flow-controlled".to_string(),
        };
        let identity = BindIdentity::new(
            PathBuf::from("/tmp/project"),
            "test".to_string(),
            "deadline".to_string(),
        );
        let consumer_identity = Some(ConsumerIdentity {
            module_id: "caller".to_string(),
            launch_nonce: "nonce".to_string(),
        });
        let first_opts = CallOptions {
            timeout: Duration::from_secs(1),
            consumer_identity: consumer_identity.clone(),
            ..CallOptions::default()
        };
        let second_opts = CallOptions {
            timeout: Duration::from_millis(25),
            consumer_identity,
            ..CallOptions::default()
        };
        let key = RouteKey::new(
            &target,
            &identity,
            first_opts.consumer_identity.as_ref(),
            None,
        );
        let handle = RouteHandle::new(5, 3, 1);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.cache_route(
                key,
                RouteState {
                    handle,
                    sem: Arc::new(Semaphore::new(1)),
                },
            );
        }

        let first = tokio::spawn({
            let consumer = SubcConsumer {
                shared: Arc::clone(&shared),
            };
            let target = target.clone();
            let identity = identity.clone();
            async move {
                consumer
                    .call(target, identity, b"first".to_vec(), first_opts)
                    .await
            }
        });
        let first_frame = rx
            .recv()
            .await
            .expect("the first request should enter the fake daemon queue");
        assert_eq!(first_frame.frame.header.ty, FrameType::Request);
        assert_eq!(first_frame.frame.body, b"first");
        assert!(shared.mark_pending_accepted(
            first_frame
                .pending
                .expect("request commands retain their pending key"),
        ));

        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let result = tokio::time::timeout(
            Duration::from_millis(250),
            consumer.call(target, identity, b"second".to_vec(), second_opts),
        )
        .await
        .expect("a flow-controlled call must finish at its own deadline")
        .unwrap_err();
        assert!(matches!(result, CallError::NotSent(_)));
        assert!(
            rx.try_recv().is_err(),
            "the timed-out second request must not reach the fake daemon"
        );

        first.abort();
        let _ = first.await;
    }

    #[tokio::test]
    async fn admitted_route_open_emits_one_frame_without_retrying_daemon_errors() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions {
                call_timeout: Duration::from_secs(1),
                ..ConsumerOptions::default()
            },
        ));
        let (writer, mut rx) = mpsc::channel(4);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
        }

        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let target = RouteTarget::ToolProvider {
            module_id: "admitted-target".to_string(),
        };
        let identity = BindIdentity::new(
            PathBuf::from("/tmp/project"),
            "test".to_string(),
            "admitted".to_string(),
        );
        let task = tokio::spawn(async move {
            consumer
                .open_route_with_admission_facts(
                    target,
                    identity,
                    serde_json::json!({"schema": 1, "verified_class": "member"}),
                )
                .await
        });

        let command = rx.recv().await.expect("one route.open must be queued");
        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
        let ClientControlRequest::RouteOpen {
            admission_facts, ..
        } = request
        else {
            panic!("expected route.open")
        };
        assert_eq!(
            admission_facts,
            Some(serde_json::json!({"schema": 1, "verified_class": "member"}))
        );

        let error_body = serde_json::to_vec(&ErrorBody {
            code: "admission_facts_not_permitted".to_string(),
            message: "not permitted".to_string(),
            detail: None,
        })
        .unwrap();
        assert!(
            dispatch_frame(
                &shared,
                1,
                Frame::build(
                    FrameType::Error,
                    Flags::new(false, Priority::Interactive, false),
                    0,
                    0,
                    command.frame.header.corr,
                    error_body,
                )
                .unwrap(),
            )
            .await
        );
        let result = task.await.unwrap();
        assert!(matches!(result, Err(CallError::NotSent(_))));
        assert!(rx.try_recv().is_err(), "one-shot route.open must not retry");
    }

    /// Drive one admitted route.open to success on a test writer and return the
    /// route.open request that was sent, the resolved handle, and the writer.
    async fn open_admitted_route_for_test(
        opts: Option<CallOptions>,
    ) -> (
        Arc<Shared>,
        SubcConsumer,
        ClientControlRequest,
        Result<RouteHandle, CallError>,
        mpsc::Receiver<WriteCommand>,
    ) {
        let shared = writer_test_shared();
        let (writer, mut rx) = mpsc::channel(8);
        let generation = {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.generation
        };
        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let target = RouteTarget::ToolProvider {
            module_id: "cerebellum".to_string(),
        };
        let identity = BindIdentity::new(
            PathBuf::from("/tmp/project"),
            "test".to_string(),
            "admitted".to_string(),
        );
        let facts = serde_json::json!({"schema": 1, "verified_class": "member"});
        // The consumer is returned from the task and kept alive by the caller:
        // dropping it closes the connection, after which no frame is dispatched.
        let task = tokio::spawn(async move {
            let result = match opts {
                Some(opts) => {
                    consumer
                        .open_route_with_admission_facts_and_options(target, identity, facts, opts)
                        .await
                }
                None => {
                    consumer
                        .open_route_with_admission_facts(target, identity, facts)
                        .await
                }
            };
            (consumer, result)
        });
        let command = rx.recv().await.expect("one route.open must be queued");
        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
        let response = serde_json::to_vec(&ClientControlResponse::RouteOpen {
            route_channel: 21,
            route_epoch: 4,
        })
        .unwrap();
        assert!(
            dispatch_frame(
                &shared,
                generation,
                Frame::build(
                    FrameType::Response,
                    Flags::new(false, Priority::Interactive, false),
                    0,
                    0,
                    command.frame.header.corr,
                    response,
                )
                .unwrap(),
            )
            .await
        );
        let (consumer, result) = tokio::time::timeout(Duration::from_secs(1), task)
            .await
            .expect("admitted route.open resolves")
            .unwrap();
        (shared, consumer, request, result, rx)
    }

    #[tokio::test]
    async fn admitted_route_open_refusal_keeps_the_daemon_code_and_detail() {
        let shared = writer_test_shared();
        let (writer, mut rx) = mpsc::channel(8);
        let generation = {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.generation
        };
        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let task = tokio::spawn(async move {
            let result = consumer
                .open_route_with_admission_facts(
                    RouteTarget::ToolProvider {
                        module_id: "cerebellum".to_string(),
                    },
                    BindIdentity::new(
                        PathBuf::from("/tmp/project"),
                        "test".to_string(),
                        "admitted".to_string(),
                    ),
                    serde_json::json!({"schema": 1, "verified_class": "member"}),
                )
                .await;
            (consumer, result)
        });
        let command = rx.recv().await.expect("one route.open must be queued");
        let refusal = ErrorBody {
            code: "module_warming".to_string(),
            message: "cerebellum is not ready".to_string(),
            detail: Some(serde_json::json!({"reason": "declared_not_ready"})),
        };
        assert!(
            dispatch_frame(
                &shared,
                generation,
                Frame::build(
                    FrameType::Error,
                    Flags::new(false, Priority::Interactive, false),
                    0,
                    0,
                    command.frame.header.corr,
                    serde_json::to_vec(&refusal).unwrap(),
                )
                .unwrap(),
            )
            .await
        );
        let (_consumer, result) = tokio::time::timeout(Duration::from_secs(1), task)
            .await
            .expect("admitted route.open resolves")
            .unwrap();
        let error = result.expect_err("a refused open is an error");
        assert!(
            error.is_not_sent(),
            "a refused open never reached the module: {error}"
        );
        let body = error
            .route_open_refusal()
            .unwrap_or_else(|| panic!("the refusal's code must survive: {error}"));
        assert_eq!(body.code, "module_warming");
        assert_eq!(
            body.detail,
            Some(serde_json::json!({"reason": "declared_not_ready"}))
        );
        assert!(
            error.to_string().contains("tool_provider:cerebellum"),
            "the error names its target: {error}"
        );
    }

    #[tokio::test]
    async fn admitted_route_without_options_opens_and_declares_no_reverse_capabilities() {
        let (_shared, _consumer, request, result, _rx) = open_admitted_route_for_test(None).await;
        let ClientControlRequest::RouteOpen {
            consumer_capabilities,
            admission_facts,
            ..
        } = request
        else {
            panic!("expected route.open")
        };
        assert_eq!(consumer_capabilities, None);
        assert!(admission_facts.is_some());
        let handle = result.expect("admitted route opens");
        assert_eq!((handle.channel, handle.epoch), (21, 4));
    }

    // An admitted route opened with handlers declares their capabilities and
    // delivers the provider's reverse requests to them, replying under the
    // provider's own correlation id: the browser plane's consent prompts arrive
    // as elicitation on exactly this kind of route.
    #[tokio::test]
    async fn admitted_route_with_options_delivers_elicitation_to_its_handler() {
        let opts = CallOptions::default();
        let seen = Arc::new(Mutex::new(None));
        let seen_by_handler = Arc::clone(&seen);
        let reply_body = br#"{"jsonrpc":"2.0","id":3,"result":{"action":"accept"}}"#.to_vec();
        let expected_reply = reply_body.clone();
        opts.reverse_requests
            .on_request("elicitation", move |body, ctx| {
                *seen_by_handler
                    .lock()
                    .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some((body, ctx.corr));
                let reply_body = reply_body.clone();
                async move { reply_body }
            })
            .unwrap();

        let (shared, _consumer, request, result, mut rx) =
            open_admitted_route_for_test(Some(opts)).await;
        let ClientControlRequest::RouteOpen {
            consumer_capabilities,
            admission_facts,
            ..
        } = request
        else {
            panic!("expected route.open")
        };
        assert_eq!(consumer_capabilities, Some(vec!["elicitation".to_string()]));
        assert_eq!(
            admission_facts,
            Some(serde_json::json!({"schema": 1, "verified_class": "member"}))
        );
        let handle = result.expect("admitted route opens");

        let request_body =
            br#"{"jsonrpc":"2.0","id":3,"method":"elicitation/create","params":{}}"#.to_vec();
        assert!(
            dispatch_frame(
                &shared,
                handle.connection_token(),
                reverse_request_frame(handle, 900, request_body.clone()),
            )
            .await
        );
        let reply = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("the handler replies")
            .unwrap()
            .frame;
        assert_eq!(reply.header.ty, FrameType::Response);
        assert_eq!(reply.header.corr, 900);
        assert_eq!(reply.header.channel, 21);
        assert_eq!(reply.body, expected_reply);
        assert_eq!(
            seen.lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .clone(),
            Some((request_body, 900))
        );
    }

    #[tokio::test]
    async fn route_open_waiter_deadline_is_not_sent_without_writing() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(4);
        let target = RouteTarget::ToolProvider {
            module_id: "single-flight".to_string(),
        };
        let identity = BindIdentity::new(
            PathBuf::from("/tmp/project"),
            "test".to_string(),
            "route-open".to_string(),
        );
        let opts = CallOptions {
            timeout: Duration::from_millis(25),
            consumer_identity: Some(ConsumerIdentity {
                module_id: "caller".to_string(),
                launch_nonce: "nonce".to_string(),
            }),
            ..CallOptions::default()
        };
        let key = RouteKey::new(&target, &identity, opts.consumer_identity.as_ref(), None);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.openings.insert(
                key,
                Opening {
                    waiters: Vec::new(),
                    closed: false,
                },
            );
        }

        let consumer = SubcConsumer { shared };
        let result = tokio::time::timeout(
            Duration::from_millis(250),
            consumer.open_route(target, identity, opts),
        )
        .await
        .expect("a route.open waiter must finish at its own deadline")
        .unwrap_err();
        assert!(matches!(result, CallError::NotSent(_)));
        assert!(
            rx.try_recv().is_err(),
            "a timed-out route.open waiter must not write a control frame"
        );
    }

    // A route.open whose control reply never arrives before the deadline has an
    // unknown outcome of its own (the daemon may have opened the channel), but
    // the managed call's request body was never written. The call and the
    // subscription must therefore report NotSent, not OutcomeUnknown: callers
    // use that distinction to decide whether a non-idempotent retry is safe.
    async fn managed_op_with_unanswered_route_open(subscribe: bool) -> CallError {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(4);
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
        }
        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let target = RouteTarget::ToolProvider {
            module_id: "slow-route-open".to_string(),
        };
        let identity = BindIdentity::new(
            PathBuf::from("/tmp/project"),
            "test".to_string(),
            "slow-route-open".to_string(),
        );
        let task = tokio::spawn(async move {
            if subscribe {
                consumer
                    .subscribe(
                        target,
                        identity,
                        b"{}".to_vec(),
                        SubscribeOptions {
                            route_open_timeout: Duration::from_millis(200),
                            route_retry_deadline: Duration::from_millis(100),
                            ..SubscribeOptions::default()
                        },
                    )
                    .await
                    .map(|_| ())
            } else {
                consumer
                    .call(
                        target,
                        identity,
                        b"{}".to_vec(),
                        CallOptions {
                            timeout: Duration::from_millis(200),
                            route_retry_deadline: Duration::from_millis(100),
                            ..CallOptions::default()
                        },
                    )
                    .await
                    .map(|_| ())
            }
        });

        // Play the writer task: accept the route.open onto the wire (so the
        // consumer knows the control frame left) and then never answer it,
        // which is what a daemon under load looks like from the client.
        let command = rx.recv().await.expect("route.open must be queued");
        assert_eq!(command.frame.header.channel, 0);
        let request: ClientControlRequest = serde_json::from_slice(&command.frame.body).unwrap();
        assert!(matches!(request, ClientControlRequest::RouteOpen { .. }));
        assert!(shared.mark_pending_accepted(command.pending.expect("route.open is tracked")));

        let err = tokio::time::timeout(Duration::from_secs(2), task)
            .await
            .expect("the managed op must settle at its own deadline")
            .unwrap()
            .expect_err("an unanswered route.open cannot yield a route");
        while let Ok(command) = rx.try_recv() {
            assert_eq!(
                command.frame.header.channel, 0,
                "no data-plane frame may be written without an open route"
            );
        }
        err
    }

    #[tokio::test]
    async fn call_whose_route_open_times_out_after_send_is_not_sent() {
        let err = managed_op_with_unanswered_route_open(false).await;
        assert!(
            matches!(err, CallError::NotSent(_)),
            "call body never left the client, got {err:?}"
        );
    }

    #[tokio::test]
    async fn subscribe_whose_route_open_times_out_after_send_is_not_sent() {
        let err = managed_op_with_unanswered_route_open(true).await;
        assert!(
            matches!(err, CallError::NotSent(_)),
            "subscription request never left the client, got {err:?}"
        );
    }

    #[tokio::test]
    async fn route_poll_deadline_bounds_writer_capacity() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(1);
        let handle = RouteHandle::new(8, 4, 1);
        writer
            .try_send(WriteCommand {
                frame: response_frame(0, 0, 99, Vec::new()),
                pending: None,
            })
            .expect("the fake daemon queue should accept its filler frame");
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.route_epochs.insert(handle.channel, handle);
        }

        let consumer = SubcConsumer { shared };
        let result = tokio::time::timeout(
            Duration::from_millis(250),
            consumer.poll_route(&handle, PollKind::Liveness, Duration::from_millis(25)),
        )
        .await
        .expect("a control request must finish at its own deadline")
        .unwrap_err();
        assert!(matches!(result, CallError::NotSent(_)));
        assert_eq!(
            rx.recv()
                .await
                .expect("the filler must still be the only queued frame")
                .frame
                .header
                .corr,
            99
        );
        assert!(
            rx.try_recv().is_err(),
            "the timed-out control request must not reach the fake daemon"
        );
    }

    #[tokio::test]
    async fn subscription_deadline_bounds_writer_capacity() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(1);
        let handle = RouteHandle::new(9, 2, 1);
        let route_sem = Arc::new(Semaphore::new(1));
        writer
            .try_send(WriteCommand {
                frame: response_frame(0, 0, 100, Vec::new()),
                pending: None,
            })
            .expect("the fake daemon queue should accept its filler frame");
        {
            let mut inner = shared.lock_inner();
            inner.writer = Some(writer);
            inner.cache_route(
                RouteKey::new(
                    &RouteTarget::ToolProvider {
                        module_id: "subscriptions".to_string(),
                    },
                    &BindIdentity::new(
                        PathBuf::from("/tmp/project"),
                        "test".to_string(),
                        "subscription".to_string(),
                    ),
                    None,
                    None,
                ),
                RouteState {
                    handle,
                    sem: Arc::clone(&route_sem),
                },
            );
        }

        let consumer = SubcConsumer { shared };
        let result = tokio::time::timeout(
            Duration::from_millis(250),
            consumer.subscribe_route(
                &handle,
                b"subscribe".to_vec(),
                SubscribeOptions {
                    route_open_timeout: Duration::from_millis(25),
                    ..SubscribeOptions::default()
                },
            ),
        )
        .await
        .expect("a subscription must finish at its route-open deadline");
        let result = match result {
            Ok(_) => panic!("a subscription blocked before writing must time out"),
            Err(err) => err,
        };
        assert!(matches!(result, CallError::NotSent(_)));
        assert_eq!(
            rx.recv()
                .await
                .expect("the filler must still be the only queued frame")
                .frame
                .header
                .corr,
            100
        );
        assert!(
            rx.try_recv().is_err(),
            "the timed-out subscription must not reach the fake daemon"
        );
        assert!(
            route_sem.try_acquire().is_ok(),
            "a pre-write subscription timeout must release its route credit"
        );
    }

    #[test]
    fn catalog_list_deserializes_golden_reply_and_ignores_unknown_fields() {
        let mut reply: serde_json::Value = serde_json::from_str(include_str!(
            "../../subc-control/tests/golden/client_control_response_catalog_list.json"
        ))
        .expect("the catalog.list golden reply must be valid JSON");
        reply["future_top_level"] = serde_json::json!(true);
        reply["modules"][0]["future_module_field"] = serde_json::json!("ignored");

        let catalog: CatalogList =
            serde_json::from_value(reply).expect("catalog.list should tolerate additive fields");
        assert_eq!(catalog.generation, 7);
        assert_eq!(catalog.modules.len(), 1);
        assert!(catalog.subc_ops.iter().any(|op| op == "catalog.list"));

        let tools = catalog.modules[0]
            .roles
            .iter()
            .find_map(|role| match role {
                subc_protocol::manifest::ProviderRole::ToolProvider { tools, .. } => Some(tools),
                _ => None,
            })
            .expect("the golden module must advertise a tool_provider role");
        let tool = tools
            .first()
            .expect("the golden tool_provider role must advertise a tool");
        assert!(!tool.name.is_empty());
        assert_eq!(
            tool.schema.get("type").and_then(serde_json::Value::as_str),
            Some("object")
        );
        assert!(matches!(
            tool.execution_mode,
            subc_protocol::manifest::ExecutionMode::Pure
        ));
    }

    #[tokio::test]
    async fn catalog_list_sends_an_unfiltered_channel_zero_request() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(1);
        shared.lock_inner().writer = Some(writer);

        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let request = tokio::spawn(async move { consumer.catalog_list().await });
        let command = rx
            .recv()
            .await
            .expect("catalog.list must queue a channel-0 request");
        assert_eq!(command.frame.header.channel, 0);
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "catalog.list");
        assert!(
            body.get("module_id").is_none(),
            "catalog.list must request the complete catalog without a module filter"
        );

        let response = serde_json::to_vec(&ClientControlResponse::CatalogList {
            generation: 9,
            modules: Vec::new(),
            subc_ops: vec!["catalog.list".to_string()],
        })
        .unwrap();
        assert!(
            dispatch_frame(
                &shared,
                1,
                response_frame(0, 0, command.frame.header.corr, response),
            )
            .await
        );
        let catalog = request.await.unwrap().unwrap();
        assert_eq!(catalog.generation, 9);
        assert!(catalog.modules.is_empty());
    }

    #[tokio::test]
    async fn spawn_snapshot_sends_a_channel_zero_request_and_returns_the_snapshot() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(1);
        shared.lock_inner().writer = Some(writer);

        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let request = tokio::spawn(async move { consumer.spawn_snapshot().await });
        let command = rx
            .recv()
            .await
            .expect("supervisor.spawn_snapshot must queue a channel-0 request");
        assert_eq!(command.frame.header.channel, 0);
        let body: serde_json::Value = serde_json::from_slice(&command.frame.body).unwrap();
        assert_eq!(body["op"], "supervisor.spawn_snapshot");

        let snapshot = SpawnSnapshot {
            cursor: SpawnCursor {
                daemon_incarnation: "incarnation-a".to_string(),
                seq: 41,
            },
            ring_bound: 256,
            live: vec![LiveSpawn {
                module_id: "participant".to_string(),
                spawn_generation: 3,
                pid: 4242,
                spawned_at_ms: 1_700_000_000_000,
            }],
        };
        let response = serde_json::to_vec(&ClientControlResponse::SupervisorSpawnSnapshot {
            snapshot: snapshot.clone(),
        })
        .unwrap();
        assert!(
            dispatch_frame(
                &shared,
                1,
                response_frame(0, 0, command.frame.header.corr, response),
            )
            .await
        );
        assert_eq!(request.await.unwrap().unwrap(), snapshot);
    }

    #[tokio::test]
    async fn spawn_snapshot_refusal_keeps_the_daemon_code() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/does-not-exist"),
            ConsumerOptions::default(),
        ));
        let (writer, mut rx) = mpsc::channel(1);
        shared.lock_inner().writer = Some(writer);

        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let request = tokio::spawn(async move { consumer.spawn_snapshot().await });
        let command = rx
            .recv()
            .await
            .expect("supervisor.spawn_snapshot must queue a channel-0 request");
        let refusal = serde_json::to_vec(&ErrorBody {
            code: "op_not_permitted".to_string(),
            message: "refused by the test".to_string(),
            detail: None,
        })
        .unwrap();
        let frame = Frame::build(
            FrameType::Error,
            Flags::new(false, Priority::Interactive, false),
            0,
            0,
            command.frame.header.corr,
            refusal,
        )
        .unwrap();
        assert!(dispatch_frame(&shared, 1, frame).await);
        let error = request.await.unwrap().unwrap_err();
        assert_eq!(error.code(), Some("op_not_permitted"));
    }

    fn spawn_cursor(seq: u64) -> SpawnCursor {
        SpawnCursor {
            daemon_incarnation: "incarnation-a".to_string(),
            seq,
        }
    }

    fn spawn_event(seq: u64, kind: SpawnEventKind, generation: u64) -> SpawnEvent {
        SpawnEvent {
            cursor: spawn_cursor(seq),
            kind,
            module_id: "participant".to_string(),
            spawn_generation: generation,
            pid: 4242,
            exit_code: (kind == SpawnEventKind::Exited).then_some(0),
            exit_signal: None,
        }
    }

    fn channel_zero_frame(ty: FrameType, corr: u64, body: Vec<u8>) -> Frame {
        Frame::build(
            ty,
            Flags::new(false, Priority::Interactive, false),
            0,
            0,
            corr,
            body,
        )
        .unwrap()
    }

    fn spawn_error_frame(corr: u64, code: &str, detail: serde_json::Value) -> Frame {
        channel_zero_frame(
            FrameType::Error,
            corr,
            serde_json::to_vec(&ErrorBody {
                code: code.to_string(),
                message: "sent by the test".to_string(),
                detail: Some(detail),
            })
            .unwrap(),
        )
    }

    /// A consumer over the writer-test harness, subscribed from `since`, with the
    /// request frame it queued.
    async fn spawn_subscribed(
        since: Option<SpawnCursor>,
    ) -> (
        Arc<Shared>,
        mpsc::Receiver<WriteCommand>,
        SpawnSubscription,
        Frame,
    ) {
        let shared = writer_test_shared();
        let (writer, mut rx) = mpsc::channel(8);
        shared.lock_inner().writer = Some(writer);
        let consumer = SubcConsumer {
            shared: Arc::clone(&shared),
        };
        let subscription = consumer
            .spawn_subscribe(since)
            .await
            .expect("supervisor.spawn_subscribe must be sent");
        std::mem::forget(consumer);
        let command = rx
            .recv()
            .await
            .expect("supervisor.spawn_subscribe must queue a channel-0 request");
        (shared, rx, subscription, command.frame)
    }

    #[tokio::test]
    async fn spawn_subscribe_sends_its_cursor_on_channel_zero_and_yields_events_until_stream_end() {
        let (shared, _rx, mut subscription, request) =
            spawn_subscribed(Some(spawn_cursor(7))).await;
        assert_eq!(request.header.channel, 0);
        assert_eq!(request.header.ty, FrameType::Request);
        let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
        assert_eq!(
            body,
            serde_json::json!({
                "op": "supervisor.spawn_subscribe",
                "since": {"daemon_incarnation": "incarnation-a", "seq": 7},
            })
        );

        let corr = request.header.corr;
        let events = [
            spawn_event(8, SpawnEventKind::Exited, 3),
            spawn_event(9, SpawnEventKind::Spawned, 4),
        ];
        for event in &events {
            let body = serde_json::to_vec(event).unwrap();
            assert!(
                dispatch_frame(
                    &shared,
                    1,
                    channel_zero_frame(FrameType::StreamData, corr, body)
                )
                .await
            );
        }
        assert!(
            dispatch_frame(
                &shared,
                1,
                channel_zero_frame(FrameType::StreamEnd, corr, Vec::new())
            )
            .await
        );
        assert_eq!(subscription.next().await.unwrap(), Some(events[0].clone()));
        assert_eq!(subscription.next().await.unwrap(), Some(events[1].clone()));
        assert_eq!(subscription.next().await.unwrap(), None);
        assert_eq!(
            subscription.next().await.unwrap(),
            None,
            "a finished stream stays finished"
        );
    }

    #[tokio::test]
    async fn spawn_subscribe_without_a_cursor_omits_since() {
        let (_shared, _rx, _subscription, request) = spawn_subscribed(None).await;
        let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
        assert_eq!(
            body,
            serde_json::json!({"op": "supervisor.spawn_subscribe"})
        );
    }

    #[tokio::test]
    async fn spawn_cursor_refusals_surface_as_coded_errors_with_their_detail() {
        let (shared, _rx, mut subscription, request) =
            spawn_subscribed(Some(spawn_cursor(7))).await;
        let frame = spawn_error_frame(
            request.header.corr,
            "spawn_cursor_incarnation_mismatch",
            serde_json::json!({"current_daemon_incarnation": "incarnation-b"}),
        );
        assert!(dispatch_frame(&shared, 1, frame).await);
        let error = subscription.next().await.unwrap_err();
        assert_eq!(error.code(), Some("spawn_cursor_incarnation_mismatch"));
        let SpawnStreamError::CursorIncarnationMismatch {
            current_daemon_incarnation,
            body,
        } = &error
        else {
            panic!("expected the incarnation refusal, got {error:?}");
        };
        assert_eq!(current_daemon_incarnation, "incarnation-b");
        assert_eq!(body.code, "spawn_cursor_incarnation_mismatch");
        assert_eq!(subscription.next().await.unwrap(), None);

        let (shared, _rx, mut subscription, request) =
            spawn_subscribed(Some(spawn_cursor(1))).await;
        let frame = spawn_error_frame(
            request.header.corr,
            "spawn_cursor_too_old",
            serde_json::json!({"oldest_retained_cursor": spawn_cursor(90)}),
        );
        assert!(dispatch_frame(&shared, 1, frame).await);
        let error = subscription.next().await.unwrap_err();
        assert_eq!(error.code(), Some("spawn_cursor_too_old"));
        let SpawnStreamError::CursorTooOld {
            oldest_retained_cursor,
            ..
        } = &error
        else {
            panic!("expected the too-old refusal, got {error:?}");
        };
        assert_eq!(oldest_retained_cursor, &spawn_cursor(90));
    }

    #[tokio::test]
    async fn a_lagged_spawn_stream_yields_its_queued_events_then_the_lag_error() {
        let (shared, _rx, mut subscription, request) =
            spawn_subscribed(Some(spawn_cursor(7))).await;
        let corr = request.header.corr;
        let queued = spawn_event(8, SpawnEventKind::Exited, 3);
        assert!(
            dispatch_frame(
                &shared,
                1,
                channel_zero_frame(
                    FrameType::StreamData,
                    corr,
                    serde_json::to_vec(&queued).unwrap()
                ),
            )
            .await
        );
        let frame = spawn_error_frame(
            corr,
            "spawn_subscriber_lagged",
            serde_json::json!({"first_undelivered_cursor": spawn_cursor(9)}),
        );
        assert!(dispatch_frame(&shared, 1, frame).await);
        assert_eq!(subscription.next().await.unwrap(), Some(queued));
        let error = subscription.next().await.unwrap_err();
        assert_eq!(error.code(), Some("spawn_subscriber_lagged"));
        let SpawnStreamError::SubscriberLagged {
            first_undelivered_cursor,
            ..
        } = &error
        else {
            panic!("expected the lag error, got {error:?}");
        };
        assert_eq!(first_undelivered_cursor, &spawn_cursor(9));
    }

    #[tokio::test]
    async fn dropping_a_spawn_subscription_sends_a_channel_zero_cancel_for_its_corr() {
        let (_shared, mut rx, subscription, request) =
            spawn_subscribed(Some(spawn_cursor(7))).await;
        drop(subscription);
        let cancel = tokio::time::timeout(Duration::from_secs(1), rx.recv())
            .await
            .expect("dropping the subscription must queue a Cancel")
            .expect("the writer stays open");
        assert_eq!(cancel.frame.header.ty, FrameType::Cancel);
        assert_eq!(cancel.frame.header.channel, 0);
        assert_eq!(cancel.frame.header.corr, request.header.corr);
    }

    #[tokio::test]
    async fn reconnect_completion_between_wait_decision_and_registration_wakes_caller() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/subc-client-rs-reconnect-wakeup"),
            ConsumerOptions::default(),
        ));
        let (sender, _receiver) = mpsc::channel(EGRESS_BUFFER);
        {
            let mut inner = shared.lock_inner();
            inner.reconnect = ReconnectState::Inline {
                generation: inner.generation,
            };
        }
        let completing = Arc::clone(&shared);
        *shared.before_wait.lock().unwrap() = Some(Box::new(move || {
            completing.lock_inner().writer = Some(sender);
            completing.notify.notify_waiters();
        }));

        let result = shared
            .ensure_connected_for_call(Instant::now() + Duration::from_millis(30))
            .await;
        assert!(
            result.is_ok(),
            "connected caller should not time out: {result:?}"
        );
        assert!(shared.before_wait.lock().unwrap().is_none());
    }

    #[tokio::test]
    async fn catalog_list_deadline_is_not_sent_when_reconnection_stays_down() {
        let shared = Arc::new(Shared::new(
            PathBuf::from("/tmp/subc-client-rs-catalog-list-unavailable"),
            ConsumerOptions {
                call_timeout: Duration::from_millis(25),
                reconnect_backoff: RetryBackoff {
                    base: Duration::from_millis(1),
                    cap: Duration::from_millis(1),
                    max_attempts: 100,
                },
                ..ConsumerOptions::default()
            },
        ));
        let consumer = SubcConsumer { shared };
        let result = tokio::time::timeout(Duration::from_millis(250), consumer.catalog_list())
            .await
            .expect("catalog.list must finish at its configured deadline")
            .unwrap_err();
        assert!(matches!(result, CallError::NotSent(_)));
    }

    fn consumer_with_malformed_connection_file(
    ) -> (cortexkit_test_support::ScratchDir, SubcConsumer) {
        let temp = cortexkit_test_support::ScratchDir::new("consumer-malformed-connection");
        let path = temp.path().join("connection.json");
        std::fs::write(&path, b"not JSON").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
        }
        let shared = Arc::new(Shared::new(
            path,
            ConsumerOptions {
                call_timeout: Duration::from_millis(100),
                reconnect_backoff: RetryBackoff {
                    base: Duration::from_millis(20),
                    cap: Duration::from_millis(40),
                    max_attempts: 6,
                },
                ..ConsumerOptions::default()
            },
        ));
        (temp, SubcConsumer { shared })
    }

    // A malformed file fails synchronously. Keep the clock running so an unpaced
    // retry loop reaches its deadline instead of hanging a paused-time runtime.
    #[tokio::test]
    async fn catalog_list_backs_off_after_malformed_connection_file_and_close_cancels_it() {
        let (_temp, consumer) = consumer_with_malformed_connection_file();
        let call = consumer.catalog_list();
        tokio::pin!(call);
        assert_pending(call.as_mut()).await;
        consumer.close().await;
        let err = call.await.unwrap_err();
        assert!(matches!(err, CallError::NotSent(_)));
        assert!(err.to_string().contains("consumer closed"));
    }

    #[tokio::test]
    async fn spawn_snapshot_backs_off_after_malformed_connection_file_and_close_cancels_it() {
        let (_temp, consumer) = consumer_with_malformed_connection_file();
        let call = consumer.spawn_snapshot();
        tokio::pin!(call);
        assert_pending(call.as_mut()).await;
        consumer.close().await;
        let err = call.await.unwrap_err();
        assert!(matches!(err, CallError::NotSent(_)));
        assert!(err.to_string().contains("consumer closed"));
    }
}

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

    const NONCE: &str = "nonce-f00dfeed1234abcd";

    #[test]
    fn option_types_and_route_keys_never_print_the_nonce() {
        let identity = ConsumerIdentity {
            module_id: "wernicke".to_string(),
            launch_nonce: NONCE.to_string(),
        };
        let call = CallOptions {
            consumer_identity: Some(identity.clone()),
            ..CallOptions::default()
        };
        let key = ConsumerIdentityKey::from(&identity);
        for printed in [format!("{call:?}"), format!("{key:?}")] {
            assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
        }
    }
}