net-mesh 0.36.0

High-performance, schema-agnostic, backend-agnostic event bus
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
//! `Mesh::serve_rpc` / `Mesh::call` glue — the wire-up between
//! `MeshNode`'s pub/sub + per-channel-hash dispatch hook and the
//! `cortex::rpc` server / client folds.
//!
//! See `docs/internal/misc/NRPC_DESIGN.md` for the full architectural framing.
//! In short:
//!
//! - `serve_rpc(service, handler)` registers an inbound dispatcher
//!   for `<service>.requests`'s channel hash. The dispatcher pushes
//!   inbound REQUEST/CANCEL events through the
//!   [`crate::adapter::net::cortex::RpcServerFold`], which spawns
//!   the user handler. The fold's emit closure publishes RESPONSE
//!   events on `<service>.replies.<caller_origin>` via
//!   [`MeshNode::publish`].
//!
//! - `call(target, service, payload, opts)` allocates a `call_id`,
//!   registers a oneshot in the per-Mesh `RpcClientPending`,
//!   subscribes to its own reply channel from `target` (lazy,
//!   cached), publishes the REQUEST envelope on `<service>.requests`,
//!   awaits the oneshot. Drop sends a CANCEL.
//!
//! Phase 1 surface — direct entity-to-entity addressing
//! (`call(target_node_id, ...)`), no service discovery layer yet.
//! Phase 2 will add `call_service(name, ...)` over the existing
//! capability-announcement registry.

use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU8, Ordering};
use std::sync::Arc;
use std::time::Instant;

use bytes::Bytes;
use parking_lot::Mutex;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;

use super::channel::{ChannelHash, ChannelId, ChannelName, ChannelPublisher, PublishConfig};
use super::mesh_rpc_metrics::{CallMetricsGuard, CallOutcome, ServiceMetricsAtomic};
use crate::adapter::net::cortex::{
    build_trace_headers, encode_request_grant, encode_rpc_route, encode_stream_grant,
    parse_request_window_initial, peek_request_service, EventMeta, RpcAsyncResponseEmitter,
    RpcCancellationToken, RpcClientFold, RpcClientStreamingHandler, RpcContext, RpcDuplexFold,
    RpcDuplexHandler, RpcHandler, RpcHandlerError, RpcInboundDispatcher, RpcInboundEvent,
    RpcRequestChunkPayload, RpcRequestGrantEmitter, RpcRequestPayload, RpcResponseEmitter,
    RpcResponsePayload, RpcServerFold, RpcServerStreamingFold, RpcStatus, RpcStreamingHandler,
    RpcStreamingRequestFold, StreamItem, TraceContext, DISPATCH_RPC_CANCEL, DISPATCH_RPC_REQUEST,
    DISPATCH_RPC_REQUEST_CHUNK, DISPATCH_RPC_REQUEST_GRANT, DISPATCH_RPC_STREAM_GRANT,
    EVENT_META_SIZE, FLAG_RPC_CLIENT_STREAMING_REQUEST, FLAG_RPC_PROPAGATE_TRACE,
    FLAG_RPC_REQUEST_END, FLAG_RPC_STREAMING_RESPONSE, HEADER_NRPC_REQUEST_WINDOW_INITIAL,
    HEADER_NRPC_STREAM_WINDOW_INITIAL, RPC_FRAME_BODY_OFFSET, RPC_ROUTE_V1_SIZE,
};
use crate::error::AdapterError;

use super::behavior::org::{OrgId, OrgMembershipCert};
use super::behavior::org_admission::OrgAdmission;
use super::behavior::org_call::{OrgCallProof, MAX_ORG_PROOF_TTL_SECS, ORG_ADMISSION_HEADER};
use super::behavior::org_grant::{CapabilityAuthorityId, OrgCapabilityGrant, OrgDispatcherGrant};
use super::mesh::{MeshNode, PeerPublishOutcome, ReplySubscription};
use super::org_admission_gate::{
    org_request_digest, CapabilityVisibility, OrgProviderPolicy, RegisteredRpcService,
};
use super::subnet::SubnetExportBinding;

// ============================================================================
// Public types.
// ============================================================================

/// How `Mesh::call_service` picks a target from the set of nodes
/// advertising the requested service.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum RoutingPolicy {
    /// Naive round-robin via the per-Mesh `call_id` counter.
    /// Distributes calls evenly across candidates regardless of
    /// load. The default.
    #[default]
    RoundRobin,
    /// Pick a candidate at random per call. Stateless, cheap, and
    /// gives even distribution under independent calls.
    Random,
    /// Consistent-hash to a target by `key`. Same `key` always
    /// hits the same target as long as the candidate set is
    /// stable. Useful for session affinity (route a given
    /// conversation / shard / user to the same backend).
    Sticky {
        /// Caller-supplied identifier — hash maps this to the
        /// target. Use a session id, shard key, or conversation
        /// id depending on the application.
        key: u64,
    },
    /// Pick the candidate with the smallest measured `latency_us`
    /// per the local `ProximityGraph`. Candidates the proximity
    /// graph hasn't observed yet (no entity ↔ node_id mapping or
    /// no pingwave received) sort to the bottom — better to pick
    /// a known-fast node than gamble on an unknown one.
    ///
    /// Falls back deterministically to the first sorted candidate
    /// when no candidates have proximity data, so a freshly-
    /// discovered service still routes consistently.
    LowestLatency,
}

/// Options for [`MeshNode::call`] and [`MeshNode::call_service`].
#[derive(Debug, Clone)]
pub struct CallOptions {
    /// Hard deadline for the call. The future returned by `call`
    /// races a `tokio::time::sleep_until`; whichever fires first
    /// wins. On timeout the caller emits a CANCEL event for
    /// `call_id` so the server can drop the in-flight handler.
    /// `None` means no deadline; the caller waits indefinitely
    /// (or until the future is dropped).
    pub deadline: Option<Instant>,
    /// How `call_service` picks a target. Ignored by `call`
    /// (which takes an explicit `target_node_id`). Default:
    /// `RoundRobin`.
    pub routing_policy: RoutingPolicy,
    /// Skip candidates whose `ProximityGraph` entry reports
    /// `!is_available()` (i.e. `Unhealthy` or `Unknown`).
    /// Default `true`. Candidates with no proximity entry at all
    /// are KEPT — absence of evidence is not evidence of
    /// unhealth, and a freshly-announced service shouldn't be
    /// filtered just because pingwaves haven't propagated yet.
    pub filter_unhealthy: bool,
    /// W3C Trace Context to propagate to the server. When `Some`,
    /// the call sets `FLAG_RPC_PROPAGATE_TRACE` on the request and
    /// emits `traceparent` / `tracestate` headers; the server's
    /// `RpcContext::trace_context` will be populated with the same
    /// values. nRPC is transport-only — application code on both
    /// sides reads / writes this via whatever tracing backend it
    /// has wired up (tracing-opentelemetry, Datadog, etc.).
    pub trace_context: Option<TraceContext>,
    /// Per-call concurrency cap. Future Phase 2 work; v1 ignores
    /// this and the per-Mesh `RpcClientPending` doesn't bound
    /// in-flight count.
    pub max_in_flight_per_target: u32,
    /// **Streaming responses only.** Initial credit window for
    /// per-streaming-response flow control. When `Some(n)`, the
    /// caller emits `nrpc-stream-window-initial: n` on the
    /// REQUEST and the server's pump task awaits one credit per
    /// emitted chunk. The returned [`RpcStream`] auto-grants 1
    /// credit per consumed chunk so the in-flight credit holds
    /// near `n` (or use [`RpcStream::grant`] for batched / custom
    /// cadence). `None` (the default) → unbounded: server pumps
    /// chunks as fast as the publish path can take them
    /// (back-compat / pre-flow-control behavior). Ignored by
    /// non-streaming `call` / `call_service`.
    pub stream_window_initial: Option<u32>,
    /// **Client-streaming / duplex only.** Initial credit window
    /// for per-call request-direction flow control. Mirror of
    /// [`Self::stream_window_initial`] for the upload direction. When
    /// `Some(n)`, the caller emits `nrpc-request-window-initial: n`
    /// on the REQUEST and its `send().await` sink awaits one
    /// credit per pushed chunk; the server refills via
    /// [`DISPATCH_RPC_REQUEST_GRANT`] events. `None` → unbounded:
    /// caller's send sink doesn't block (legacy / fast-path).
    /// Ignored by unary `call` / `call_streaming`.
    ///
    /// Bidi streaming plan (Phase C).
    pub request_window_initial: Option<u32>,
    /// Caller-supplied request headers. Appended to the wire
    /// `RpcRequestPayload::headers` after any auto-generated
    /// headers (trace context, stream-window). Useful for
    /// application-level metadata the server needs at
    /// dispatch-time — e.g., the `net-where` predicate
    /// header (Phase 9b of `CAPABILITY_SYSTEM_SDK_PLAN.md`) that
    /// services consult for predicate-pushdown filtering.
    ///
    /// Each entry is `(name, value_bytes)`. Names use the lowercase
    /// `cyberdeck-*` / `nrpc-*` convention; the substrate doesn't
    /// validate names beyond the `MAX_RPC_HEADER_NAME_LEN` cap
    /// enforced at encode time.
    ///
    /// Default: empty.
    pub request_headers: Vec<(String, Vec<u8>)>,
    /// Caller-side cancel token. Mint via
    /// [`MeshNode::reserve_cancel_token`]; pair with
    /// [`MeshNode::cancel`] from any thread to abort the in-flight
    /// call. `None` (or `Some(0)` — the "no token" sentinel) → no
    /// cancel slot is reserved and the call has no external abort
    /// path beyond Drop-on-future-cancellation.
    ///
    /// Honored uniformly by every call shape: `call`, `call_service`,
    /// `call_streaming`, `call_client_stream`, `call_duplex`. The
    /// substrate registers the token in a per-mesh cancel registry
    /// at call construction and removes it on resolution (success,
    /// error, or Drop). A cancel that fires mid-flight surfaces to
    /// the caller as [`RpcError::Cancelled`] and emits CANCEL on
    /// the wire via the existing per-call-shape guards (UnaryCallGuard,
    /// ClientStreamCallRaw::Drop, DuplexCallRaw::Drop).
    ///
    /// Cancel-before-register is race-safe: a cancel that arrives
    /// in the gap between `reserve_cancel_token` and the call's
    /// internal register step latches a pre-cancel flag on the
    /// registry's orphan entry; the subsequent register observes
    /// it and the call short-circuits to [`RpcError::Cancelled`]
    /// without ever publishing the REQUEST.
    pub cancel_token: Option<u64>,
    /// E2.1: when set, the unary [`MeshNode::call`] mints an org-admission proof
    /// over the finalized request and appends the `net-org-admission` header, so
    /// a PROTECTED provider's admission gate can verify the call. `None` (the
    /// default) → an ordinary public call. Protected admission is unary-only
    /// (E1.8): the streaming / duplex call shapes do NOT silently ignore an
    /// intent set here — they REJECT it with a local [`RpcError::Codec`] error
    /// (fail-loud), so a credential can never be dropped on the floor.
    pub org_proof_intent: Option<OrgProofIntent>,
}

impl Default for CallOptions {
    fn default() -> Self {
        Self {
            deadline: None,
            routing_policy: RoutingPolicy::default(),
            filter_unhealthy: true,
            trace_context: None,
            max_in_flight_per_target: 64,
            stream_window_initial: None,
            request_window_initial: None,
            request_headers: Vec::new(),
            cancel_token: None,
            org_proof_intent: None,
        }
    }
}

/// Caller credentials for minting an org-admission proof inside the unary
/// [`MeshNode::call`] (E2.1) — the minimal honest caller seam, not the full
/// grant-management CLI (OA2-F). Set it on [`CallOptions::org_proof_intent`] to
/// call a PROTECTED service: `call` mints the `call_id`, finalizes the request,
/// computes the shared
/// [`org_request_digest`],
/// signs an [`OrgCallProof`] binding THIS call, and appends the
/// `net-org-admission` header. Protected admission is unary-only (E1.8).
#[derive(Clone)]
pub struct OrgProofIntent {
    /// The caller's signing keypair (actor S). `Arc`-held so `CallOptions`
    /// stays `Clone` without cloning key material.
    pub caller: Arc<crate::adapter::net::identity::EntityKeypair>,
    /// The caller's org membership certificate.
    pub membership: OrgMembershipCert,
    /// The dispatcher grant empowering the caller to act for its org over the
    /// invoked capability.
    pub dispatcher: OrgDispatcherGrant,
    /// The cross-org capability grant (for [`OrgAdmission::CrossOrgGranted`]);
    /// `None` for [`OrgAdmission::OwnerDelegated`].
    pub capability_grant: Option<OrgCapabilityGrant>,
    /// The org the caller acts for (A).
    pub acting_org: OrgId,
    /// The provider's owner org (B) the proof is addressed to.
    pub provider_owner_org: OrgId,
    /// The exact provider (P) this call targets.
    pub provider: crate::adapter::net::identity::EntityId,
    /// The invoked capability (`nrpc:<service>`).
    pub capability: CapabilityAuthorityId,
    /// Proof lifetime in seconds from `call` time.
    pub proof_ttl_secs: u64,
}

impl std::fmt::Debug for OrgProofIntent {
    /// Redacts the keypair + credentials — an intent must never print key or
    /// certificate material into a log line.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OrgProofIntent")
            .field("acting_org", &self.acting_org)
            .field("provider_owner_org", &self.provider_owner_org)
            .field("provider", &self.provider)
            .field("capability", &self.capability)
            .field("proof_ttl_secs", &self.proof_ttl_secs)
            .field("credentials", &"<redacted>")
            .finish()
    }
}

/// What [`MeshNode::call`] returns on success.
#[derive(Debug, Clone)]
pub struct RpcReply {
    /// Response payload from the server's handler. Caller decodes
    /// according to its application protocol.
    pub body: Bytes,
    /// Headers attached by the server's response.
    pub headers: Vec<(String, Vec<u8>)>,
    /// Wall-clock latency from `call(...)` to RESPONSE arrival.
    pub latency_ns: u64,
}

/// What [`MeshNode::call`] returns on failure.
#[derive(Debug, thiserror::Error)]
pub enum RpcError {
    /// No subscription / no route to the target. Either
    /// `target_node_id` is unknown to the local mesh, or the
    /// caller's reply-channel subscription couldn't be set up.
    #[error("no route to target {target:#x}: {reason}")]
    NoRoute {
        /// Target node id the call was directed at.
        target: u64,
        /// Diagnostic — typically the underlying transport error.
        reason: String,
    },
    /// Caller's deadline elapsed before a RESPONSE arrived. The
    /// caller emits a CANCEL on timeout so the server can drop
    /// the in-flight handler; this variant is returned to the
    /// awaiting caller.
    #[error("timeout after {elapsed_ms}ms")]
    Timeout {
        /// Wall-clock milliseconds elapsed before timeout fired.
        elapsed_ms: u64,
    },
    /// Server returned a non-`Ok` status. Body carries the
    /// server's diagnostic (UTF-8) when available.
    #[error("server returned status {status:#06x}: {message}")]
    ServerError {
        /// Wire-level `RpcStatus` value the server returned.
        status: u16,
        /// UTF-8 diagnostic from the response body, when the body
        /// decodes as valid UTF-8; otherwise hex-truncated.
        message: String,
        /// Reply headers from the error response — the wire has always
        /// carried them (same frame field as success replies); the
        /// caller used to discard them here. Empty when the server
        /// attached none. The message stays the human diagnostic;
        /// headers are the structured sidecar channel (e.g. a
        /// `net-failure-schematic` verdict).
        headers: Vec<(String, Vec<u8>)>,
    },
    /// Underlying transport error (publish failure, encryption,
    /// etc.).
    #[error("transport: {0}")]
    Transport(#[from] AdapterError),
    /// Client-local serialization or deserialization failure.
    /// `direction = Encode` means the typed wrapper failed to
    /// encode the request before it ever hit the wire;
    /// `direction = Decode` means the response landed but the
    /// typed wrapper failed to decode it. Either way this is a
    /// caller-fixable bug (wrong codec, schema drift, malformed
    /// `Serialize` impl) — NOT a transient infra failure — so
    /// retry / circuit-breaker predicates skip it by default.
    #[error("codec ({direction:?}): {message}")]
    Codec {
        /// Which side of the call the codec failure happened on.
        direction: CodecDirection,
        /// Decode/encode diagnostic from the underlying serde impl.
        message: String,
    },
    /// v0.4 capability-auth gate denied the call. Either the
    /// target's latest `CapabilityAnnouncement` does not list
    /// the requested `nrpc:<service>` tag, or it lists the tag
    /// with allow-lists the caller does not match. See
    /// `docs/internal/plans/CAPABILITY_AUTH_PLAN.md` §3 for the model.
    ///
    /// Raised by the caller-side gate inside
    /// [`MeshNode::call_service`] BEFORE the request hits the
    /// wire, and surfaced by the caller on receipt of a
    /// `RpcStatus::CapabilityDenied` response (the callee-side
    /// defense-in-depth path).
    #[error("capability denied: target {target:#x} does not authorize nrpc:{capability}")]
    CapabilityDenied {
        /// Target node id the gate denied.
        target: u64,
        /// Service / capability tag (without the `nrpc:` prefix)
        /// the gate denied.
        capability: String,
    },
    /// Caller-side cancellation fired via
    /// [`MeshNode::cancel`] with the call's `cancel_token`.
    /// Triggers a Drop-on-cancel CANCEL frame on the wire so the
    /// server's in-flight handler observes the cancel; the
    /// awaiting caller returns this variant. NOT retried by the
    /// default retry policy — cancellation is caller-driven and
    /// re-issuing the call defeats the point.
    #[error("call cancelled by caller")]
    Cancelled,
}

/// Which side of the call surfaced a [`RpcError::Codec`] failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodecDirection {
    /// Encoding the outbound request failed before the call was issued.
    Encode,
    /// Decoding the inbound response failed after the call returned Ok.
    Decode,
}

/// RAII handle returned by [`MeshNode::serve_rpc`]. Dropping it
/// unregisters the inbound dispatcher and removes the service
/// from the local-services registry (so subsequent
/// `announce_capabilities` calls stop emitting the
/// `nrpc:<service>` tag).
///
/// **Bridge task lifecycle.** The bridge task that drains the
/// inbound mpsc into the fold is NOT aborted on Drop. The
/// `register_rpc_inbound` dispatcher closure owns the only
/// `mpsc::Sender` clone, so `unregister_rpc_inbound` (which drops
/// the dispatcher) closes the channel; the bridge's `rx.recv()`
/// then yields `None` and the task exits cleanly after draining
/// any queued events. Aborting would race events that are
/// mid-`fold.lock().apply()` — those events would be killed
/// without their RESPONSE being emitted, so the corresponding
/// callers would just time out.
///
/// Outstanding handler executions (already-spawned tokio tasks)
/// continue to completion regardless.
pub struct ServeHandle {
    /// Channel hash to unregister on Drop.
    channel_hash: ChannelHash,
    /// OA2-E0.1: the registration id this handle owns. Drop passes
    /// it to `unregister_rpc_inbound`, which removes the dispatcher
    /// ONLY if the id still matches — so a stale handle whose
    /// registration was already torn down and replaced cannot evict
    /// the newer registration.
    registration_id: u64,
    /// Service name to remove from `rpc_local_services` on Drop.
    service: String,
    /// The bridge task. Held only so callers can introspect /
    /// detach it; Drop does NOT abort it (see struct doc-comment).
    /// Detaches naturally when the handle is dropped — the bridge
    /// exits on its own once the dispatcher's `mpsc::Sender` is
    /// dropped via `unregister_rpc_inbound`.
    _bridge: JoinHandle<()>,
    /// The per-service response drainer task (unary `serve_rpc` only;
    /// `None` for the streaming/duplex variants, which still spawn per
    /// emit). Like `_bridge`, held only to detach — it exits on its own
    /// once the emit closure (the sole `Sender` owner, dropped when the
    /// bridge task ends and the fold drops) is gone. See §8a.
    _response_drain: Option<JoinHandle<()>>,
    /// Hold an Arc back to the mesh so we can unregister on Drop
    /// without the mesh having to track us.
    mesh: Arc<MeshNode>,
    /// Test-only handle to this bridge's authenticated response-route cache
    /// (the per-serve `origin_node_cache`), so a witness can DETERMINISTICALLY
    /// assert that a rejected frame (origin mismatch / relayed) left no cached
    /// route — the one preflight-side state a drop could otherwise touch.
    #[cfg(test)]
    origin_node_cache: RpcOriginNodeCache,
}

impl Drop for ServeHandle {
    fn drop(&mut self) {
        // Order matters: unregister the dispatcher FIRST so no new
        // events can land in the bridge's mpsc, THEN drop the
        // service-tag entry. The bridge task drains any in-flight
        // events naturally and exits when its `rx.recv()` yields
        // `None` (which happens as soon as the dispatcher closure
        // — the sole `tx` owner — is dropped above).
        self.mesh
            .unregister_rpc_inbound(self.channel_hash, self.registration_id);
        // OA2-E0.2 P1: token-owned retirement. Remove the service tag
        // ONLY if it still belongs to THIS registration. A handle
        // preempted between the dispatcher-unregister above and here,
        // while a replacement `serve_rpc` re-registered the freed slot
        // and reinstalled the tag under a new id, must NOT evict the
        // replacement's live tag by name.
        self.mesh
            .rpc_local_services_arc()
            .remove_if(&self.service, self.registration_id);
    }
}

/// OA2-E0.2 P0 — cross-service confused-deputy guard for the serve
/// bridges.
///
/// The route discriminator (E0.2) already selected THIS service's
/// dispatcher by canonical channel hash. But the initial REQUEST
/// payload carries its own self-declared `service` field, and the
/// server folds route to their handler without re-checking it. A
/// frame physically delivered to `admin.requests` whose payload
/// names `echo` would otherwise run the admin handler under an
/// `echo` request — a cross-service confused deputy.
///
/// Returns `true` when `frame` is an initial `DISPATCH_RPC_REQUEST`
/// whose payload names a service OTHER than `expected` and must be
/// dropped BEFORE the capability gate or any fold/handler state.
/// Returns `false` for:
///   * control frames (CANCEL / CHUNK / GRANT) — they carry no
///     service and inherit the route-selected active call;
///   * a REQUEST whose payload names exactly `expected`;
///   * a REQUEST whose service field is unreadable — the fold's own
///     full decode then rejects it (`UnknownVersion`), so no handler
///     runs and the caller still gets a diagnostic (rather than a
///     silent drop here that mimics a timeout);
///   * a frame too short to even carry the `EventMeta` — the fold
///     drops those too.
fn is_cross_service_request(frame: &[u8], expected: &str) -> bool {
    let Some(meta) = (if frame.len() >= EVENT_META_SIZE {
        EventMeta::from_bytes(&frame[..EVENT_META_SIZE])
    } else {
        None
    }) else {
        return false;
    };
    if meta.dispatch != DISPATCH_RPC_REQUEST {
        return false;
    }
    match peek_request_service(frame) {
        Some(svc) => svc != expected,
        None => false,
    }
}

/// OA2-E1 (Kyra E1 audit) — cache the direct-send response
/// destination for a call ONLY when it is trustworthy.
///
/// The origin→node cache is an optimization the response emit closure
/// consults to skip the subscriber-roster fan-out. Populating it from
/// EVERY inbound frame BEFORE the equality/capability gate let a
/// forged frame poison it: an attacker whose frame claims a victim's
/// `origin_hash` (but arrives on the attacker's own session) could
/// overwrite `victim_origin → attacker_node` and redirect the
/// victim's in-flight response. This closes that:
///
/// - only the initial `DISPATCH_RPC_REQUEST` establishes routing
///   (CANCEL / CHUNK / GRANT never rewrite it);
/// - the wire-claimed `origin_hash` is cached ONLY when it equals the
///   AEAD-authenticated last-hop peer's OWN origin (`from_node`'s
///   TOFU-pinned entity) — a forged or relayed origin is refused, so
///   the cache only ever maps a real caller to its own node;
/// - callers reach this ONLY on the accept path (after the
///   service-equality check and the capability/admission gate), so a
///   denied frame never mutates routing.
///
/// An unauthenticated / loopback / relayed call simply is not cached;
/// the response falls back to the signed subscriber roster, preserving
/// public behavior without the direct-send shortcut.
fn cache_authenticated_response_destination(
    mesh: &MeshNode,
    cache: &RpcOriginNodeCache,
    inbound: &RpcInboundEvent,
) {
    let meta = if inbound.payload.len() >= EVENT_META_SIZE {
        EventMeta::from_bytes(&inbound.payload[..EVENT_META_SIZE])
    } else {
        None
    };
    // Direct-session binding (E0.3): the wire-claimed `origin_hash` is
    // trusted only when it matches the AEAD-authenticated `from_node`
    // peer's OWN origin. A malicious node that stamps a victim's origin
    // on the wire header is refused here.
    let authenticated_peer_origin = mesh
        .peer_entity_id(inbound.from_node)
        .map(|e| e.origin_hash());
    if response_route_is_trustworthy(
        inbound.from_node,
        meta.as_ref().map(|m| m.dispatch),
        inbound.origin_hash,
        authenticated_peer_origin,
    ) {
        // Trustworthiness requires `dispatch == DISPATCH_RPC_REQUEST`,
        // so `meta` is always `Some` here. Key the route by the call
        // `(origin, call_id)` (AV-4 item 4) so two authenticated
        // sessions sharing one entity/origin route each response to the
        // node that issued THAT call, rather than clobbering each other.
        if let Some(m) = meta {
            cache.insert(
                (inbound.from_node, inbound.origin_hash, m.seq_or_ts),
                inbound.from_node,
            );
        }
    }
}

/// The pure decision behind [`cache_authenticated_response_destination`]
/// (Kyra E1 audit) — factored out so it is deterministically testable
/// without a live session. A response destination is trustworthy iff:
///
/// - `from_node` is a real session (never the `0` loopback sentinel);
/// - the frame is an initial `DISPATCH_RPC_REQUEST` (control frames
///   carry no new routing and must not rewrite it);
/// - the wire-claimed `claimed_origin` equals the AEAD-authenticated
///   peer's OWN origin (`authenticated_peer_origin`) — a forged or
///   relayed origin, or an unpinned peer (`None`), is refused.
fn response_route_is_trustworthy(
    from_node: u64,
    dispatch: Option<u8>,
    claimed_origin: u64,
    authenticated_peer_origin: Option<u64>,
) -> bool {
    from_node != 0
        && dispatch == Some(DISPATCH_RPC_REQUEST)
        && authenticated_peer_origin == Some(claimed_origin)
}

/// Where an upload REQUEST_GRANT for a flow-controlled call may be routed,
/// classified ONCE at request admission from the SAME authenticated-origin
/// equality response routing uses (Kyra Gate-3). A secure upload grant must
/// reach the caller's directly-authenticated session; deriving "direct" from
/// `from_node != 0` alone would hand a relay's grant to the relay, or
/// roster-fan it to a same-origin bystander.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum RequestGrantRoute {
    /// `from_node` is the caller's own AEAD-authenticated session: its pinned
    /// peer origin equals the wire-claimed origin. Grants are
    /// `DirectOnly(node)`.
    TrustedDirect(u64),
    /// The loopback / test sentinel (`from_node == 0`): local delivery, the
    /// roster path is preserved.
    Loopback,
    /// A nonzero `from_node` whose pinned origin does NOT match the claimed
    /// caller origin — a relayed frame (the last hop is a relay) or a forged
    /// origin. No end-to-end recipient correlation exists to deliver a grant
    /// to the true caller, so a flow-controlled call on this route is
    /// rejected before the fold rather than admitted and silently stalled.
    RelayedOrUntrusted,
}

/// Classify the grant route of an inbound flow-controlled REQUEST using the
/// same equality as [`response_route_is_trustworthy`]: `from_node == 0` is
/// loopback; a nonzero `from_node` whose pinned peer origin equals the
/// wire-claimed origin is a trusted direct session; anything else is relayed
/// or untrusted. Pure and deterministically testable. Captured at admission
/// (never recomputed later from an evictable route cache).
fn classify_request_grant_route(
    from_node: u64,
    claimed_origin: u64,
    authenticated_peer_origin: Option<u64>,
) -> RequestGrantRoute {
    if from_node == 0 {
        RequestGrantRoute::Loopback
    } else if authenticated_peer_origin == Some(claimed_origin) {
        RequestGrantRoute::TrustedDirect(from_node)
    } else {
        RequestGrantRoute::RelayedOrUntrusted
    }
}

/// Whether a server-streaming / duplex RESPONSE frame terminates its
/// call — a non-`Ok` status (error / cancel / deadline) or the explicit
/// `nrpc-streaming: end` marker. The multi-fire emit closures use this
/// to retire the call's cached response route on the terminal frame
/// only (AV-4 item 4). Unary and client-streaming emit exactly one,
/// always-terminal RESPONSE, so they retire unconditionally instead.
fn streaming_response_is_terminal(resp: &RpcResponsePayload) -> bool {
    resp.status != RpcStatus::Ok
        || resp.headers.iter().any(|(name, value)| {
            name.eq_ignore_ascii_case(crate::adapter::net::cortex::HEADER_NRPC_STREAMING)
                && value.as_slice() == crate::adapter::net::cortex::HEADER_NRPC_STREAMING_END
        })
}

/// The verdict of the shared callee-side preflight
/// ([`bridge_preflight`]) — what a serve bridge must do with one
/// inbound frame BEFORE it reaches the fold.
enum BridgePreflight {
    /// Passed equality + the capability gate; the response route was
    /// cached if authenticated. Hand THIS frame to the fold.
    ///
    /// The frame is carried by value rather than the caller reusing its own
    /// `inbound` (§8). A public/legacy handler must never receive
    /// org-admission credential material (E1.6), and the strip that enforces
    /// that lives inside [`bridge_preflight`] — so a bridge physically cannot
    /// fold an unstripped frame, because the only frame it is handed is the
    /// stripped one. Cloning is cheap: `payload` is a refcounted `Bytes` and
    /// the rest is three `u64`s.
    Proceed(RpcInboundEvent),
    /// Cross-service confused deputy, malformed, or a denial with no
    /// authenticated reply identity — drop silently.
    Drop,
    /// The capability gate denied this caller. Emit the terminal
    /// denial ONLY to the AEAD-authenticated session peer `from_node`
    /// (never fanned out to the claimed origin's roster — NC2), on the
    /// reply channel for `claimed_origin`, tagged with `call_id`.
    Deny {
        claimed_origin: u64,
        call_id: u64,
        from_node: u64,
    },
}

/// The ONE callee-side preflight shared by all four serve bridges
/// (Kyra E1 audit — singular seam). Runs, in order:
///
/// 1. captured-service equality (E0.2 P0) — a cross-service REQUEST
///    drops;
/// 2. the public capability admission gate
///    ([`capability_bridge::may_admit`] — `allowed_nodes` or the
///    permissive all-empty default; the self-declared subnet/group
///    axes never admit, per SUBNET_AUTH_PLAN.md S1) — skipped only
///    for the `from_node == 0` loopback/test sentinel;
/// 3. on accept, the authenticated response-route cache
///    ([`cache_authenticated_response_destination`]).
///
/// On denial the reply is delivered ONLY to the AEAD-authenticated
/// session peer `from_node` (NC2, via [`emit_capability_denial`]): a
/// malicious peer that stamps a victim's origin on the wire header
/// cannot reflect a forged `CapabilityDenied` into the victim's reply
/// channel — the denial is unicast to the ATTACKER's own node, where
/// the victim's reply channel has no subscriber, and is dropped.
/// The origin-and-service portion of the callee preflight, shared by the public
/// [`bridge_preflight`] and the protected admission bridge (E1.2): captured-
/// service equality (E0.2), EventMeta decode, and the Gate-3 packet↔payload
/// origin binding. Returns the decoded `EventMeta` to proceed, or `None` to DROP
/// (a cross-service confused deputy, a too-short frame, or an origin mismatch —
/// the last bumps `packet_origin_mismatch_dropped_total`). The CAPABILITY gate
/// diverges after this: the public path runs `may_execute`; the protected path
/// runs `has_local_capability` + org admission. The response-route cache
/// mutation is likewise the caller's, so the two paths share exactly this origin
/// check and nothing else.
fn bridge_origin_check(
    inbound: &RpcInboundEvent,
    expected_service: &str,
    tag: &str,
    metrics: &ServiceMetricsAtomic,
) -> Option<EventMeta> {
    if is_cross_service_request(&inbound.payload, expected_service) {
        return None;
    }
    let meta = (if inbound.payload.len() >= EVENT_META_SIZE {
        EventMeta::from_bytes(&inbound.payload[..EVENT_META_SIZE])
    } else {
        None
    })?;
    let from_node = inbound.from_node;
    // Gate-3: bind the packet (transport) origin to the payload (EventMeta)
    // origin. The response-route cache keys on the packet origin
    // (`inbound.origin_hash`), while every fold keys calls, continuations, and
    // grant emitters on the payload origin (`meta.origin_hash`). A direct peer
    // that stamps a DIFFERENT payload origin than its authenticated packet
    // origin would pass the packet-origin trust check yet run the fold under a
    // forged origin (and split response routing between the two keys). Drop
    // such a frame BEFORE capability admission, cache mutation, or fold
    // execution. Loopback (`from_node == 0`) is exempt — its test/local
    // metadata need not mirror production wire traffic.
    if from_node != 0 && inbound.origin_hash != meta.origin_hash {
        metrics
            .packet_origin_mismatch_dropped_total
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        tracing::warn!(
            service = expected_service,
            tag = tag,
            from_node = format!("{from_node:#x}"),
            packet_origin = format!("{:#x}", inbound.origin_hash),
            payload_origin = format!("{:#x}", meta.origin_hash),
            call_id = meta.seq_or_ts,
            "nrpc: dropping frame whose packet origin != payload (EventMeta) origin \
             before admission — a direct peer must not run the fold under a forged \
             payload origin",
        );
        return None;
    }
    Some(meta)
}

fn bridge_preflight(
    mesh: &MeshNode,
    cache: &RpcOriginNodeCache,
    inbound: &RpcInboundEvent,
    expected_service: &str,
    tag: &str,
    metrics: &ServiceMetricsAtomic,
) -> BridgePreflight {
    let Some(meta) = bridge_origin_check(inbound, expected_service, tag, metrics) else {
        return BridgePreflight::Drop;
    };
    let from_node = inbound.from_node;
    if from_node != 0
        && !crate::adapter::net::behavior::fold::capability_bridge::may_admit(
            mesh.capability_fold(),
            mesh.node_id(),
            tag,
            from_node,
        )
    {
        return BridgePreflight::Deny {
            claimed_origin: inbound.origin_hash,
            call_id: meta.seq_or_ts,
            from_node,
        };
    }
    cache_authenticated_response_destination(mesh, cache, inbound);
    // E1.6 (§8): a public / legacy handler must NEVER see org-admission
    // credential material. This used to be the unary bridge's job, applied at
    // its single fold call site — so `serve_rpc_streaming`,
    // `serve_rpc_client_stream` and `serve_rpc_duplex`, which call this
    // preflight and then fold directly, never stripped at all. Doing it here,
    // and handing the caller the stripped frame rather than letting it reuse
    // its own, makes the omission unrepresentable.
    //
    // Cheap: `strip_public_admission_header` short-circuits on non-REQUEST
    // frames and on a byte-scan miss, so only genuinely admission-bearing
    // frames pay the decode/re-encode.
    let frame = strip_public_admission_header(inbound).unwrap_or_else(|| inbound.clone());
    BridgePreflight::Proceed(frame)
}

/// Emit a terminal `CapabilityDenied` for a gate-denied call, routed
/// ONLY to the AEAD-authenticated session peer `from_node` (NC2 —
/// Kyra E1 audit). The reply origin is derived from the peer's PINNED
/// session entity when known (AV-3 nit — Kyra item 3), so the reply
/// channel is `<service>.replies.<authenticated_origin>`, never the
/// wire-claimed one: a malicious peer that forged a victim's
/// `claimed_origin` gets the denial addressed to ITS OWN origin channel
/// and unicast to ITS OWN node, so a forged denial can never terminate
/// a victim's pending call. When the peer has no pinned entity (a
/// caller that connected but never announced), the reply falls back to
/// the claimed origin — still harmless, because it is unicast to
/// `from_node` and never fanned out to the claimed origin's roster.
async fn emit_capability_denial(
    mesh: &MeshNode,
    service: &str,
    claimed_origin: u64,
    call_id: u64,
    from_node: u64,
) {
    let resp = crate::adapter::net::cortex::RpcResponsePayload {
        status: RpcStatus::CapabilityDenied,
        headers: vec![],
        body: Bytes::from(format!(
            "callee-side capability-auth gate denied nrpc:{service}"
        )),
    };
    let meta = EventMeta::new(
        crate::adapter::net::cortex::DISPATCH_RPC_RESPONSE,
        0,
        mesh.identity_origin_hash(),
        call_id,
        0,
    );
    let mut buf = Vec::with_capacity(EVENT_META_SIZE + 64);
    buf.extend_from_slice(&meta.to_bytes());
    resp.encode_into(&mut buf);

    // AV-3 nit (Kyra item 3): address the reply to the peer's PINNED
    // authenticated origin when known, never the wire-claimed one, so a
    // forger's denial can't be aimed at a victim's reply channel. Falls
    // back to the claimed origin only for an unpinned (non-announced)
    // peer — safe because the send is unicast to `from_node` below.
    let reply_origin = mesh
        .peer_entity_id(from_node)
        .map(|e| e.origin_hash())
        .unwrap_or(claimed_origin);
    let reply_channel_name = format!("{service}.replies.{reply_origin:016x}");
    let Ok(reply_channel) = ChannelName::new(&reply_channel_name) else {
        return;
    };
    let reply_channel_id = ChannelId::new(reply_channel.clone());
    let reply_channel_hash = reply_channel_id.hash();
    let reply_stream_id = MeshNode::publish_stream_id(&reply_channel_id);
    // `target_hint = Some(from_node)` + `DirectOnly` force a direct
    // unicast to the AEAD-authenticated session peer and NOTHING else:
    // if that session is gone the denial is dropped, never reflected onto
    // the (possibly forged) claimed origin's roster channel (NC2 / R2-7).
    let _ = publish_response_to_caller(
        mesh,
        reply_origin,
        Some(from_node),
        &reply_channel,
        reply_channel_hash,
        reply_stream_id,
        Bytes::from(buf),
        ResponseRouteFallback::DirectOnly,
    )
    .await;
}

/// Emit a terminal `AdmissionDenied` (0x0009) for an org-protected call the
/// admission gate rejected (E1.2 / E2.2). Like [`emit_capability_denial`] it is
/// unicast ONLY to the AEAD-authenticated session peer `from_node`, on the reply
/// channel for the peer's PINNED origin (never the wire-claimed one, NC2), so a
/// forged proof cannot aim a denial at a victim's reply channel. The response
/// body carries ONLY the single COARSE reason byte — the detailed
/// `AdmissionDenied` variant stays provider-side audit (a caller must not learn
/// which check failed).
fn emit_admission_denial(
    mesh: &MeshNode,
    resp_tx: &mpsc::Sender<RpcResponseJob>,
    service: &str,
    claimed_origin: u64,
    call_id: u64,
    from_node: u64,
    coarse: crate::adapter::net::behavior::org_admission::CoarseAdmissionReason,
) {
    let resp = crate::adapter::net::cortex::RpcResponsePayload {
        status: RpcStatus::AdmissionDenied,
        headers: vec![],
        body: Bytes::copy_from_slice(&[coarse.to_wire()]),
    };
    let meta = EventMeta::new(
        crate::adapter::net::cortex::DISPATCH_RPC_RESPONSE,
        0,
        mesh.identity_origin_hash(),
        call_id,
        0,
    );
    let mut buf = Vec::with_capacity(EVENT_META_SIZE + 16);
    buf.extend_from_slice(&meta.to_bytes());
    resp.encode_into(&mut buf);
    let reply_origin = mesh
        .peer_entity_id(from_node)
        .map(|e| e.origin_hash())
        .unwrap_or(claimed_origin);
    let Ok(reply_channel) = ChannelName::new(&format!("{service}.replies.{reply_origin:016x}"))
    else {
        return;
    };
    let reply_channel_id = ChannelId::new(reply_channel.clone());
    let reply_channel_hash = reply_channel_id.hash();
    let reply_stream_id = MeshNode::publish_stream_id(&reply_channel_id);
    // §7 — hand the denial to the response DRAINER instead of awaiting the
    // publish here.
    //
    // Every serve bridge is a single task draining a bounded mpsc, so an
    // awaited network write inside the loop serializes behind itself: one
    // session-holding peer (no org credentials required — it stamps its own
    // origin, so the origin check and caller resolution both pass) could send
    // junk proofs and impose a full AEAD-encrypt + socket write of
    // head-of-line blocking per packet on every legitimate protected call.
    // `master` emitted denials through the sync `RpcResponseEmitter`; making
    // this path `.await` was a regression, not a design change.
    //
    // The routing guarantees are unchanged and must stay that way:
    // `target_hint = Some(from_node)` is set EXPLICITLY here rather than
    // resolved from the origin-node cache — a denied call was never dispatched
    // so it has no cache entry, and the drainer publishes protected responses
    // with `ResponseRouteFallback::DirectOnly`, under which a `None` hint
    // means DROP. Getting this wrong would silently swallow every denial
    // rather than misroute one, which is why the live witnesses assert the
    // 0x0009 actually arrives.
    if resp_tx
        .try_send(RpcResponseJob {
            caller_origin: reply_origin,
            call_id,
            target_hint: Some(from_node),
            reply_channel,
            reply_channel_hash,
            reply_stream_id,
            payload: Bytes::from(buf),
        })
        .is_err()
    {
        tracing::debug!(
            from_node = format!("{:#x}", from_node),
            call_id,
            "rpc admission: response drainer at capacity; dropping denial"
        );
    }
}

/// Strip a stray `net-org-admission` proof header from a PUBLIC-service inbound
/// before it reaches the handler (Kyra #47 mixed-version tail): a public (or
/// legacy) handler must NEVER receive org-admission credential material a caller
/// attached — e.g. a caller that believed the service was protected, or a
/// protected→public downgrade. Returns `Some(rewritten)` ONLY when a header was
/// actually removed; `None` (the overwhelming common case) means "dispatch the
/// original inbound" with zero decode or re-encode.
///
/// The raw-bytes prefilter keeps this off the hot path: the header NAME appears
/// verbatim in the postcard-encoded request iff some header carries it, so the
/// absence of those bytes is a definitive skip. A rare coincidental match inside
/// a request body only triggers a wasted decode that finds no such HEADER and
/// returns `None` — never an incorrect rewrite (the removal is header-name
/// scoped). Only genuinely admission-bearing frames pay the decode/re-encode.
fn strip_public_admission_header(inbound: &RpcInboundEvent) -> Option<RpcInboundEvent> {
    // REQUEST-only (Kyra #47 final): only the initial REQUEST carries request
    // headers. A CANCEL / control frame for an already-dispatched call has no
    // header to strip, so short-circuit before the scan and never rewrite a
    // non-REQUEST frame.
    if inbound.payload.len() < EVENT_META_SIZE {
        return None;
    }
    match EventMeta::from_bytes(&inbound.payload[..EVENT_META_SIZE]) {
        Some(meta) if meta.dispatch == DISPATCH_RPC_REQUEST => {}
        _ => return None,
    }
    let needle = ORG_ADMISSION_HEADER.as_bytes();
    if inbound.payload.len() < RPC_FRAME_BODY_OFFSET
        || !inbound.payload.windows(needle.len()).any(|w| w == needle)
    {
        return None;
    }
    let mut req = RpcRequestPayload::decode(inbound.payload.slice(RPC_FRAME_BODY_OFFSET..)).ok()?;
    if !req.headers.iter().any(|(n, _)| n == ORG_ADMISSION_HEADER) {
        return None;
    }
    req.headers.retain(|(n, _)| n != ORG_ADMISSION_HEADER);
    // Preserve the frame prefix (EventMeta + route) verbatim; only the request
    // body is re-encoded without the proof header.
    let mut buf = inbound.payload[..RPC_FRAME_BODY_OFFSET].to_vec();
    req.encode_into(&mut buf);
    Some(RpcInboundEvent {
        channel_hash: inbound.channel_hash,
        origin_hash: inbound.origin_hash,
        from_node: inbound.from_node,
        payload: Bytes::from(buf),
    })
}

/// The E1.2 protected admission gate for ONE inbound frame on a protected unary
/// service, run on the captured immutable [`RegisteredRpcService`]. On the
/// initial REQUEST it runs, in order: the shared origin check, direct-session
/// caller identity (E0.3), local capability (E1.2 — `has_local_capability`, not
/// `may_execute`), provider self-verify (E1.3), and `verify_org_admission`
/// (E1.4/E1.5 stability recheck plus the captured provider policy, one clock
/// sample), then `apply_inbound_admitted`. Any denial is unicast as an
/// `AdmissionDenied` (0x0009 with a coarse reason) to the authenticated peer and
/// the handler NEVER runs. A non-REQUEST frame (a CANCEL for an already-admitted
/// call) passes to the fold unchanged — no re-admission.
#[allow(clippy::too_many_arguments)]
async fn admit_and_dispatch_protected(
    mesh: &Arc<MeshNode>,
    cache: &RpcOriginNodeCache,
    inbound: &RpcInboundEvent,
    service: &str,
    tag: &str,
    metrics: &ServiceMetricsAtomic,
    reg: &crate::adapter::net::org_admission_gate::RegisteredRpcService,
    replay: &crate::adapter::net::behavior::org_admission_replay::AdmissionReplayGuard,
    fold: &Arc<Mutex<RpcServerFold>>,
    // §7 — the bounded response drainer. Denials are ENQUEUED here rather than
    // published inline, so the single bridge task never awaits a socket write.
    resp_tx: &mpsc::Sender<RpcResponseJob>,
) {
    use crate::adapter::net::behavior::org_admission::{AdmissionContext, CoarseAdmissionReason};
    use crate::adapter::net::org_admission_gate as gate;

    let Some(meta) = bridge_origin_check(inbound, service, tag, metrics) else {
        return;
    };
    let from_node = inbound.from_node;
    let claimed_origin = meta.origin_hash;
    let call_id = meta.seq_or_ts;

    // Only the initial REQUEST is admitted; a CANCEL (or any control frame) for
    // an already-admitted call reaches the fold WITHOUT re-admission — the fold
    // keys it on the authenticated session peer + call id.
    if meta.dispatch != DISPATCH_RPC_REQUEST {
        if let Err(e) = fold.lock().apply_inbound(inbound) {
            tracing::warn!(error = %e, "rpc serve_rpc_protected: fold apply error");
        }
        return;
    }

    // E0.3 (Kyra #47 B1): resolve the DIRECT-session caller AND bind the
    // authenticated session entity's origin to the wire-claimed origin. Loopback
    // (`from_node == 0`), an unpinned peer, and — critically — a pinned peer
    // whose origin != the claimed origin are all refused. Without this binding a
    // peer could admit under its OWN proof while stamping a victim's origin into
    // both packet and payload, splitting `org_admission.caller` (authenticated
    // peer) from `RpcContext::caller_origin` (attacker-selected) and aiming the
    // response at the victim.
    let caller = match mesh.resolve_direct_caller(from_node, claimed_origin) {
        Ok(caller) => caller,
        Err(_) => {
            emit_admission_denial(
                mesh,
                resp_tx,
                service,
                claimed_origin,
                call_id,
                from_node,
                CoarseAdmissionReason::Denied,
            );
            return;
        }
    };

    // E1.2: the PROVIDER must itself hold the capability. `has_local_capability`
    // (not `may_execute`) — the caller's authorization is the org proof, never
    // the announcement allow-list.
    if !crate::adapter::net::behavior::fold::capability_bridge::has_local_capability(
        mesh.capability_fold(),
        mesh.node_id(),
        tag,
    ) {
        emit_admission_denial(
            mesh,
            resp_tx,
            service,
            claimed_origin,
            call_id,
            from_node,
            CoarseAdmissionReason::Denied,
        );
        return;
    }

    // §32 — length guard, matching the two sibling helpers
    // (`strip_public_admission_header`, `reject_relayed_flow_controlled_request`).
    // `Bytes::slice` PANICS on an out-of-range start, and this was the one of
    // the three that lacked the check. Currently unreachable — mesh ingress
    // requires `decode_rpc_route` to succeed, which needs
    // `len >= RPC_FRAME_BODY_OFFSET` — but that safety rests on a constant
    // relationship two modules away, and a panic HERE kills the bridge task
    // permanently (`ServeHandle._bridge` is never joined or restarted),
    // silently retiring the service rather than failing one call.
    if inbound.payload.len() < RPC_FRAME_BODY_OFFSET {
        return;
    }

    // Decode the finalized request for the digest + admission header(s).
    let Ok(payload) = RpcRequestPayload::decode(inbound.payload.slice(RPC_FRAME_BODY_OFFSET..))
    else {
        emit_admission_denial(
            mesh,
            resp_tx,
            service,
            claimed_origin,
            call_id,
            from_node,
            CoarseAdmissionReason::Denied,
        );
        return;
    };
    let Ok(request_digest) = gate::org_request_digest(&payload) else {
        emit_admission_denial(
            mesh,
            resp_tx,
            service,
            claimed_origin,
            call_id,
            from_node,
            CoarseAdmissionReason::Denied,
        );
        return;
    };
    let admission_headers: Vec<&[u8]> = payload
        .headers
        .iter()
        .filter(|(n, _)| n == crate::adapter::net::behavior::org_call::ORG_ADMISSION_HEADER)
        .map(|(_, v)| v.as_slice())
        .collect();
    // Unary only (E1.8): a streaming flag on a protected REQUEST is a distinct
    // "not supported" denial, never admitted under a unary binding.
    let is_unary =
        payload.flags & (FLAG_RPC_CLIENT_STREAMING_REQUEST | FLAG_RPC_STREAMING_RESPONSE) == 0;

    // Provider self-verify (E1.3) against ONE clock sample.
    let clock = crate::adapter::net::behavior::admission_clock::ClockSample::now();

    // D7 — the subnet-export binding, revalidated against LIVE state on
    // every call, for a subnet-exported registration only. Runs BEFORE
    // the expensive org-admission signature work (it is two binary
    // probes and four integer compares) and BEFORE the failed-admission
    // throttle: a denial here is provider-side authority movement
    // (credentials or boundaries replaced, floor raised, epoch
    // advanced, expiry), never caller proof abuse, so it is not charged
    // against the caller's budget. The coarse reason deliberately does
    // not disclose WHICH term failed.
    let subnet_export_facts = match reg.subnet_export() {
        Some(binding) => match gate::verify_subnet_export(mesh, binding, &clock) {
            Ok(facts) => Some(facts),
            Err(denied) => {
                emit_admission_denial(
                    mesh,
                    resp_tx,
                    service,
                    claimed_origin,
                    call_id,
                    from_node,
                    denied.coarse(),
                );
                return;
            }
        },
        None => None,
    };

    let facts = match gate::verify_provider_authority(mesh, &clock) {
        Ok(f) => f,
        Err(d) => {
            emit_admission_denial(
                mesh,
                resp_tx,
                service,
                claimed_origin,
                call_id,
                from_node,
                d.coarse(),
            );
            return;
        }
    };
    let invoked_capability =
        crate::adapter::net::behavior::org_grant::CapabilityAuthorityId::for_tag(tag);
    let ctx = AdmissionContext {
        mode: reg.admission(),
        authenticated_caller: &caller,
        provider: &facts.provider,
        provider_owner_org: facts.provider_owner_org,
        invoked_capability,
        call_id,
        request_digest,
        is_unary,
        floors: facts.floors.as_ref(),
        skew_secs: facts.skew_secs,
    };
    let captured_stamp = facts.stamp;

    // Review-7 RED negative-control seam — registration-local, #[cfg(test)] ONLY,
    // compiled out of production. If this registration was built with the disabled
    // mode (unreachable from any production constructor), bypass ONLY the
    // org-admission engine and dispatch the handler. Every provider/transport
    // precondition above is still enforced: the bridge origin bind, the
    // authenticated-caller resolution, the local-capability possession check, the
    // provider self-verification, and the request decode/digest. Removing ONLY
    // organization admission lets an unauthorized protected call run — the proof
    // that `verify_org_admission` is load-bearing, independent of any legacy
    // `may_execute` verdict. The synthetic attribution below is deliberately not a
    // verified `Admitted`; the point is that execution proceeds WITHOUT one.
    #[cfg(test)]
    if reg.red_witness_admission_disabled() {
        cache_authenticated_response_destination(mesh, cache, inbound);
        let admitted = crate::adapter::net::behavior::org_admission::Admitted {
            caller: caller.clone(),
            acting_org: facts.provider_owner_org,
            provider_org: facts.provider_owner_org,
            provider: facts.provider.clone(),
            capability: invoked_capability,
        };
        if let Err(e) = fold.lock().apply_inbound_admitted(inbound, admitted) {
            tracing::warn!(error = %e, "rpc serve_rpc_protected: fold apply error");
        }
        return;
    }

    // §6 — throttle BEFORE the signature work, not after.
    //
    // Everything below this point costs up to three `ed25519 verify_strict`
    // operations, and reaching it requires NO org credentials: a TOFU-pinned
    // peer self-mints an `OrgKeypair`, issues itself a valid membership cert
    // and dispatcher grant under it, and attaches a garbage capability grant
    // naming this provider's public owner org. Every cheap plaintext check
    // passes. Failed admissions deliberately consume no replay slot, so the
    // replay ceilings — including the §5 partition — never see this traffic.
    //
    // The budget is charged on FAILURE only (see `AdmissionFailureLimiter`), so
    // an honest caller whose admissions succeed is entirely unaffected however
    // fast it calls. A peer that has spent its allowance is denied here,
    // cheaply, without the verification it was trying to compel.
    if !mesh
        .admission_rate_limiter()
        .may_attempt(from_node, clock.monotonic)
    {
        tracing::warn!(
            service = service,
            from_node = format!("{:#x}", from_node),
            "nrpc: org admission throttled — peer exhausted its failed-admission budget",
        );
        metrics
            .capability_denied_total
            .fetch_add(1, Ordering::Relaxed);
        emit_admission_denial(
            mesh,
            resp_tx,
            service,
            claimed_origin,
            call_id,
            from_node,
            CoarseAdmissionReason::Unavailable,
        );
        return;
    }

    let outcome = crate::adapter::net::behavior::org_admission::verify_org_admission(
        &ctx,
        &admission_headers,
        replay,
        clock,
        // §9.5 stability: the view captured before verification must still be
        // live at the replay insert, or the stale decision is denied without
        // consuming a slot. For a subnet-exported registration BOTH stamps
        // must hold — the org security view AND the subnet-export view
        // (gateway/boundary snapshot identity + both epochs) — so a
        // wholesale credential or boundary replacement, a floor, or an
        // epoch advance landing mid-verification denies rather than
        // admitting against a dead view.
        || {
            captured_stamp.is_current(&gate::capture_admission_stamp(mesh))
                && subnet_export_facts
                    .as_ref()
                    .is_none_or(|facts| facts.is_current(mesh))
        },
        |proof| (reg.provider_policy())(proof),
    );
    match outcome {
        Ok(admitted) => {
            // Cache the authenticated response route (as the public accept path
            // does), then hand the fold the admitted REQUEST — the handler runs
            // with `RpcContext::org_admission = Some(admitted)` and the raw proof
            // header stripped.
            cache_authenticated_response_destination(mesh, cache, inbound);
            if let Err(e) = fold.lock().apply_inbound_admitted(inbound, admitted) {
                tracing::warn!(error = %e, "rpc serve_rpc_protected: fold apply error");
            }
        }
        Err(denied) => {
            // §6 — charge the failure. A denial is what an attacker produces;
            // a legitimate caller's admissions succeed and cost nothing.
            //
            // EXCEPT `AuthorityChanged` (D7): the §9.5 stability recheck
            // failing means the PROVIDER's security view moved mid-
            // verification — an org authority/floor swap, or a subnet
            // gateway/boundary republication under a subnet-exported
            // registration. That is provider-side state movement, not
            // malformed caller behavior, and charging it would let the
            // provider's own churn exhaust an honest caller's budget.
            if !matches!(
                denied,
                crate::adapter::net::behavior::org_admission::AdmissionDenied::AuthorityChanged
            ) {
                mesh.admission_rate_limiter()
                    .on_failure(from_node, clock.monotonic);
            }
            tracing::warn!(service = service, reason = ?denied, "nrpc: org admission denied");
            emit_admission_denial(
                mesh,
                resp_tx,
                service,
                claimed_origin,
                call_id,
                from_node,
                denied.coarse(),
            );
        }
    }
}

/// Reject a relayed/untrusted flow-controlled upload REQUEST at admission —
/// BEFORE the fold, handler, or grant emitter runs (Kyra Gate-3). Only the
/// two flow-controlled serve bridges (client-streaming, duplex) call this;
/// unary and server-streaming public calls are unaffected.
///
/// A relayed frame arrives with a nonzero `from_node` (the relay's own
/// authenticated session) whose pinned origin does NOT equal the claimed
/// caller origin. A secure upload grant can only reach a directly
/// authenticated caller session — there is no end-to-end recipient
/// correlation to deliver it to the true caller through a relay — so rather
/// than admit the call and then silently lose its grants (partial execution
/// followed by an unexplained stall), the initial REQUEST is DROPPED: the
/// fold is not fed, a dedicated counter is bumped, and a structured warning
/// is logged. Nothing is reflected onto the untrusted claimed origin's
/// roster (contrast [`emit_capability_denial`], which unicasts a denial to
/// the authenticated peer — here there is no trusted peer to answer).
///
/// Returns `true` if the frame was rejected and the bridge must `continue`.
/// Only the initial REQUEST is classified/rejected; later frames for a call
/// that was never admitted are harmlessly ignored by the fold, so metering
/// stays per-call rather than per-frame.
fn reject_relayed_flow_controlled_request(
    mesh: &MeshNode,
    metrics: &ServiceMetricsAtomic,
    inbound: &RpcInboundEvent,
    service: &str,
    tag: &str,
) -> bool {
    let Some(meta) = (if inbound.payload.len() >= EVENT_META_SIZE {
        EventMeta::from_bytes(&inbound.payload[..EVENT_META_SIZE])
    } else {
        None
    }) else {
        return false;
    };
    // Classify (and reject) only the initial REQUEST; CHUNK / CANCEL / GRANT
    // control frames inherit the call the REQUEST already admitted-or-dropped.
    if meta.dispatch != DISPATCH_RPC_REQUEST {
        return false;
    }
    // Reject ONLY a REQUEST that actually enables upload flow control: without
    // a valid request-window header the fold creates no grant emitter (the
    // unbounded-upload fast path), so a relayed/unpinned caller needs no secure
    // grant and is admitted. Decode with the canonical decoder and use the SAME
    // predicate the fold uses (`parse_request_window_initial`) — no second
    // parser, identical "malformed header == absent" semantics. A too-short or
    // undecodable frame is left to the fold, which rejects it.
    if inbound.payload.len() < RPC_FRAME_BODY_OFFSET {
        return false;
    }
    let flow_controlled = matches!(
        RpcRequestPayload::decode(inbound.payload.slice(RPC_FRAME_BODY_OFFSET..)),
        Ok(request) if parse_request_window_initial(&request.headers).is_some()
    );
    if !flow_controlled {
        return false;
    }
    let authenticated_peer_origin = mesh
        .peer_entity_id(inbound.from_node)
        .map(|e| e.origin_hash());
    if RequestGrantRoute::RelayedOrUntrusted
        == classify_request_grant_route(
            inbound.from_node,
            inbound.origin_hash,
            authenticated_peer_origin,
        )
    {
        metrics
            .relayed_flow_controlled_rejected_total
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        tracing::warn!(
            service = service,
            tag = tag,
            from_node = format!("{:#x}", inbound.from_node),
            claimed_origin = format!("{:#x}", inbound.origin_hash),
            call_id = meta.seq_or_ts,
            "nrpc: rejecting relayed/untrusted flow-controlled upload before fold — \
             secure upload grants require a directly authenticated caller session; \
             relayed flow-controlled nRPC is unsupported until end-to-end recipient \
             correlation exists",
        );
        return true;
    }
    false
}

/// A response ready to publish, handed from a (synchronous) `serve_rpc`
/// emit closure to the per-service response drainer task. Replaces the
/// pre-§8a `tokio::spawn`-per-response: the emit closure builds the wire
/// payload (cheap, sync) and `try_send`s this job; one drain task does the
/// `.await` publish. The reply `ChannelName` is `Arc<str>` and `payload` is
/// `Bytes`, so the hand-off is a couple of moves — no copy, no per-response
/// task allocation/scheduling.
struct RpcResponseJob {
    caller_origin: u64,
    call_id: u64,
    target_hint: Option<u64>,
    reply_channel: ChannelName,
    /// PERF_AUDIT §3.10 — cached
    /// `ChannelId::new(reply_channel).hash()`, populated by the
    /// emit closure's `reply_channel_cache` lookup. Pre-fix the
    /// drainer re-ran xxh3 over the channel name per response;
    /// the same `BoundedLru` now caches the triple so a
    /// cache hit is one Arc bump + two `u64` copies.
    reply_channel_hash: ChannelHash,
    /// PERF_AUDIT §3.10 — cached
    /// `MeshNode::publish_stream_id(&reply_channel_id)`.
    reply_stream_id: u64,
    payload: Bytes,
}

/// Cached triple `(ChannelName, ChannelHash, stream_id)` for the
/// per-caller reply channel. Stored in the per-`serve_rpc`
/// `BoundedLru` so each subsequent response to the same
/// caller is one Arc bump on the name + two `u64` copies — no
/// xxh3, no `publish_stream_id`.
///
/// Per PERF_AUDIT §3.10.
#[derive(Clone)]
struct CachedReplyChannel {
    name: ChannelName,
    hash: ChannelHash,
    stream_id: u64,
}

// ============================================================================
// Streaming caller-side: RpcStream.
// ============================================================================

/// An open streaming RPC call. Implements `Stream<Item =
/// Result<Bytes, RpcError>>` — yields chunks as the server emits
/// them, terminates on a clean stream-end frame OR a non-`Ok`
/// status (which is yielded as the last `Err` item before the
/// stream closes).
///
/// Dropping the stream emits a CANCEL to the server (best-effort)
/// and discards the pending entry — any chunks the server emits
/// after the drop are silently discarded by the client fold.
pub struct RpcStream {
    mesh: Arc<MeshNode>,
    target_node_id: u64,
    request_channel: ChannelName,
    /// Cached `ChannelId::new(request_channel).hash()`. Pre-fix
    /// `spawn_grant_publish` re-ran xxh3 over the channel name on
    /// every auto/explicit grant — per PERF_AUDIT §3.10 the value
    /// is invariant for the stream's lifetime, so we cache it once
    /// at construction.
    request_channel_hash: ChannelHash,
    /// Cached `MeshNode::publish_stream_id(&request_channel_id)`.
    /// Same reasoning as `request_channel_hash`.
    request_stream_id: u64,
    self_origin: u64,
    call_id: u64,
    inner: tokio::sync::mpsc::UnboundedReceiver<StreamItem>,
    /// Set true once we've yielded the terminal item (or an
    /// error). Subsequent polls return `None`.
    done: bool,
    /// `Some(_)` if this stream uses flow control (caller set
    /// `CallOptions::stream_window_initial`). Auto-grant
    /// accumulates 1 credit per delivered chunk and fires one
    /// batched `spawn_grant_publish` once the accumulator reaches
    /// `window / 2` (or 1 for tiny windows). Keeps the server's
    /// pump fed at roughly the configured rate without the per-
    /// chunk spawn-storm + AEAD-storm the pre-fix path produced.
    /// `None` → no flow control; `poll_next` does not emit grants.
    /// Per PERF_AUDIT_2026_06_10_FULL_CRATE.md §3.3.
    stream_window: Option<u32>,
    /// Auto-grant accumulator: chunks delivered since the last
    /// emitted grant. Flushed at the `window / 2` threshold (see
    /// the doc on [`Self::stream_window`]).
    grant_pending: u32,
    /// Observer-fire bookkeeping. Latched on terminal observation
    /// in `poll_next`; fired once from `Drop` so the Deck NRPC
    /// tab + every other `RpcObserver` consumer sees one event
    /// per streaming-response call.
    observer: StreamingObserverState,
    /// v3 cancel-watcher keep-alive (C-S1). Dropping this field
    /// (on stream Drop) resolves the matching watcher task's
    /// oneshot receiver with `Err`, telling the watcher to exit
    /// cleanly + release the registry entry. When the call was
    /// opened without `cancel_token`, this is a placeholder sender
    /// with no watcher behind it — drop has no observable effect.
    _cancel_keep_alive: StreamCancelKeepAlive,
}

impl RpcStream {
    /// Server-assigned `call_id`. Useful for trace correlation /
    /// custom logging at the call site.
    pub fn call_id(&self) -> u64 {
        self.call_id
    }

    /// Whether this stream is flow-controlled (caller set
    /// `CallOptions::stream_window_initial`). Useful for tests +
    /// diagnostics; user code typically doesn't need to inspect
    /// this.
    pub fn flow_controlled(&self) -> bool {
        self.stream_window.is_some()
    }

    /// Explicitly grant `amount` more credits to the server's
    /// pump. Spawns a fire-and-forget publish; doesn't await
    /// acknowledgement. **No-op when flow control was not enabled
    /// for this stream** — the server would silently drop the
    /// grant anyway, and emitting wire traffic with no purpose
    /// would just burn bandwidth.
    ///
    /// Auto-grant (1 credit per delivered chunk) covers the
    /// common case; use this for batched cadence (e.g. grant
    /// `window/2` after every `window/2` chunks consumed) when
    /// `auto_grant`-style amortization isn't enough.
    pub fn grant(&self, amount: u32) {
        if !self.flow_controlled() || amount == 0 {
            return;
        }
        spawn_grant_publish(
            Arc::clone(&self.mesh),
            self.target_node_id,
            self.request_channel_hash,
            self.request_stream_id,
            self.self_origin,
            self.call_id,
            amount,
        );
    }
}

/// PERF_AUDIT §3.3 — auto-grant coalescing decision for
/// [`RpcStream::poll_next`]. Accumulates one credit (the chunk
/// that was just delivered to the consumer) into `pending` and
/// returns `Some(amount)` when the accumulator reaches the flush
/// threshold of `window / 2` (clamped to ≥ 1 so a window of 1
/// degenerates to the pre-fix per-chunk cadence).
///
/// Liveness invariant (why no flush-on-drop / timer backstop is
/// needed): the credits left pending never exceed
/// `threshold - 1 < window`. The server starts with `window`
/// credits and `credits = window - (sent - delivered) - pending`,
/// so whenever the consumer has polled everything that was sent
/// (the only state in which it could block waiting on the server),
/// `credits = window - pending >= window - threshold + 1 >= 1` —
/// the server can always make progress. A consumer that stops
/// polling stalls the pump by design (that's flow control), and
/// the chunks already buffered in the stream's mpsc are enough to
/// carry `pending` across the threshold as soon as it resumes.
fn accumulate_auto_grant(pending: &mut u32, window: u32) -> Option<u32> {
    *pending = pending.saturating_add(1);
    let threshold = (window / 2).max(1);
    if *pending >= threshold {
        let amount = *pending;
        *pending = 0;
        Some(amount)
    } else {
        None
    }
}

/// Shared fire-and-forget GRANT-publish helper. Used by
/// [`RpcStream::grant`] (explicit) and the auto-grant in
/// [`RpcStream::poll_next`]. Same direct-unicast publish path as
/// [`spawn_cancel_publish`], just with a different dispatch byte
/// + a 4-byte u32 payload.
///
/// PERF_AUDIT §3.10 — takes `request_channel_hash` and
/// `request_stream_id` as pre-computed inputs (cached on
/// `RpcStream`) so the per-chunk grant path doesn't re-run
/// `ChannelId::new` + xxh3 on every call.
fn spawn_grant_publish(
    mesh: Arc<MeshNode>,
    target: u64,
    request_channel_hash: ChannelHash,
    request_stream_id: u64,
    self_origin: u64,
    call_id: u64,
    amount: u32,
) {
    tokio::spawn(async move {
        let meta = EventMeta::new(DISPATCH_RPC_STREAM_GRANT, 0, self_origin, call_id, 0);
        let mut buf = Vec::with_capacity(EVENT_META_SIZE + RPC_ROUTE_V1_SIZE + 4);
        buf.extend_from_slice(&meta.to_bytes());
        encode_rpc_route(&mut buf, request_channel_hash);
        buf.extend_from_slice(&encode_stream_grant(amount));
        let payload = Bytes::from(buf);
        let _ = mesh
            .publish_to_peer(
                target,
                request_channel_hash,
                request_stream_id,
                /* reliable */ true,
                std::slice::from_ref(&payload),
            )
            .await;
    });
}

impl futures::Stream for RpcStream {
    type Item = Result<Bytes, RpcError>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        if self.done {
            return std::task::Poll::Ready(None);
        }
        match self.inner.poll_recv(cx) {
            std::task::Poll::Ready(Some(StreamItem::Chunk(body))) => {
                // Auto-grant: accumulate 1 credit per delivered
                // chunk and fire a batched `spawn_grant_publish`
                // only when the accumulator reaches `window / 2`
                // (or 1 for tiny windows). Per PERF_AUDIT §3.3 —
                // pre-fix this spawned one task + one reliable
                // AEAD packet per chunk, a spawn-storm + AEAD-
                // storm under bursting; the server side already
                // fixed the identical shape via
                // `build_request_grant_emitter` (§3.3 audit text).
                // Callers needing finer cadence still have
                // `RpcStream::grant` for explicit batches.
                if let Some(window) = self.stream_window {
                    let mut pending = self.grant_pending;
                    if let Some(amount) = accumulate_auto_grant(&mut pending, window) {
                        spawn_grant_publish(
                            Arc::clone(&self.mesh),
                            self.target_node_id,
                            self.request_channel_hash,
                            self.request_stream_id,
                            self.self_origin,
                            self.call_id,
                            amount,
                        );
                    }
                    self.grant_pending = pending;
                }
                self.observer.add_response_bytes(body.len() as u32);
                std::task::Poll::Ready(Some(Ok(body)))
            }
            std::task::Poll::Ready(Some(StreamItem::End)) => {
                self.done = true;
                self.observer.latch_ok();
                std::task::Poll::Ready(None)
            }
            std::task::Poll::Ready(Some(StreamItem::Error(resp))) => {
                self.done = true;
                let status = resp.status.to_wire();
                let message = String::from_utf8(resp.body.to_vec()).unwrap_or_else(|e| {
                    format!("<{} bytes of non-utf8 body>", e.into_bytes().len())
                });
                self.observer
                    .latch_error(format!("server returned status {status:#06x}: {message}"));
                std::task::Poll::Ready(Some(Err(RpcError::ServerError {
                    status,
                    message,
                    headers: resp.headers,
                })))
            }
            std::task::Poll::Ready(None) => {
                self.done = true;
                std::task::Poll::Ready(None)
            }
            std::task::Poll::Pending => std::task::Poll::Pending,
        }
    }
}

impl Drop for RpcStream {
    fn drop(&mut self) {
        // Best-effort CANCEL to the server. Spawn a task because
        // Drop can't be async; the publish happens off-thread.
        // Also clear our pending entry so any in-flight chunks
        // are dropped on arrival.
        self.mesh.rpc_client_pending_arc().cancel(self.call_id);
        spawn_cancel_publish(
            Arc::clone(&self.mesh),
            self.target_node_id,
            self.request_channel.clone(),
            self.self_origin,
            self.call_id,
        );
        // Fire the observer with the latched status (Ok / Error /
        // Canceled). Idempotent — only the first fire emits.
        self.observer.fire();
    }
}

// ============================================================================
// Phase C — caller-side client-streaming / duplex primitive.
// ============================================================================

/// Shared REQUEST_CHUNK-publish helper. Builds the wire frame and
/// fires through `publish_to_peer` direct-unicast (same routing
/// pattern as the initial REQUEST — caller knows the target).
/// PERF_AUDIT §3.10 — accepts pre-computed
/// `request_channel_hash` and `request_stream_id` (cached on
/// `ClientStreamCallRaw`) so the per-chunk client-stream send path
/// doesn't re-run `ChannelId::new` + xxh3 on every chunk.
async fn publish_request_chunk(
    mesh: &Arc<MeshNode>,
    target: u64,
    request_channel_hash: ChannelHash,
    request_stream_id: u64,
    self_origin: u64,
    chunk: &RpcRequestChunkPayload,
) -> Result<(), RpcError> {
    let meta = EventMeta::new(DISPATCH_RPC_REQUEST_CHUNK, 0, self_origin, chunk.call_id, 0);
    let mut buf = Vec::with_capacity(EVENT_META_SIZE + RPC_ROUTE_V1_SIZE + chunk.encoded_len());
    buf.extend_from_slice(&meta.to_bytes());
    encode_rpc_route(&mut buf, request_channel_hash);
    chunk.encode_into(&mut buf);
    let payload = Bytes::from(buf);
    mesh.publish_to_peer(
        target,
        request_channel_hash,
        request_stream_id,
        /* reliable */ true,
        std::slice::from_ref(&payload),
    )
    .await
    .map_err(RpcError::Transport)
}

/// Internal state of a [`ClientStreamCallRaw`]. The state machine
/// is small: open the call (initial REQUEST not yet sent), then
/// send N items (the first becomes the initial REQUEST, subsequent
/// become REQUEST_CHUNKs), then finish (terminal REQUEST_END
/// frame). After finish, no further sends are accepted.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ClientStreamState {
    /// Pending entry registered, reply subscription ensured, but
    /// the initial REQUEST has NOT been published to the wire yet.
    /// First `send` flips this to `Sending`.
    JustOpened,
    /// Initial REQUEST has been published; subsequent sends ride
    /// as REQUEST_CHUNKs.
    Sending,
    /// `finish` has been called; the terminal REQUEST_END frame
    /// (or the initial REQUEST with FLAG_END for the degenerate
    /// zero-send path) has been published. The terminal RESPONSE
    /// has not necessarily arrived yet — that's awaited on the
    /// caller's terminal_rx.
    Finishing,
    /// Terminal RESPONSE has been delivered. Drop is a no-op.
    Done,
}

/// Caller-side handle for a client-streaming (or duplex Phase D)
/// RPC. Push N items via [`ClientStreamCallRaw::send`], then
/// [`ClientStreamCallRaw::finish`] to await the terminal RESPONSE.
///
/// **Lazy initial REQUEST.** The initial REQUEST is published on
/// the FIRST `send()` (or on `finish()` if the caller sends nothing
/// — that's the "zero-item upload" degenerate path that opens and
/// closes the call in one frame). Constructing the handle does
/// NOT yet emit any wire traffic beyond the reply-channel
/// subscription setup.
///
/// **Flow control.** When the caller set
/// [`CallOptions::request_window_initial`] to `Some(n)`, the
/// handle holds an `n`-permit `Semaphore` that gates `send`. The
/// server's [`DISPATCH_RPC_REQUEST_GRANT`] events refill the
/// semaphore. When `None`, `send` doesn't block (caller is on the
/// unbounded-credit fast path).
///
/// **Cancellation.** Dropping the handle BEFORE `finish` returns
/// `Ok` fires a best-effort CANCEL to the server and clears the
/// pending entry. Dropping after a successful `finish` is a no-op
/// (terminal RESPONSE already delivered + entry removed).
///
/// Bidi streaming plan (Phase C).
pub struct ClientStreamCallRaw {
    mesh: Arc<MeshNode>,
    target_node_id: u64,
    request_channel: ChannelName,
    /// PERF_AUDIT §3.10 — cached `ChannelId::new(request_channel).hash()`
    /// so per-chunk REQUEST_CHUNK publishes don't re-run xxh3.
    request_channel_hash: ChannelHash,
    /// PERF_AUDIT §3.10 — cached
    /// `MeshNode::publish_stream_id(&request_channel_id)`.
    request_stream_id: u64,
    self_origin: u64,
    call_id: u64,
    service: String,
    /// Header set queued for the initial REQUEST. Drained on the
    /// first publish (either `send` or `finish`).
    initial_headers: Vec<(String, Vec<u8>)>,
    /// Flag bits queued for the initial REQUEST. Always carries
    /// `FLAG_RPC_CLIENT_STREAMING_REQUEST`; may also carry
    /// `FLAG_RPC_PROPAGATE_TRACE` when the caller supplied a
    /// trace context.
    initial_flags: u16,
    /// `deadline_ns` from `CallOptions::deadline`. Embedded in the
    /// initial REQUEST.
    deadline_ns: u64,
    /// Per-call semaphore for upload credits. `None` when the
    /// caller didn't opt into flow control (`request_window_initial`
    /// was `None` on the `CallOptions`).
    credit_sem: Option<Arc<tokio::sync::Semaphore>>,
    /// Background task that drains REQUEST_GRANT credits from the
    /// pending entry's grant mpsc into `credit_sem`. Aborted on
    /// Drop. `None` when flow control is off.
    grant_pump: Option<JoinHandle<()>>,
    /// Single-shot terminal-RESPONSE receiver. Taken by `finish`;
    /// after that `Drop` doesn't attempt to await again.
    terminal_rx: Option<tokio::sync::oneshot::Receiver<RpcResponsePayload>>,
    /// State machine. See [`ClientStreamState`].
    state: ClientStreamState,
    /// Wall-clock start (for `RpcReply::latency_ns` reporting).
    started: Instant,
    /// Observer-fire bookkeeping. Latched on terminal observation
    /// in `finish`; fired once from `Drop` so the Deck NRPC tab +
    /// every `RpcObserver` consumer sees one event per
    /// client-streaming call.
    observer: StreamingObserverState,
    /// v3 cancel-watcher keep-alive (C-S1). Dropping this field
    /// (on call Drop) tells the watcher task to exit cleanly and
    /// release the registry entry. See
    /// [`spawn_stream_cancel_watcher`] for the lifecycle.
    _cancel_keep_alive: StreamCancelKeepAlive,
}

impl ClientStreamCallRaw {
    /// Server-assigned `call_id`. Useful for trace correlation /
    /// custom logging.
    pub fn call_id(&self) -> u64 {
        self.call_id
    }

    /// Whether this call is flow-controlled (caller set
    /// `CallOptions::request_window_initial`).
    pub fn flow_controlled(&self) -> bool {
        self.credit_sem.is_some()
    }

    /// Push one body chunk to the server. Encodes as the initial
    /// REQUEST (first call) or as a REQUEST_CHUNK (subsequent
    /// calls). When flow control is opted into, awaits one credit
    /// before publishing.
    ///
    /// Returns `Err(RpcError::Codec)` if called after [`Self::finish`].
    pub async fn send(&mut self, body: Bytes) -> Result<(), RpcError> {
        match self.state {
            ClientStreamState::Finishing | ClientStreamState::Done => {
                return Err(RpcError::Codec {
                    direction: CodecDirection::Encode,
                    message: "send() called after finish()".to_string(),
                });
            }
            _ => {}
        }
        // Gate on credit when flow control is opted into.
        if let Some(sem) = self.credit_sem.as_ref() {
            let permit = sem.clone().acquire_owned().await.map_err(|_| {
                RpcError::Transport(AdapterError::Connection("credit semaphore closed".into()))
            })?;
            permit.forget();
        }
        self.observer.add_request_bytes(body.len() as u32);
        match self.state {
            ClientStreamState::JustOpened => {
                // First send → initial REQUEST.
                let req = RpcRequestPayload {
                    service: self.service.clone(),
                    deadline_ns: self.deadline_ns,
                    flags: self.initial_flags,
                    headers: std::mem::take(&mut self.initial_headers),
                    body: body.clone(),
                };
                self.publish_initial_request(&req).await?;
                self.state = ClientStreamState::Sending;
            }
            ClientStreamState::Sending => {
                let chunk = RpcRequestChunkPayload {
                    call_id: self.call_id,
                    flags: 0,
                    headers: vec![],
                    body: body.clone(),
                };
                publish_request_chunk(
                    &self.mesh,
                    self.target_node_id,
                    self.request_channel_hash,
                    self.request_stream_id,
                    self.self_origin,
                    &chunk,
                )
                .await?;
            }
            ClientStreamState::Finishing | ClientStreamState::Done => unreachable!(),
        }
        Ok(())
    }

    /// Close the upload direction and await the server's terminal
    /// RESPONSE. Emits a REQUEST_CHUNK with `FLAG_RPC_REQUEST_END`
    /// (empty body) if the call has already published its initial
    /// REQUEST, or an initial REQUEST with both
    /// `FLAG_RPC_CLIENT_STREAMING_REQUEST` and
    /// `FLAG_RPC_REQUEST_END` set (the degenerate "zero-item
    /// upload" path) if nothing was sent.
    ///
    /// Consumes the handle — Drop after `finish` is a no-op.
    pub async fn finish(mut self) -> Result<RpcReply, RpcError> {
        match self.state {
            ClientStreamState::JustOpened => {
                let req = RpcRequestPayload {
                    service: self.service.clone(),
                    deadline_ns: self.deadline_ns,
                    flags: self.initial_flags | FLAG_RPC_REQUEST_END,
                    headers: std::mem::take(&mut self.initial_headers),
                    body: Bytes::new(),
                };
                self.publish_initial_request(&req).await?;
            }
            ClientStreamState::Sending => {
                let chunk = RpcRequestChunkPayload {
                    call_id: self.call_id,
                    flags: FLAG_RPC_REQUEST_END,
                    headers: vec![],
                    body: Bytes::new(),
                };
                publish_request_chunk(
                    &self.mesh,
                    self.target_node_id,
                    self.request_channel_hash,
                    self.request_stream_id,
                    self.self_origin,
                    &chunk,
                )
                .await?;
            }
            ClientStreamState::Finishing | ClientStreamState::Done => {
                return Err(RpcError::Codec {
                    direction: CodecDirection::Encode,
                    message: "finish() called twice".to_string(),
                });
            }
        }
        self.state = ClientStreamState::Finishing;
        let terminal_rx = self.terminal_rx.take().ok_or_else(|| {
            RpcError::Transport(AdapterError::Connection(
                "terminal receiver already consumed".into(),
            ))
        })?;
        // Honor the deadline if the caller set one.
        let resp = if self.deadline_ns > 0 {
            let now = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos() as u64)
                .unwrap_or(0);
            let remaining = self.deadline_ns.saturating_sub(now);
            match tokio::time::timeout(std::time::Duration::from_nanos(remaining), terminal_rx)
                .await
            {
                Ok(Ok(r)) => r,
                Ok(Err(_)) => {
                    let msg = "terminal sender dropped before response arrived";
                    self.observer.latch_error(msg);
                    return Err(RpcError::Transport(AdapterError::Connection(msg.into())));
                }
                Err(_elapsed) => {
                    let elapsed_ms = self.started.elapsed().as_millis() as u64;
                    self.observer.latch_timeout();
                    return Err(RpcError::Timeout { elapsed_ms });
                }
            }
        } else {
            match terminal_rx.await {
                Ok(r) => r,
                Err(_) => {
                    let msg = "terminal sender dropped before response arrived";
                    self.observer.latch_error(msg);
                    return Err(RpcError::Transport(AdapterError::Connection(msg.into())));
                }
            }
        };
        self.state = ClientStreamState::Done;
        self.observer.add_response_bytes(resp.body.len() as u32);
        if !resp.status.is_ok() {
            // String::from_utf8 takes `Vec<u8>`. `Bytes::to_vec()`
            // matches the prior `resp.body.clone()` semantics (full
            // copy of the body for the error-formatting path);
            // bulk-throughput improvement lives on the decode side,
            // not here.
            let message = String::from_utf8(resp.body.to_vec())
                .unwrap_or_else(|e| format!("<{} bytes of non-utf8 body>", e.into_bytes().len()));
            self.observer.latch_error(format!(
                "server returned status {:#06x}: {message}",
                resp.status.to_wire()
            ));
            return Err(RpcError::ServerError {
                status: resp.status.to_wire(),
                message,
                headers: resp.headers,
            });
        }
        self.observer.latch_ok();
        let latency_ns = self.started.elapsed().as_nanos() as u64;
        Ok(RpcReply {
            body: resp.body,
            headers: resp.headers,
            latency_ns,
        })
    }

    async fn publish_initial_request(&self, req: &RpcRequestPayload) -> Result<(), RpcError> {
        let meta = EventMeta::new(DISPATCH_RPC_REQUEST, 0, self.self_origin, self.call_id, 0);
        let mut buf = Vec::with_capacity(EVENT_META_SIZE + RPC_ROUTE_V1_SIZE + req.encoded_len());
        buf.extend_from_slice(&meta.to_bytes());
        encode_rpc_route(&mut buf, self.request_channel_hash);
        req.encode_into(&mut buf);
        let payload = Bytes::from(buf);
        // PERF_AUDIT §3.10 — use the cached hash + stream_id from
        // construction; no per-publish `ChannelId::new` + xxh3.
        self.mesh
            .publish_to_peer(
                self.target_node_id,
                self.request_channel_hash,
                self.request_stream_id,
                /* reliable */ true,
                std::slice::from_ref(&payload),
            )
            .await
            .map_err(RpcError::Transport)
    }
}

impl Drop for ClientStreamCallRaw {
    fn drop(&mut self) {
        if let Some(task) = self.grant_pump.take() {
            task.abort();
        }
        // Fire the observer with whatever status was latched
        // (Ok / Error / Timeout / Canceled). Idempotent — only
        // the first call emits.
        self.observer.fire();
        if matches!(self.state, ClientStreamState::Done) {
            // Successful completion — pending entry already gone,
            // no CANCEL needed.
            return;
        }
        self.mesh.rpc_client_pending_arc().cancel(self.call_id);
        // Only fire CANCEL on the wire if the server has actually
        // seen the initial REQUEST. A `JustOpened` Drop means we
        // never published anything; no need to CANCEL a call the
        // server doesn't know about.
        if !matches!(self.state, ClientStreamState::JustOpened) {
            spawn_cancel_publish(
                Arc::clone(&self.mesh),
                self.target_node_id,
                self.request_channel.clone(),
                self.self_origin,
                self.call_id,
            );
        }
    }
}

// ============================================================================
// Phase D — caller-side duplex primitive.
// ============================================================================

/// Shared state between a `DuplexSink` and its sibling
/// `DuplexStream`. Both halves hold an `Arc<DuplexInner>`; when
/// the refcount hits zero (i.e. both halves dropped) the Drop
/// fires CANCEL to the server unless the call was cleanly closed
/// (`clean_close = true`).
struct DuplexInner {
    mesh: Arc<MeshNode>,
    target_node_id: u64,
    request_channel: ChannelName,
    /// PERF_AUDIT §3.10 — cached channel-id hash + stream id so
    /// per-chunk publishes from the upload side don't re-run
    /// `ChannelId::new` + xxh3.
    request_channel_hash: ChannelHash,
    request_stream_id: u64,
    self_origin: u64,
    call_id: u64,
    /// Whether the initial REQUEST was successfully published.
    /// `false` means we never reached the wire — no CANCEL needed
    /// (server doesn't know about the call).
    initial_sent: std::sync::atomic::AtomicBool,
    /// Set true when the call closes cleanly — terminal RESPONSE
    /// (or terminal Error) was observed on the response stream.
    /// Suppresses CANCEL-on-drop.
    clean_close: std::sync::atomic::AtomicBool,
    /// Observer-fire bookkeeping. Latched from the various
    /// terminal-observation sites (DuplexCall::next /
    /// DuplexStream::poll_next yielding End or Error); fired
    /// once on Drop. The DuplexCall / DuplexSink / DuplexStream
    /// each share access via the surrounding Arc<DuplexInner>.
    observer: StreamingObserverState,
    /// v3 cancel-watcher keep-alive (C-S1). Lives on
    /// `Arc<DuplexInner>` so it survives `into_split` — both
    /// halves of the duplex hold the same Arc, so the watcher
    /// task exits only when BOTH halves drop (matching the
    /// Drop-fires-CANCEL semantics above). Wrapped in `Option`
    /// for `mem::take`-style construction patterns; populated
    /// once at `call_duplex` time and never cleared.
    _cancel_keep_alive: Option<StreamCancelKeepAlive>,
}

impl Drop for DuplexInner {
    fn drop(&mut self) {
        self.mesh.rpc_client_pending_arc().cancel(self.call_id);
        // Fire the observer with the latched status (Ok / Error /
        // Canceled). Idempotent — only the first call emits.
        self.observer.fire();
        if self.clean_close.load(Ordering::SeqCst) {
            return;
        }
        if !self.initial_sent.load(Ordering::SeqCst) {
            return;
        }
        spawn_cancel_publish(
            Arc::clone(&self.mesh),
            self.target_node_id,
            self.request_channel.clone(),
            self.self_origin,
            self.call_id,
        );
    }
}

/// Send half of a duplex call. Push items via `send`; emit the
/// terminal REQUEST_END frame via `finish_sending`. After
/// `finish_sending` the upload side is closed but the sibling
/// `DuplexStream` continues yielding response chunks until the
/// server's terminal frame arrives.
///
/// Bidi streaming plan (Phase D).
pub struct DuplexSink {
    inner: Arc<DuplexInner>,
    service: String,
    initial_headers: Vec<(String, Vec<u8>)>,
    initial_flags: u16,
    deadline_ns: u64,
    credit_sem: Option<Arc<tokio::sync::Semaphore>>,
    grant_pump: Option<JoinHandle<()>>,
    state: ClientStreamState,
}

impl DuplexSink {
    /// Push one body chunk to the server. Same semantics as
    /// [`ClientStreamCallRaw::send`].
    pub async fn send(&mut self, body: Bytes) -> Result<(), RpcError> {
        match self.state {
            ClientStreamState::Finishing | ClientStreamState::Done => {
                return Err(RpcError::Codec {
                    direction: CodecDirection::Encode,
                    message: "send() called after finish_sending()".to_string(),
                });
            }
            _ => {}
        }
        if let Some(sem) = self.credit_sem.as_ref() {
            let permit = sem.clone().acquire_owned().await.map_err(|_| {
                RpcError::Transport(AdapterError::Connection("credit semaphore closed".into()))
            })?;
            permit.forget();
        }
        self.inner.observer.add_request_bytes(body.len() as u32);
        match self.state {
            ClientStreamState::JustOpened => {
                let req = RpcRequestPayload {
                    service: self.service.clone(),
                    deadline_ns: self.deadline_ns,
                    flags: self.initial_flags,
                    headers: std::mem::take(&mut self.initial_headers),
                    body: body.clone(),
                };
                self.publish_initial_request(&req).await?;
                self.inner.initial_sent.store(true, Ordering::SeqCst);
                self.state = ClientStreamState::Sending;
            }
            ClientStreamState::Sending => {
                let chunk = RpcRequestChunkPayload {
                    call_id: self.inner.call_id,
                    flags: 0,
                    headers: vec![],
                    body: body.clone(),
                };
                publish_request_chunk(
                    &self.inner.mesh,
                    self.inner.target_node_id,
                    self.inner.request_channel_hash,
                    self.inner.request_stream_id,
                    self.inner.self_origin,
                    &chunk,
                )
                .await?;
            }
            ClientStreamState::Finishing | ClientStreamState::Done => unreachable!(),
        }
        Ok(())
    }

    /// Close the upload direction. Emits the terminal REQUEST_END
    /// frame. The response stream continues until the server's
    /// terminal RESPONSE arrives (use the sibling `DuplexStream`).
    pub async fn finish_sending(mut self) -> Result<(), RpcError> {
        match self.state {
            ClientStreamState::JustOpened => {
                let req = RpcRequestPayload {
                    service: self.service.clone(),
                    deadline_ns: self.deadline_ns,
                    flags: self.initial_flags | FLAG_RPC_REQUEST_END,
                    headers: std::mem::take(&mut self.initial_headers),
                    body: Bytes::new(),
                };
                self.publish_initial_request(&req).await?;
                self.inner.initial_sent.store(true, Ordering::SeqCst);
            }
            ClientStreamState::Sending => {
                let chunk = RpcRequestChunkPayload {
                    call_id: self.inner.call_id,
                    flags: FLAG_RPC_REQUEST_END,
                    headers: vec![],
                    body: Bytes::new(),
                };
                publish_request_chunk(
                    &self.inner.mesh,
                    self.inner.target_node_id,
                    self.inner.request_channel_hash,
                    self.inner.request_stream_id,
                    self.inner.self_origin,
                    &chunk,
                )
                .await?;
            }
            ClientStreamState::Finishing | ClientStreamState::Done => {
                return Err(RpcError::Codec {
                    direction: CodecDirection::Encode,
                    message: "finish_sending() called twice".to_string(),
                });
            }
        }
        self.state = ClientStreamState::Finishing;
        Ok(())
    }

    /// Server-assigned `call_id`. Same value on the sibling
    /// `DuplexStream`.
    pub fn call_id(&self) -> u64 {
        self.inner.call_id
    }

    /// Whether this call is flow-controlled on the upload side.
    pub fn flow_controlled(&self) -> bool {
        self.credit_sem.is_some()
    }

    async fn publish_initial_request(&self, req: &RpcRequestPayload) -> Result<(), RpcError> {
        let meta = EventMeta::new(
            DISPATCH_RPC_REQUEST,
            0,
            self.inner.self_origin,
            self.inner.call_id,
            0,
        );
        let mut buf = Vec::with_capacity(EVENT_META_SIZE + RPC_ROUTE_V1_SIZE + req.encoded_len());
        buf.extend_from_slice(&meta.to_bytes());
        encode_rpc_route(&mut buf, self.inner.request_channel_hash);
        req.encode_into(&mut buf);
        let payload = Bytes::from(buf);
        // PERF_AUDIT §3.10 — cached hash + stream_id from the
        // inner `ClientStreamCallRaw`.
        self.inner
            .mesh
            .publish_to_peer(
                self.inner.target_node_id,
                self.inner.request_channel_hash,
                self.inner.request_stream_id,
                /* reliable */ true,
                std::slice::from_ref(&payload),
            )
            .await
            .map_err(RpcError::Transport)
    }
}

impl Drop for DuplexSink {
    fn drop(&mut self) {
        if let Some(task) = self.grant_pump.take() {
            task.abort();
        }
        // The shared DuplexInner's Drop (when refcount hits 0)
        // does the CANCEL — nothing to do here beyond aborting
        // the grant pump.
    }
}

/// Receive half of a duplex call. Implements `futures::Stream`
/// yielding `Result<Bytes, RpcError>` per inbound RESPONSE chunk.
/// EOF on terminal Ok; one final `Err(RpcError::ServerError)` on
/// terminal non-Ok.
///
/// Bidi streaming plan (Phase D).
pub struct DuplexStream {
    inner: Arc<DuplexInner>,
    chunks_rx: tokio::sync::mpsc::UnboundedReceiver<StreamItem>,
    done: bool,
}

impl DuplexStream {
    /// Server-assigned `call_id`. Same value on the sibling
    /// `DuplexSink`.
    pub fn call_id(&self) -> u64 {
        self.inner.call_id
    }
}

impl futures::Stream for DuplexStream {
    type Item = Result<Bytes, RpcError>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        if self.done {
            return std::task::Poll::Ready(None);
        }
        match self.chunks_rx.poll_recv(cx) {
            std::task::Poll::Ready(Some(StreamItem::Chunk(body))) => {
                self.inner.observer.add_response_bytes(body.len() as u32);
                std::task::Poll::Ready(Some(Ok(body)))
            }
            std::task::Poll::Ready(Some(StreamItem::End)) => {
                self.done = true;
                self.inner.clean_close.store(true, Ordering::SeqCst);
                self.inner.observer.latch_ok();
                std::task::Poll::Ready(None)
            }
            std::task::Poll::Ready(Some(StreamItem::Error(resp))) => {
                self.done = true;
                self.inner.clean_close.store(true, Ordering::SeqCst);
                let status = resp.status.to_wire();
                let message = String::from_utf8(resp.body.to_vec()).unwrap_or_else(|e| {
                    format!("<{} bytes of non-utf8 body>", e.into_bytes().len())
                });
                self.inner
                    .observer
                    .latch_error(format!("server returned status {status:#06x}: {message}"));
                std::task::Poll::Ready(Some(Err(RpcError::ServerError {
                    status,
                    message,
                    headers: resp.headers,
                })))
            }
            std::task::Poll::Ready(None) => {
                self.done = true;
                std::task::Poll::Ready(None)
            }
            std::task::Poll::Pending => std::task::Poll::Pending,
        }
    }
}

/// Caller-side handle for a duplex RPC. Combines a `DuplexSink`
/// (upload) and `DuplexStream` (download). For application code
/// that wants to encode requests in one task and decode responses
/// in another, use [`Self::into_split`] to peel off the two halves.
///
/// Bidi streaming plan (Phase D).
pub struct DuplexCallRaw {
    sink: DuplexSink,
    stream: DuplexStream,
}

impl DuplexCallRaw {
    /// Server-assigned `call_id`.
    pub fn call_id(&self) -> u64 {
        self.sink.call_id()
    }

    /// Whether the upload side is flow-controlled.
    pub fn flow_controlled(&self) -> bool {
        self.sink.flow_controlled()
    }

    /// Push one body chunk to the server. Delegates to the inner
    /// `DuplexSink::send`.
    pub async fn send(&mut self, body: Bytes) -> Result<(), RpcError> {
        self.sink.send(body).await
    }

    /// Close the upload direction. Delegates to the inner
    /// `DuplexSink::finish_sending` but keeps the receive side
    /// alive so the caller can keep polling response chunks.
    ///
    /// NOTE: consumes the sink half but not the stream half.
    /// Internally, we replace `self.sink` with a no-op
    /// placeholder so subsequent send() / finish_sending()
    /// surface a clear error (`send() after finish_sending()`).
    pub async fn finish_sending(&mut self) -> Result<(), RpcError> {
        // Take the sink out by swapping in a placeholder whose
        // state is `Done` so subsequent sends error cleanly.
        let placeholder = DuplexSink {
            inner: Arc::clone(&self.sink.inner),
            service: String::new(),
            initial_headers: Vec::new(),
            initial_flags: 0,
            deadline_ns: 0,
            credit_sem: None,
            grant_pump: None,
            state: ClientStreamState::Done,
        };
        let sink = std::mem::replace(&mut self.sink, placeholder);
        sink.finish_sending().await
    }

    /// Pull the next response chunk. `None` on terminal Ok;
    /// `Some(Err)` then `None` on terminal non-Ok. Same shape as
    /// `futures::StreamExt::next`.
    pub async fn next(&mut self) -> Option<Result<Bytes, RpcError>> {
        use futures::StreamExt;
        self.stream.next().await
    }

    /// Split into independent send / receive halves. Both halves
    /// hold an `Arc<DuplexInner>`; CANCEL fires only when BOTH
    /// halves drop without a clean close.
    pub fn into_split(self) -> (DuplexSink, DuplexStream) {
        (self.sink, self.stream)
    }
}

impl futures::Stream for DuplexCallRaw {
    type Item = Result<Bytes, RpcError>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        std::pin::Pin::new(&mut self.stream).poll_next(cx)
    }
}

// ============================================================================
// Unary call: CANCEL-on-drop guard.
// ============================================================================

/// RAII guard that fires CANCEL to the server if the unary call
/// future is dropped before a response arrives. Without this, a
/// `select!`-loser future (e.g. hedge runner-up) would leave the
/// server-side handler running to completion — wasting CPU on a
/// reply nobody will read.
///
/// The guard is built *after* the REQUEST has been successfully
/// published — if the publish fails, no guard is constructed and
/// no CANCEL is sent. On the success path the call function flips
/// `completed = true` so Drop becomes a no-op (the server already
/// finished and removed its in-flight entry).
struct UnaryCallGuard {
    pending: Arc<crate::adapter::net::cortex::RpcClientPending>,
    mesh: Arc<MeshNode>,
    target_node_id: u64,
    request_channel: ChannelName,
    self_origin: u64,
    call_id: u64,
    /// True after the call resolved Ok or got a definitive
    /// non-cancellable Err. Drop checks this — `false` fires
    /// CANCEL, `true` is a no-op (still removes the pending
    /// entry).
    completed: bool,
}

impl Drop for UnaryCallGuard {
    fn drop(&mut self) {
        self.pending.cancel(self.call_id);
        if !self.completed {
            spawn_cancel_publish(
                Arc::clone(&self.mesh),
                self.target_node_id,
                self.request_channel.clone(),
                self.self_origin,
                self.call_id,
            );
        }
    }
}

// ============================================================================
// Streaming/duplex observer-fire bookkeeping.
//
// The unary `MeshNode::call` fires `RpcObserver::on_call` at each
// terminal return path (see line ~2306). The streaming /
// client-streaming / duplex paths have multiple terminal points
// (poll_next sees End / Error; finish() returns; Drop without
// terminal observation). To avoid sprinkling `fire_rpc_observer_outbound`
// at every terminal site, each handle holds a
// `StreamingObserverState` that latches the terminal status on
// observation and fires exactly once on Drop. The Deck NRPC tab
// + every consumer of `RpcObserver` get one event per streaming
// / duplex call, same as for unary today.
// ============================================================================

/// Per-call observer-fire bookkeeping shared between the
/// streaming + client-streaming + duplex caller-side handles.
/// Latches terminal status on observation; `fire()` (called from
/// the handle's Drop) emits one `RpcCallEvent` with the latched
/// status (or `Canceled` if nothing latched — i.e. the handle
/// was dropped before observing its terminator).
///
/// Status discriminator:
///   0 = none latched (Drop → Canceled)
///   1 = Ok
///   2 = Error (message in `observer_msg`)
///   3 = Timeout
pub(crate) struct StreamingObserverState {
    mesh: Arc<MeshNode>,
    target_node_id: u64,
    service: String,
    started: Instant,
    request_bytes: AtomicU32,
    response_bytes: AtomicU32,
    observer_status: AtomicU8,
    observer_msg: parking_lot::Mutex<Option<String>>,
    fired: AtomicBool,
}

impl StreamingObserverState {
    pub(crate) fn new(
        mesh: Arc<MeshNode>,
        target_node_id: u64,
        service: impl Into<String>,
        request_bytes: u32,
    ) -> Self {
        Self {
            mesh,
            target_node_id,
            service: service.into(),
            started: Instant::now(),
            request_bytes: AtomicU32::new(request_bytes),
            response_bytes: AtomicU32::new(0),
            observer_status: AtomicU8::new(0),
            observer_msg: parking_lot::Mutex::new(None),
            fired: AtomicBool::new(false),
        }
    }

    pub(crate) fn add_request_bytes(&self, n: u32) {
        self.request_bytes.fetch_add(n, Ordering::Relaxed);
    }

    pub(crate) fn add_response_bytes(&self, n: u32) {
        self.response_bytes.fetch_add(n, Ordering::Relaxed);
    }

    pub(crate) fn latch_ok(&self) {
        self.observer_status.store(1, Ordering::Relaxed);
    }

    pub(crate) fn latch_error(&self, msg: impl Into<String>) {
        *self.observer_msg.lock() = Some(msg.into());
        self.observer_status.store(2, Ordering::Relaxed);
    }

    pub(crate) fn latch_timeout(&self) {
        self.observer_status.store(3, Ordering::Relaxed);
    }

    /// Fire the observer event. Idempotent — only the first call
    /// actually emits; subsequent are no-ops. Called from each
    /// streaming handle's Drop.
    pub(crate) fn fire(&self) {
        if self.fired.swap(true, Ordering::SeqCst) {
            return;
        }
        let status_code = self.observer_status.load(Ordering::Relaxed);
        let status = match status_code {
            1 => crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Ok,
            2 => {
                let msg = self.observer_msg.lock().clone().unwrap_or_default();
                crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Error(msg)
            }
            3 => crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Timeout,
            _ => crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Canceled,
        };
        self.mesh.fire_rpc_observer_outbound(
            self.target_node_id,
            &self.service,
            self.started.elapsed().as_millis() as u32,
            status,
            self.request_bytes.load(Ordering::Relaxed),
            self.response_bytes.load(Ordering::Relaxed),
        );
    }
}

/// Per-call cap on in-flight request-direction credits. Tokio's
/// `Semaphore::MAX_PERMITS` is `usize::MAX >> 3`; we cap the
/// caller-side accumulator at this value so a misbehaving server
/// can't make the caller hold an unbounded outstanding window.
/// 1M credits is already orders of magnitude beyond any sane
/// request burst — a caller sitting on 1M unconsumed credits is
/// either misconfigured or under attack.
const REQUEST_GRANT_PER_CALL_CAP: usize = 1_000_000;

/// Add `credits` to a caller-side request-direction credit
/// semaphore, capped so the accumulator never exceeds
/// [`REQUEST_GRANT_PER_CALL_CAP`]. Per-frame cap of `usize::MAX >> 4`
/// remains as a second line of defense against pathological frame
/// values.
fn add_request_grant_credits(sem: &tokio::sync::Semaphore, credits: u32) {
    if credits == 0 {
        return;
    }
    let current = sem.available_permits();
    let remaining = REQUEST_GRANT_PER_CALL_CAP.saturating_sub(current);
    let safe = (credits as usize).min(usize::MAX >> 4).min(remaining);
    if safe > 0 {
        sem.add_permits(safe);
    }
}

/// Build a coalescing REQUEST_GRANT emitter.
///
/// Naive emitters `tokio::spawn` one publish task per consumed
/// chunk, which becomes a spawn-storm + AEAD-storm under bursting.
/// This helper hands back an emitter that pushes `(caller_origin,
/// call_id, credits)` into an unbounded mpsc; a single dedicated
/// drainer task `try_recv`s the queue to drain whatever is
/// immediately available, coalesces credits per call_id, and
/// publishes ONE batched REQUEST_GRANT per call per drain cycle.
///
/// Lifecycle: the drainer task lives as long as any clone of the
/// returned emitter (mpsc sender count > 0). When the fold and all
/// in-flight handlers release the emitter, `rx.recv` returns `None`
/// and the drainer exits naturally.
/// R3-1 / Gate-3 routing policy for an upload REQUEST_GRANT. A grant is a
/// server→caller frame on the caller's reply channel, so it funnels through
/// the SAME session-scoped router as responses.
///
/// This runs ONLY for admitted flow-controlled calls: a REQUEST whose caller
/// session is relayed/untrusted is rejected at admission, BEFORE the fold or
/// this emitter runs (see [`reject_relayed_flow_controlled_request`] /
/// [`classify_request_grant_route`]). So here a nonzero `from_node` provably
/// names the caller's OWN AEAD-authenticated session
/// ([`RequestGrantRoute::TrustedDirect`]), never a relay — the false "nonzero
/// last hop ⟹ direct" invariant is ENFORCED upstream, not assumed here:
///
/// - a trusted direct route (`from_node != 0`) is `DirectOnly` to that
///   authenticated session — the grant is DROPPED, never roster-fanned to a
///   same-origin sibling, if the session vanished (the server fold binds
///   continuation frames to the original session anyway, so a sibling's
///   request semaphore must never be refilled by it);
/// - the loopback / test sentinel (`from_node == 0`,
///   [`RequestGrantRoute::Loopback`]) keeps the roster path so local/test
///   behavior is preserved.
fn request_grant_route(from_node: u64) -> (Option<u64>, ResponseRouteFallback) {
    if from_node != 0 {
        (Some(from_node), ResponseRouteFallback::DirectOnly)
    } else {
        (None, ResponseRouteFallback::RosterOnStaleDirect)
    }
}

fn build_request_grant_emitter(
    mesh: Arc<MeshNode>,
    service: String,
    server_origin: u64,
    diag_tag: &'static str,
) -> RpcRequestGrantEmitter {
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<(u64, u64, u64, u32)>();
    tokio::spawn(async move {
        while let Some(first) = rx.recv().await {
            // R3-1: coalesce by the FULL session-scoped call identity
            // `(from_node, caller_origin, call_id)`, never `(origin,
            // call_id)` alone — two authenticated sessions that share one
            // entity/origin and picked the same caller-chosen call_id no
            // longer collapse into one grant that would refill the wrong
            // call's upload semaphore.
            let mut summed: std::collections::HashMap<(u64, u64, u64), u32> =
                std::collections::HashMap::new();
            let (from_node, caller, call_id, credits) = first;
            summed.insert((from_node, caller, call_id), credits);
            // Coalesce anything immediately queued behind the first
            // wake. Bounded by what the substrate has produced so
            // far; doesn't add latency since `try_recv` returns
            // immediately when the queue is empty.
            while let Ok((from_node, caller, call_id, credits)) = rx.try_recv() {
                let entry = summed.entry((from_node, caller, call_id)).or_insert(0);
                *entry = entry.saturating_add(credits);
            }
            for ((from_node, caller, call_id), credits) in summed {
                let reply_channel_name = format!("{service}.replies.{caller:016x}");
                let reply_channel = match ChannelName::new(&reply_channel_name) {
                    Ok(c) => c,
                    Err(e) => {
                        tracing::warn!(
                            error = %e,
                            channel = %reply_channel_name,
                            tag = diag_tag,
                            "rpc grant drainer: invalid reply channel name");
                        continue;
                    }
                };
                let reply_channel_id = ChannelId::new(reply_channel.clone());
                let reply_channel_hash = reply_channel_id.hash();
                let reply_stream_id = MeshNode::publish_stream_id(&reply_channel_id);
                let meta = EventMeta::new(DISPATCH_RPC_REQUEST_GRANT, 0, server_origin, call_id, 0);
                // `meta ‖ grant`; `publish_response_to_caller` inserts the
                // RpcRouteV1 discriminator centrally (matches the response
                // path), so no manual `encode_rpc_route` here.
                let mut buf = Vec::with_capacity(EVENT_META_SIZE + 12);
                buf.extend_from_slice(&meta.to_bytes());
                buf.extend_from_slice(&encode_request_grant(call_id, credits));
                let (target_hint, fallback) = request_grant_route(from_node);
                if let Err(e) = publish_response_to_caller(
                    &mesh,
                    caller,
                    target_hint,
                    &reply_channel,
                    reply_channel_hash,
                    reply_stream_id,
                    Bytes::from(buf),
                    fallback,
                )
                .await
                {
                    tracing::warn!(
                        error = %e,
                        caller_origin = format!("{:#x}", caller),
                        call_id,
                        tag = diag_tag,
                        "rpc grant drainer: REQUEST_GRANT publish failed");
                }
            }
        }
    });
    Arc::new(move |from_node, caller_origin, call_id, credits| {
        // Send failure means the drainer has exited (all sender
        // clones dropped, then we somehow cloned a stale one).
        // Treat as a no-op — the call is tearing down anyway.
        let _ = tx.send((from_node, caller_origin, call_id, credits));
    })
}

/// Per-service map from a call `(caller origin_hash, call_id)` to the
/// AEAD-verified `from_node` of the session that delivered that
/// inbound REQUEST. Populated by the serve_rpc bridge tasks at
/// REQUEST-receipt time; consulted by [`publish_response_to_caller`]
/// to skip the roster fan-out on the response leg.
///
/// **Call-scoped** (AV-4 item 4): keying on `(origin, call_id)` rather
/// than `origin` alone means two authenticated sessions that share one
/// entity/origin (a caller reconnecting under a new NodeId, or the same
/// entity running on two nodes) route each response to the node that
/// actually issued THAT call, instead of clobbering one another's
/// destination. Entries are retired when the call's terminal RESPONSE
/// is emitted (which also covers the cancel / deadline / fold-rejection
/// paths, since each of those emits a terminal frame); bridge teardown
/// drops the whole cache with the registration.
///
/// Lives per `serve_rpc*` registration rather than mesh-wide because
/// the source-of-truth `MeshNode::origin_hash_to_node` is only safe
/// to populate from *signed* capability announcements — populating
/// it from unsigned wire `origin_hash` fields would let any session
/// peer pre-claim arbitrary origins. This map is bridge-local and
/// only used by the matching service's response emit, so a malicious
/// peer can at most misdirect responses for THEIR own request — they
/// already could.
///
/// **Bounded** ([`BoundedLru`]): the LRU caps the footprint under a
/// crafted-origin flood.
///
/// The insert is on the ACCEPT path only — `cache_authenticated_response_destination`
/// runs after the gate on both the public bridge
/// ([`MeshNode::bridge_preflight`]) and the protected one
/// ([`MeshNode::admit_and_dispatch_protected`]) — so a rejected caller
/// never occupies a slot. (This ordering was inverted relative to an
/// earlier revision of this comment, which described the insert as
/// preceding the gate.)
///
/// **What an eviction costs depends on the registration mode.** For a
/// legacy public service it is a response-path cache miss that falls back
/// to the roster — availability-neutral. For an org-protected service it
/// is a DROPPED response and a caller timeout, because those registrations
/// are [`ResponseRouteFallback::DirectOnly`] and must never roster-fan an
/// org-confidential body onto a permissive reply channel (see
/// [`UnaryAdmission::response_route_fallback`]). Eviction is therefore
/// never a *confidentiality* event in either mode, but it is not free for
/// protected services — size this cap against their concurrency.
type RpcOriginNodeCache = Arc<BoundedLru<(u64, u64, u64), u64>>;

/// Capacity bound for the per-`serve_rpc` caller-keyed caches
/// ([`RpcOriginNodeCache`] and the §8b reply-channel cache). Sized for the
/// legitimate active-caller working set of a single service; well past it the
/// LRU evicts cold origins rather than growing without limit under a
/// crafted-origin flood. Each entry is tiny (a `u64` and, for the reply
/// cache, an `Arc<str>` channel name), so the whole bound is a few hundred KB
/// per service.
const RPC_CALLER_CACHE_CAP: usize = 4096;

/// Non-zero form of [`RPC_CALLER_CACHE_CAP`], validated at compile time so
/// `BoundedLru::new` carries no runtime `unwrap`/`expect`. A zero cap
/// would fail the build here rather than panic at startup.
const RPC_CALLER_CACHE_CAP_NZ: std::num::NonZeroUsize =
    match std::num::NonZeroUsize::new(RPC_CALLER_CACHE_CAP) {
        Some(n) => n,
        None => panic!("RPC_CALLER_CACHE_CAP must be non-zero"),
    };

/// Thread-safe, bounded LRU. Backs both the call-scoped
/// [`RpcOriginNodeCache`] (keyed `(origin, call_id)`, AV-4 item 4) and
/// the §8b reply-channel cache (keyed `origin`). Wraps `lru::LruCache`
/// (which needs `&mut` even to read, to bump the entry to
/// most-recently-used) in a `parking_lot::Mutex`. The per-response lock
/// is uncontended in the common case — one fold drives a given service
/// — and is far cheaper than the `format!` + `ChannelName` allocation /
/// roster fan-out the caches exist to avoid.
///
/// Eviction is always *safe*, but not always free: for the reply-channel
/// cache a miss just recomputes the channel name, and for the
/// [`RpcOriginNodeCache`] a miss costs a roster fallback on public
/// services and a dropped response on protected ones. See that type's
/// docs.
struct BoundedLru<K, V>(Mutex<lru::LruCache<K, V>>);

impl<K: std::hash::Hash + Eq, V: Clone> BoundedLru<K, V> {
    fn new() -> Self {
        Self(Mutex::new(lru::LruCache::new(RPC_CALLER_CACHE_CAP_NZ)))
    }

    /// Look up `key`, promoting it to most-recently-used on a hit.
    fn get(&self, key: K) -> Option<V> {
        self.0.lock().get(&key).cloned()
    }

    /// Insert / refresh `key`, evicting the least-recently-used entry
    /// when at capacity.
    fn insert(&self, key: K, value: V) {
        self.0.lock().put(key, value);
    }

    /// Retire `key` (AV-4 item 4 lifecycle retirement). Idempotent —
    /// removing an absent key is a no-op.
    fn remove(&self, key: K) {
        self.0.lock().pop(&key);
    }
}

/// Direct-send a built RESPONSE (or streaming chunk) packet to the
/// caller's reply channel, bypassing the roster fan-out path
/// [`MeshNode::publish`] uses.
///
/// **Fast path:** when the bridge has cached the caller's
/// `from_node` (i.e. the server processed an inbound REQUEST from
/// this caller via an AEAD-authenticated session), or when the
/// caller's capability announcement has reached us, the response
/// rides `publish_to_peer` — one DashMap lookup instead of roster
/// lookup + ACL check + subnet filter + per-recipient `Vec<Bytes>`
/// allocation.
///
/// **Fallback:** when neither lookup resolves — pathological cases
/// like a test harness where the caller never announces and the
/// bridge cache is empty — fall back to [`MeshNode::publish`] via
/// the roster, matching the pre-T1.2 behavior verbatim.
/// PERF_AUDIT §3.10 — accepts pre-computed
/// `reply_channel_hash` and `reply_stream_id` so the per-response
/// path doesn't re-run `ChannelId::new` + xxh3 + `publish_stream_id`
/// on every send. The emit closure's `BoundedLru<u64, CachedReplyChannel>`
/// caches the triple per caller_origin.
/// Routing policy for a server→caller frame when the resolved direct
/// route has no live session at send time (R2-7).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ResponseRouteFallback {
    /// AV-5: a normal RESPONSE frame. An honest caller that reconnected
    /// under a new NodeId (its cached direct route went stale) is still
    /// reachable via its *signed* subscriber roster subscription, so a
    /// pre-send miss falls back to the roster fan-out rather than
    /// dropping the response.
    RosterOnStaleDirect,
    /// NC2 / R2-7: a capability denial (or any authenticated-only frame)
    /// is delivered ONLY to the AEAD-authenticated session peer named by
    /// the explicit `target_hint`. If that session is gone the frame is
    /// DROPPED — never resolved via the origin reverse-index and never
    /// fanned out to a (possibly forged) claimed origin's roster channel,
    /// which is exactly the reflection NC2 forbids.
    DirectOnly,
}

// The reply-channel triple (`reply_channel`, `reply_channel_hash`,
// `reply_stream_id`) is deliberately passed pre-split rather than bundled:
// PERF_AUDIT §3.10 computes and caches the hash + stream_id per caller so
// the emit hot path never re-derives them, and every call site already
// holds the three values separately. Adding the R2-7 `fallback` policy
// pushes this focused internal helper to 8 args — the same accepted
// tradeoff the crate makes in ~24 other places.
#[allow(clippy::too_many_arguments)]
async fn publish_response_to_caller(
    mesh: &MeshNode,
    caller_origin: u64,
    target_hint: Option<u64>,
    reply_channel: &ChannelName,
    reply_channel_hash: ChannelHash,
    reply_stream_id: u64,
    payload: Bytes,
    fallback: ResponseRouteFallback,
) -> Result<(), AdapterError> {
    // OA2-E0.2: every server→caller frame (RESPONSE / DEADLINE /
    // REQUEST_GRANT / STREAM_GRANT built for the reply channel)
    // funnels through here, so insert the RpcRouteV1 discriminator —
    // the reply channel's canonical hash — once, centrally. The
    // caller's mesh ingress selects exactly this dispatcher.
    let payload = crate::adapter::net::cortex::insert_rpc_route(payload, reply_channel_hash);
    // A `DirectOnly` frame trusts ONLY the explicit `target_hint` (the
    // AEAD-authenticated session peer): it must never resolve a
    // destination through the origin reverse-index, which could point at
    // a different node claiming this origin (NC2). A normal RESPONSE may
    // resolve the caller's node via the reverse-index when no hint is
    // cached.
    let resolved = match fallback {
        ResponseRouteFallback::DirectOnly => target_hint,
        ResponseRouteFallback::RosterOnStaleDirect => {
            target_hint.or_else(|| mesh.get_node_by_origin_hash(caller_origin))
        }
    };
    // R2-6: attempt the direct send and branch on the ATOMIC typed
    // outcome, eliminating the `has_peer_session`-then-`publish` TOCTOU
    // that AV-5 used. `try_publish_to_peer` makes the session-existence
    // check its single gate:
    //
    // - `Sent`       — the frame reached the socket; done.
    // - `SendFailed` — a failure at/after transmission; MUST NOT be
    //                  retried on the roster (that would duplicate).
    // - `NoSession`  — no session existed at send time, so nothing was
    //                  transmitted. Safe to fall back per `fallback`.
    if let Some(target_node_id) = resolved {
        match mesh
            .try_publish_to_peer(
                target_node_id,
                reply_channel_hash,
                reply_stream_id,
                /* reliable */ true,
                std::slice::from_ref(&payload),
            )
            .await
        {
            PeerPublishOutcome::Sent => return Ok(()),
            PeerPublishOutcome::SendFailed(e) => return Err(e),
            PeerPublishOutcome::NoSession => {
                if fallback == ResponseRouteFallback::DirectOnly {
                    // The authenticated peer's session vanished. Drop the
                    // frame — a denial must never reflect onto a claimed
                    // origin's roster channel (NC2).
                    tracing::debug!(
                        caller_origin = format!("{caller_origin:#x}"),
                        target_node = format!("{target_node_id:#x}"),
                        "rpc direct-only frame: peer session gone at send time; dropping",
                    );
                    return Ok(());
                }
                tracing::debug!(
                    caller_origin = format!("{caller_origin:#x}"),
                    target_node = format!("{target_node_id:#x}"),
                    "rpc response: resolved route has no peer session; roster fallback",
                );
            }
        }
    } else if fallback == ResponseRouteFallback::DirectOnly {
        // No explicit direct target to unicast to — a direct-only frame
        // has nowhere authenticated to go, so drop it rather than
        // roster-fanning it out.
        return Ok(());
    }
    // Fallback: roster fan-out. Reached only for `RosterOnStaleDirect`
    // when the caller's origin is unknown to both the bridge cache AND
    // the global reverse index, OR the resolved node had no live session
    // at send time (nothing was sent).
    let publisher = ChannelPublisher::new(reply_channel.clone(), PublishConfig::default());
    mesh.publish(&publisher, payload).await.map(|_| ())
}

/// The runtime a client call was opened on, for [`spawn_cancel_publish`]
/// to fall back to when Drop runs somewhere else.
///
/// Every client call is *created* inside a runtime, but it is not always
/// *dropped* inside one. The owner can be a Python object freed by
/// CPython's GC on the asyncio thread, a handle released across the C
/// FFI, or a plain `drop()` in sync Rust — none of which have an ambient
/// reactor. `tokio::spawn` panics there, and a panic in a `Drop` reached
/// from `tp_dealloc` surfaces as an unraisable exception nobody can
/// catch.
///
/// One handle for the process, not one per call: these calls all belong
/// to the same `MeshNode`, and storing a `Handle` on four structs to say
/// the same thing costs more than it explains.
static CANCEL_PUBLISH_RT: std::sync::OnceLock<tokio::runtime::Handle> = std::sync::OnceLock::new();

/// Record the current runtime as the one to fire CANCEL frames on.
///
/// Called when a client call is opened — always from an `async fn`, so
/// `try_current` always succeeds there. Idempotent, and first writer
/// wins.
pub(crate) fn remember_cancel_publish_runtime() {
    if let Ok(handle) = tokio::runtime::Handle::try_current() {
        let _ = CANCEL_PUBLISH_RT.set(handle);
    }
}

/// Shared CANCEL-publish helper: spawn a task that fires a
/// CANCEL event for `call_id` to `target` on the request channel.
/// Both [`RpcStream::Drop`] and [`UnaryCallGuard::Drop`] use it.
///
/// Never panics on a foreign thread: prefers the ambient runtime, falls
/// back to the one the call was opened on, and degrades to a log if
/// neither exists (the process is tearing down, and the peer's
/// keep-alive expiry is the backstop).
fn spawn_cancel_publish(
    mesh: Arc<MeshNode>,
    target: u64,
    request_channel: ChannelName,
    self_origin: u64,
    call_id: u64,
) {
    let handle = tokio::runtime::Handle::try_current()
        .ok()
        .or_else(|| CANCEL_PUBLISH_RT.get().cloned());
    let Some(handle) = handle else {
        tracing::debug!(
            call_id,
            target_node = format!("{target:#x}"),
            "rpc CANCEL: no runtime to publish on (dropped during teardown); \
             relying on the peer's keep-alive expiry",
        );
        return;
    };
    handle.spawn(async move {
        let meta = EventMeta::new(DISPATCH_RPC_CANCEL, 0, self_origin, call_id, 0);
        let request_channel_id = ChannelId::new(request_channel);
        let request_channel_hash = request_channel_id.hash();
        let stream_id = MeshNode::publish_stream_id(&request_channel_id);
        // OA2-E0.2: CANCEL is meta-only (no frame payload) — the
        // RpcRouteV1 discriminator still rides so ingress selects the
        // exact request dispatcher, never a bucket-colliding sibling.
        let mut buf = meta.to_bytes().to_vec();
        encode_rpc_route(&mut buf, request_channel_hash);
        let payload = Bytes::from(buf);
        let _ = mesh
            .publish_to_peer(
                target,
                request_channel_hash,
                stream_id,
                /* reliable */ true,
                std::slice::from_ref(&payload),
            )
            .await;
    });
}

/// Type alias for the keep-alive sender that streaming-call handles
/// store. Its purpose is *only* to signal "stream done" when the
/// handle drops: the cancel-watcher task `select!`s on the matching
/// receiver, and dropping the sender (which happens on handle Drop)
/// resolves the receiver with an `Err` so the watcher exits cleanly.
///
/// `()` payload because the signal IS the resolution; no data is
/// transmitted.
type StreamCancelKeepAlive = tokio::sync::oneshot::Sender<()>;

/// Spawn a cancel-watcher task for a streaming call (call_streaming,
/// call_client_stream, call_duplex). The watcher races
/// `cancel_notify.notified()` against the keep-alive oneshot — first
/// to fire wins. On cancel, the watcher drops the pending-streaming
/// entry (which closes the receiver's mpsc, letting the stream's
/// poll_next observe EOF), then releases the registry entry. On
/// handle Drop, the keep-alive sender drops, the oneshot resolves
/// `Err`, and the watcher exits via the done arm with a registry
/// release.
///
/// When `cancel_token == 0` (the "no token" sentinel), this is a
/// no-op: the returned sender is a placeholder whose drop has no
/// observable effect, and no task is spawned. Lets the streaming
/// call shapes always store a keep-alive on the returned handle
/// without branching on whether a token was set.
fn spawn_stream_cancel_watcher(
    cancel_notify: Arc<tokio::sync::Notify>,
    cancel_token: u64,
    cancel_registry: Arc<crate::adapter::net::cancel_registry::CancelRegistry>,
    pending: Arc<crate::adapter::net::cortex::RpcClientPending>,
    call_id: u64,
) -> StreamCancelKeepAlive {
    let (done_tx, done_rx) = tokio::sync::oneshot::channel();
    if cancel_token == 0 {
        // No-op fast path. The returned sender is held by the
        // handle but never paired with a watcher, so its eventual
        // drop has no effect. Avoids spawning a task per
        // cancel-less stream.
        return done_tx;
    }
    tokio::spawn(async move {
        tokio::select! {
            biased;
            _ = cancel_notify.notified() => {
                // Cancel fired. Drop the pending-stream entry so
                // the receiver's mpsc closes (causing the stream's
                // poll_next to observe EOF via Ready(None)). The
                // handle's Drop will then fire CANCEL on the wire
                // via its existing per-shape Drop impl.
                pending.cancel(call_id);
                cancel_registry.release(cancel_token);
            }
            _ = done_rx => {
                // Stream completed normally — sender dropped on
                // handle Drop, recv returns Err. Just release the
                // registry entry; no CANCEL emission needed (the
                // handle's Drop handles that path itself if it
                // wasn't a clean close).
                cancel_registry.release(cancel_token);
            }
        }
    });
    done_tx
}

/// One-call helper that registers a cancel-notify against the
/// caller's `opts.cancel_token` and spawns the stream cancel
/// watcher. Used by every streaming call shape (`call_streaming`,
/// `call_client_stream`, `call_duplex`) to keep their bodies free
/// of the three-step token/notify/spawn boilerplate.
///
/// When `opts.cancel_token` is `None` (or `Some(0)`), this is the
/// same no-op fast path as [`spawn_stream_cancel_watcher`].
fn arm_stream_cancel(
    mesh: &Arc<MeshNode>,
    opts: &CallOptions,
    pending: &Arc<crate::adapter::net::cortex::RpcClientPending>,
    call_id: u64,
) -> StreamCancelKeepAlive {
    let cancel_token = opts.cancel_token.unwrap_or(0);
    let cancel_notify = mesh.cancel_registry().register_notify(cancel_token);
    spawn_stream_cancel_watcher(
        cancel_notify,
        cancel_token,
        Arc::clone(mesh.cancel_registry()),
        Arc::clone(pending),
        call_id,
    )
}

/// Side-effects + return value for the unary `call`'s cancel
/// branch. Releases the registry entry, records the Transport
/// outcome on the metrics guard, fires the Canceled observer
/// event, and returns `RpcError::Cancelled`. Both the
/// no-deadline and with-deadline `select!` arms invoke this so a
/// shape change to the cancel outcome (extra metric, new field
/// on the observer event) lands in exactly one place.
fn fire_unary_cancel_outcome(
    mesh: &Arc<MeshNode>,
    metrics_guard: &mut crate::adapter::net::mesh_rpc_metrics::CallMetricsGuard,
    cancel_token: u64,
    target_node_id: u64,
    service: &str,
    started_total: Instant,
    request_bytes_len: u32,
) -> RpcError {
    mesh.cancel_registry().release(cancel_token);
    metrics_guard.record(crate::adapter::net::mesh_rpc_metrics::CallOutcome::Transport);
    mesh.fire_rpc_observer_outbound(
        target_node_id,
        service,
        started_total.elapsed().as_millis() as u32,
        crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Canceled,
        request_bytes_len,
        0,
    );
    RpcError::Cancelled
}

// ============================================================================
// MeshNode extensions.
// ============================================================================

impl MeshNode {
    /// Register an nRPC handler for `service` on this node.
    ///
    /// Subscribes this node to `<service>.requests` (so the local
    /// `register_rpc_inbound` dispatcher feeds inbound REQUEST
    /// events into the [`RpcServerFold`]) and wires the fold's
    /// RESPONSE-emit callback to publish on
    /// `<service>.replies.<caller_origin>` via the existing
    /// pub/sub path.
    ///
    /// **Local-only registration** (Phase 1). Multi-instance
    /// services that load-balance via `SubscriptionMode::QueueGroup`
    /// require each replica to call `serve_rpc` on its own node;
    /// the mesh-level subscriber roster + `dispatch_recipients`
    /// then routes one-of-N as designed. Each replica's local
    /// `serve_rpc` must use the same service name (which becomes
    /// the queue-group identifier).
    ///
    /// Returns a [`ServeHandle`] whose Drop tears down the
    /// registration. Concurrent registrations for the same service
    /// on one node return `Err(ServeError::AlreadyServing)`.
    pub fn serve_rpc<H: RpcHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
    ) -> Result<ServeHandle, ServeError> {
        self.serve_rpc_unary_impl(service, handler, UnaryAdmission::Public)
    }

    /// Register a PROTECTED unary RPC handler (E1.1/E1.2). Every call must carry
    /// a `net-org-admission` proof that [`verify_org_admission`] accepts under
    /// `admission` (owner-delegated or cross-org); the captured `provider_policy`
    /// is the final application veto. REQUIRES an installed node authority (else
    /// [`ServeError::ProtectedAuthorityRequired`]) and an org-protected mode
    /// (never `PublicAuthenticated`). Unary only (E1.8). Denied calls receive
    /// [`RpcStatus::AdmissionDenied`] (0x0009 + a coarse reason); the handler
    /// runs ONLY on an admitted call and reads the four-party attribution via
    /// [`RpcContext::org_admission`](crate::adapter::net::cortex::RpcContext).
    ///
    /// [`verify_org_admission`]: crate::adapter::net::behavior::org_admission::verify_org_admission
    pub fn serve_rpc_protected<H: RpcHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
        admission: OrgAdmission,
        provider_policy: OrgProviderPolicy,
    ) -> Result<ServeHandle, ServeError> {
        if matches!(admission, OrgAdmission::PublicAuthenticated) {
            return Err(ServeError::InvalidProtectedRegistration(
                "admission mode must be org-protected (OwnerDelegated / CrossOrgGranted), \
                 not PublicAuthenticated"
                    .to_string(),
            ));
        }
        // E1.1: protected registration requires an installed authority — checked
        // up front so the registration below cannot half-succeed then unwind.
        if self.node_authority().is_none() {
            return Err(ServeError::ProtectedAuthorityRequired(service.to_string()));
        }
        self.serve_rpc_unary_impl(
            service,
            handler,
            UnaryAdmission::Protected {
                admission,
                provider_policy,
            },
        )
    }

    /// Register a SUBNET-EXPORTED unary RPC handler (SUBNET_AUTH_PLAN.md
    /// D7): everything [`Self::serve_rpc_protected`] requires, PLUS an
    /// immutable binding of this service to ONE exact declared subnet
    /// crossing. The call's execution is conditioned on this node
    /// CURRENTLY holding the authority to export through that crossing —
    /// gateway credentials with exact `EXPORT` at the bound path, the
    /// path declared in the live [`SubnetBoundarySet`], matching
    /// topology/auth epochs, unexpired — revalidated on EVERY call
    /// before organization admission. The external caller proves org
    /// admission and never joins this node's subnet.
    ///
    /// Registration fails up front when the shape is impossible NOW
    /// ([`ServeError::SubnetExportUnauthorized`]); passing here is not
    /// standing authority — credentials replace wholesale, boundaries
    /// replace wholesale, floors and epochs move, and any of those
    /// darkens the live service until exact current authority returns.
    ///
    /// [`SubnetBoundarySet`]: crate::adapter::net::subnet::SubnetBoundarySet
    pub fn serve_rpc_subnet_exported<H: RpcHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
        admission: OrgAdmission,
        export: SubnetExportBinding,
        provider_policy: OrgProviderPolicy,
    ) -> Result<ServeHandle, ServeError> {
        if matches!(admission, OrgAdmission::PublicAuthenticated) {
            return Err(ServeError::InvalidProtectedRegistration(
                "admission mode must be org-protected (OwnerDelegated / CrossOrgGranted), \
                 not PublicAuthenticated"
                    .to_string(),
            ));
        }
        if self.node_authority().is_none() {
            return Err(ServeError::ProtectedAuthorityRequired(service.to_string()));
        }
        // Registration-time shape check: the declared boundary must exist
        // exactly and this node must hold current exact EXPORT authority
        // at it. This prevents a service from STARTING in an impossible
        // shape; the per-call revalidation in the dispatch gate is the
        // authority decision.
        let clock = crate::adapter::net::behavior::admission_clock::ClockSample::now();
        if let Err(denied) =
            crate::adapter::net::org_admission_gate::verify_subnet_export(self, &export, &clock)
        {
            return Err(ServeError::SubnetExportUnauthorized(format!(
                "{service}: {denied:?}"
            )));
        }
        self.serve_rpc_unary_impl(
            service,
            handler,
            UnaryAdmission::SubnetExported {
                admission,
                export,
                provider_policy,
            },
        )
    }

    /// Test-only (review-7 RED negative control): register a protected service
    /// whose dispatch bypasses ONLY `verify_org_admission`. NOT a production API —
    /// compiled out without `cfg(test)`. Requires an installed authority and an
    /// org-protected mode, exactly like [`Self::serve_rpc_protected`]; the sole
    /// difference is the disabled admission flag on the captured registration.
    #[cfg(test)]
    pub(crate) fn serve_rpc_protected_red_witness_disabled<H: RpcHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
        admission: OrgAdmission,
        provider_policy: OrgProviderPolicy,
    ) -> Result<ServeHandle, ServeError> {
        if matches!(admission, OrgAdmission::PublicAuthenticated) {
            return Err(ServeError::InvalidProtectedRegistration(
                "admission mode must be org-protected".to_string(),
            ));
        }
        if self.node_authority().is_none() {
            return Err(ServeError::ProtectedAuthorityRequired(service.to_string()));
        }
        self.serve_rpc_unary_impl(
            service,
            handler,
            UnaryAdmission::ProtectedRedWitnessDisabled {
                admission,
                provider_policy,
            },
        )
    }

    /// Register an OWNER-SCOPED unary RPC handler (OA3-4b1): an internal private
    /// capability of this node's OWN org. Its `nrpc:<service>` tag is NEVER
    /// broadcast in the clear — the capability is emitted only as an encrypted
    /// owner-audience `ScopedCapabilityAnnouncement` — but it enters the local
    /// self-fold so [`OrgAdmission::OwnerDelegated`] admission can dispatch it.
    /// REQUIRES an installed node authority (the owner audience credential; else
    /// [`ServeError::ProtectedAuthorityRequired`]). Unary only (E1.8).
    pub fn serve_rpc_owner_scoped<H: RpcHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
        provider_policy: OrgProviderPolicy,
    ) -> Result<ServeHandle, ServeError> {
        // Owner-scoped registration requires an installed authority — both for
        // the `OwnerDelegated` admission gate and for the owner audience
        // credential the encrypted emission consumes.
        if self.node_authority().is_none() {
            return Err(ServeError::ProtectedAuthorityRequired(service.to_string()));
        }
        self.serve_rpc_unary_impl(
            service,
            handler,
            UnaryAdmission::OwnerScoped { provider_policy },
        )
    }

    /// Register a GRANTED-AUDIENCE unary RPC handler (OA3-4b2): a cross-org private
    /// capability. Its `nrpc:<service>` tag is NEVER broadcast in the clear — the
    /// capability is emitted only as an encrypted grant-audience
    /// `ScopedCapabilityAnnouncement`, one envelope per active provider grant
    /// record — but it enters the local self-fold so
    /// [`OrgAdmission::CrossOrgGranted`] admission can dispatch it. The invoke gate
    /// is identical to [`Self::serve_rpc_protected`] with `CrossOrgGranted`; the two
    /// differ ONLY in discovery visibility (protected = public discovery, granted =
    /// grant-audience-private discovery). REQUIRES an installed node authority.
    /// Registering BEFORE a matching grant is installed is fail-closed: the service
    /// is dispatchable but undiscoverable until a provider grant is installed (which
    /// wakes a coherent reannouncement). Unary only (E1.8).
    pub fn serve_rpc_granted<H: RpcHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
        provider_policy: OrgProviderPolicy,
    ) -> Result<ServeHandle, ServeError> {
        // Granted registration requires an installed authority — both to bind this
        // node's owner org (the grant issuer) and because the granted emission
        // consumes the provider grant/secret store, which is meaningless without one.
        if self.node_authority().is_none() {
            return Err(ServeError::ProtectedAuthorityRequired(service.to_string()));
        }
        self.serve_rpc_unary_impl(
            service,
            handler,
            UnaryAdmission::Granted { provider_policy },
        )
    }

    /// Shared unary serve implementation for the public [`Self::serve_rpc`] and
    /// protected [`Self::serve_rpc_protected`] wrappers. The bridge branches on
    /// the captured [`RegisteredRpcService`]'s admission mode: public runs the
    /// v0.4 `may_execute` gate; protected runs the E1.2 org-admission gate.
    fn serve_rpc_unary_impl<H: RpcHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
        mode: UnaryAdmission,
    ) -> Result<ServeHandle, ServeError> {
        let request_channel = ChannelName::new(&format!("{service}.requests"))
            .map_err(|e| ServeError::InvalidServiceName(e.to_string()))?;
        let channel_hash = request_channel.hash();
        // The channel policy nRPC requires is installed here, by the
        // one seam every serve shape passes through, before anything
        // is registered, advertised, or spawned.
        //
        // It used to be the SDK wrapper's job. Node, Python and Go/C
        // call `MeshNode::serve_rpc*` directly and never did it, so on
        // their strict-by-default registries a successful registration
        // still could not complete a single call: `<service>.requests`
        // and `<service>.replies.*` were unknown channels and every
        // request was refused. A protocol prerequisite belongs to the
        // protocol, not to whichever wrapper remembers.
        //
        // Install-if-absent, so an operator ACL registered before
        // serving survives untouched.
        if let Some(registry) = self.channel_configs() {
            registry.install_rpc_service_defaults(service)?;
        }

        // Captured before `mode` is consumed below. An org-protected
        // registration NEVER roster-fans its responses — see
        // [`UnaryAdmission::response_route_fallback`].
        let response_fallback = mode.response_route_fallback();

        // Bridge: a tokio mpsc the inbound dispatcher pushes into.
        // The bridge task drains it and runs each event through
        // the fold. Bounded so a runaway publisher can't OOM the
        // server; over-cap pushes drop the inbound event (which
        // surfaces to the caller as a timeout).
        let (tx, mut rx) = mpsc::channel::<RpcInboundEvent>(1024);

        // T1.2 cache: maps each caller's wire `origin_hash` to the
        // AEAD-verified `from_node` of the session that delivered
        // its REQUEST. Populated by the bridge below; consumed by
        // the emit closure so [`publish_response_to_caller`] can
        // skip the roster fan-out on the response leg.
        let origin_node_cache: RpcOriginNodeCache = Arc::new(BoundedLru::new());

        // Build the emit closure. When the handler completes, the
        // fold calls this (synchronously) with `(caller_origin, call_id,
        // response)`. §8a: instead of `tokio::spawn`ing a task per response,
        // the closure builds the wire payload (cheap, no await) and hands a
        // job to a single per-service response drainer task (below), which
        // does the `.await` publish. A `tokio::spawn` per response cost
        // ~1–2 µs of scheduling on a wake-bound path; a channel send is a
        // fraction of that, and the drainer amortizes the wakeup.
        let service_for_emit = service.to_string();
        let server_origin = self.identity_origin_hash();
        let origin_node_cache_for_emit = Arc::clone(&origin_node_cache);
        // §8b reply-channel cache: the reply channel name is
        // `<service>.replies.<caller_origin:016x>` — deterministic from
        // `(service, caller_origin)`, and `service` is fixed for this
        // `serve_rpc`, so it varies only by `caller_origin`. `ChannelName` is
        // `Arc<str>`, so a cache hit is an Arc bump; this removes the per-
        // response `format!` String + `ChannelName::new` (`Arc<str>`) allocation
        // (and the per-call `service.clone()`) the emit closure used to pay on
        // every response. Keyed by the wire-claimed `caller_origin` and so
        // bounded the same way as `origin_node_cache` above — an
        // `BoundedLru`, not an unbounded map, so a crafted-origin flood
        // can't amplify server memory (a miss just rebuilds the name).
        // PERF_AUDIT §3.10 — cache the triple (name, hash, stream_id)
        // per caller_origin so the per-response drainer doesn't
        // recompute xxh3 + publish_stream_id on every send.
        let reply_channel_cache: Arc<BoundedLru<u64, CachedReplyChannel>> =
            Arc::new(BoundedLru::new());
        // §8a response drainer channel. Bounded like the inbound channel; a
        // full channel means the drainer can't keep up, so we drop (the
        // caller times out) rather than block the fold.
        let (resp_tx, mut resp_rx) = mpsc::channel::<RpcResponseJob>(1024);
        // §7 — a second handle for the protected bridge's DENIAL path, so a
        // denial is enqueued on the same bounded drainer as any other response
        // instead of being published inline. Mirrors `master`'s
        // `emit_for_bridge`, which existed for exactly this reason on the
        // capability-denial path.
        let resp_tx_for_denials = resp_tx.clone();
        let emit: RpcResponseEmitter = Arc::new(move |from_node, caller_origin, call_id, resp| {
            let target_hint = origin_node_cache_for_emit.get((from_node, caller_origin, call_id));
            // Resolve the reply channel from cache (Arc bump on hit; one
            // `format!` + `ChannelName::new` the first time we see a caller).
            let cached = match reply_channel_cache.get(caller_origin) {
                Some(c) => c,
                None => {
                    let name = format!("{service_for_emit}.replies.{caller_origin:016x}");
                    match ChannelName::new(&name) {
                        Ok(channel_name) => {
                            // Compute hash + stream_id ONCE per caller_origin
                            // and stash them alongside the name.
                            let channel_id = ChannelId::new(channel_name.clone());
                            let triple = CachedReplyChannel {
                                hash: channel_id.hash(),
                                stream_id: MeshNode::publish_stream_id(&channel_id),
                                name: channel_name,
                            };
                            reply_channel_cache.insert(caller_origin, triple.clone());
                            triple
                        }
                        Err(e) => {
                            tracing::warn!(error = %e, channel = %name,
                                "rpc serve_rpc: invalid reply channel name");
                            return;
                        }
                    }
                }
            };
            // Build the RESPONSE event envelope (24-byte meta + encoded
            // payload) synchronously — pure CPU, no await — then hand it to
            // the drainer.
            let meta = EventMeta::new(
                crate::adapter::net::cortex::DISPATCH_RPC_RESPONSE,
                0,
                server_origin,
                call_id,
                0,
            );
            let mut buf = Vec::with_capacity(EVENT_META_SIZE + 64);
            buf.extend_from_slice(&meta.to_bytes());
            resp.encode_into(&mut buf);
            if resp_tx
                .try_send(RpcResponseJob {
                    caller_origin,
                    call_id,
                    target_hint,
                    reply_channel: cached.name,
                    reply_channel_hash: cached.hash,
                    reply_stream_id: cached.stream_id,
                    payload: Bytes::from(buf),
                })
                .is_err()
            {
                tracing::debug!(
                    caller_origin = format!("{:#x}", caller_origin),
                    call_id,
                    "rpc serve_rpc: response drainer at capacity; dropping response"
                );
            }
            // AV-4 item 4: a unary call emits exactly one, always-
            // terminal RESPONSE — retire its cached response route now
            // (target_hint for THIS response was already captured above).
            origin_node_cache_for_emit.remove((from_node, caller_origin, call_id));
        });

        // Build the server fold and wrap it in an Arc<Mutex<...>>
        // so the bridge task can drive it (the trait takes
        // `&mut self`). Attach the per-service metrics handle so
        // the spawned handler tasks bump server-side counters.
        let metrics_handle = self.rpc_metrics_arc().for_service(service);
        // Clone the per-service metrics handle so the bridge can
        // bump `capability_denied_total` on gate rejection. The
        // fold's own clone (passed via `with_metrics`) handles the
        // handler-side counters; this one covers the path BEFORE
        // the handler runs, which the fold-side metrics never see.
        // (The denial itself is emitted by `emit_capability_denial`,
        // which unicasts to the authenticated session peer — NC2.)
        let metrics_for_bridge = Arc::clone(&metrics_handle);
        let fold = Arc::new(Mutex::new(
            RpcServerFold::new(handler as Arc<dyn RpcHandler>, emit).with_metrics(metrics_handle),
        ));

        // Register the inbound dispatcher. Push into the mpsc;
        // the bridge task does the actual fold work.
        let dispatcher: RpcInboundDispatcher = Arc::new(move |ev| {
            // Best-effort send — over-cap means the bridge can't
            // keep up; drop and let the caller time out. Logging
            // here would spam.
            let _ = tx.try_send(ev);
        });
        // Register the service in `rpc_local_services` and refresh
        // the self-indexed announcement BEFORE installing the
        // dispatcher so the callee-side gate (in the bridge below)
        // sees a self-announcement carrying `nrpc:<service>` the
        // moment the first inbound event lands. Without this, the
        // gate was either silently permissive (no self-ann) or
        // silently denying (self-ann from a prior
        // `announce_capabilities` that pre-dated this service's
        // registration). See `docs/internal/misc/CODE_REVIEW_2026_05_19_CAPABILITY_AUTH.md`
        // H1 + H2.
        //
        // OA2-E0.1: register FIRST (vacant-only). A duplicate
        // `serve_rpc` now fails WITHOUT touching the incumbent and
        // WITHOUT leaving a service tag behind. The tag + self-index
        // still land before the bridge task below runs the gate, so
        // the H1/H2 visibility guarantee holds.
        let Some(registration_id) = self.register_rpc_inbound(channel_hash, dispatcher) else {
            return Err(ServeError::AlreadyServing(service.to_string()));
        };
        // OA3-4b1: the visibility rides into the local-service registry so
        // emission projects correctly — an owner-scoped tag is excluded from the
        // plaintext broadcast, a public one is not.
        let visibility = mode.visibility();
        self.rpc_local_services_arc()
            .insert(service.to_string(), registration_id, visibility);
        self.index_self_with_local_services();

        // E1.1: the immutable registration the bridge captures — ONE truth, the
        // provider policy captured WITH the handler (no name→policy side map, no
        // unknown-policy fallback). Public is a trivial allow-all; protected
        // carries the org-protected mode + explicit policy.
        let reg = Arc::new(match mode {
            UnaryAdmission::Public => {
                RegisteredRpcService::public(registration_id, Arc::from(service))
            }
            UnaryAdmission::Protected {
                admission,
                provider_policy,
            } => match RegisteredRpcService::protected(
                registration_id,
                Arc::from(service),
                admission,
                provider_policy,
            ) {
                Ok(reg) => reg,
                Err(e) => {
                    // Roll back the just-installed registration so no dispatcher
                    // or tag is left behind (the mode is pre-validated in
                    // `serve_rpc_protected`, so this is a belt-and-suspenders
                    // path).
                    self.unregister_rpc_inbound(channel_hash, registration_id);
                    self.rpc_local_services_arc()
                        .remove_if(service, registration_id);
                    return Err(ServeError::InvalidProtectedRegistration(e.to_string()));
                }
            },
            // OA3-4b1: owner-scoped — internal private capability of this node's
            // own org. `OwnerScoped` visibility (encrypted-only emission) +
            // `OwnerDelegated` invocation authority.
            UnaryAdmission::OwnerScoped { provider_policy } => RegisteredRpcService::owner_scoped(
                registration_id,
                Arc::from(service),
                provider_policy,
            ),
            // OA3-4b2: granted-audience — cross-org private capability.
            // `GrantedAudience` visibility (encrypted-only emission) +
            // `CrossOrgGranted` invocation authority.
            UnaryAdmission::Granted { provider_policy } => {
                RegisteredRpcService::granted(registration_id, Arc::from(service), provider_policy)
            }
            // D7: subnet-exported — an org-protected registration bound to
            // one exact declared crossing, captured immutably.
            UnaryAdmission::SubnetExported {
                admission,
                export,
                provider_policy,
            } => match RegisteredRpcService::subnet_exported(
                registration_id,
                Arc::from(service),
                admission,
                export,
                provider_policy,
            ) {
                Ok(reg) => reg,
                Err(e) => {
                    self.unregister_rpc_inbound(channel_hash, registration_id);
                    self.rpc_local_services_arc()
                        .remove_if(service, registration_id);
                    return Err(ServeError::InvalidProtectedRegistration(e.to_string()));
                }
            },
            // Test-only (review-7 RED): a protected registration marked to bypass
            // ONLY the org-admission engine. Same shape validation as a normal
            // protected registration; the disabled flag is the sole difference.
            #[cfg(test)]
            UnaryAdmission::ProtectedRedWitnessDisabled {
                admission,
                provider_policy,
            } => match RegisteredRpcService::protected(
                registration_id,
                Arc::from(service),
                admission,
                provider_policy,
            ) {
                Ok(reg) => reg.with_red_witness_disabled(),
                Err(e) => {
                    self.unregister_rpc_inbound(channel_hash, registration_id);
                    self.rpc_local_services_arc()
                        .remove_if(service, registration_id);
                    return Err(ServeError::InvalidProtectedRegistration(e.to_string()));
                }
            },
        });
        // E1.5 (Kyra #47 B2): the NODE-owned admission replay guard, shared
        // across every protected registration on this node — so `(caller,
        // call_id)` uniqueness holds provider-wide (across services AND across a
        // teardown / re-registration), not fragmented per registration.
        let admission_replay = self.rpc_admission_replay_arc();

        // Spawn the bridge task. It reads inbound events and runs the
        // registration's callee-side gate: public → the v0.4 `may_execute`
        // preflight; protected → the E1.2 org-admission gate. On accept it feeds
        // the fold; the caller-side gate inside `call_service` covers the
        // well-behaved public client path.
        let mesh_for_bridge = Arc::clone(self);
        let service_for_bridge = service.to_string();
        let origin_node_cache_for_bridge = Arc::clone(&origin_node_cache);
        let reg_for_bridge = Arc::clone(&reg);
        let replay_for_bridge = Arc::clone(&admission_replay);
        let bridge = tokio::spawn(async move {
            let tag = format!("nrpc:{}", service_for_bridge);
            while let Some(inbound) = rx.recv().await {
                match reg_for_bridge.admission() {
                    OrgAdmission::PublicAuthenticated => {
                        // The ONE shared public callee preflight: captured-
                        // service equality → may_execute → authenticated
                        // response-route cache. On denial it hands back the
                        // AUTHENTICATED reply origin (NC2), never the wire-
                        // claimed one.
                        match bridge_preflight(
                            &mesh_for_bridge,
                            &origin_node_cache_for_bridge,
                            &inbound,
                            &service_for_bridge,
                            &tag,
                            &metrics_for_bridge,
                        ) {
                            BridgePreflight::Proceed(frame) => {
                                // AV-1 item 1: drive the fold with the
                                // AEAD-verified `from_node` so per-call state
                                // binds to the authenticated session peer.
                                // `frame` is the preflight's stripped frame
                                // (E1.6 / §8) — never the raw `inbound`.
                                if let Err(e) = fold.lock().apply_inbound(&frame) {
                                    tracing::warn!(error = %e, "rpc serve_rpc: fold apply error");
                                }
                            }
                            BridgePreflight::Drop => continue,
                            BridgePreflight::Deny {
                                claimed_origin,
                                call_id,
                                from_node,
                            } => {
                                metrics_for_bridge
                                    .capability_denied_total
                                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                emit_capability_denial(
                                    &mesh_for_bridge,
                                    &service_for_bridge,
                                    claimed_origin,
                                    call_id,
                                    from_node,
                                )
                                .await;
                                continue;
                            }
                        }
                    }
                    OrgAdmission::OwnerDelegated | OrgAdmission::CrossOrgGranted => {
                        // E1.2: the org-admission gate. Verifies the proof,
                        // hands the fold the admitted REQUEST (handler runs with
                        // `RpcContext::org_admission = Some(..)`), or unicasts an
                        // `AdmissionDenied` (0x0009) to the authenticated peer.
                        admit_and_dispatch_protected(
                            &mesh_for_bridge,
                            &origin_node_cache_for_bridge,
                            &inbound,
                            &service_for_bridge,
                            &tag,
                            &metrics_for_bridge,
                            &reg_for_bridge,
                            &replay_for_bridge,
                            &fold,
                            &resp_tx_for_denials,
                        )
                        .await;
                    }
                }
            }
        });

        // §8a response drainer. Drains `resp_rx` and does the `.await`
        // publish that the emit closure used to `tokio::spawn` per response.
        // Exits on its own when `resp_tx` (held only by the emit closure,
        // which the fold owns) is dropped — i.e. when the bridge task ends
        // and the fold drops, the same teardown that stops `_bridge`.
        let response_drain_mesh = Arc::clone(self);
        let response_drain = tokio::spawn(async move {
            while let Some(job) = resp_rx.recv().await {
                if let Err(e) = publish_response_to_caller(
                    &response_drain_mesh,
                    job.caller_origin,
                    job.target_hint,
                    &job.reply_channel,
                    job.reply_channel_hash,
                    job.reply_stream_id,
                    job.payload,
                    response_fallback,
                )
                .await
                {
                    tracing::warn!(
                        error = %e,
                        caller_origin = format!("{:#x}", job.caller_origin),
                        call_id = job.call_id,
                        "rpc serve_rpc: response publish failed"
                    );
                }
            }
        });

        // Spawn an async re-announce so peers also learn about
        // the new service without the operator having to call
        // `announce_capabilities` manually. The local self-index
        // already happened above; this is purely for peer
        // visibility (the broadcast path also re-runs the
        // self-index, which is a cheap version bump).
        //
        // Republish the CURRENT baseline (read inside `announce_mu`)
        // rather than snapshotting it here and handing it back as a
        // NEW baseline. This task is spawned, so its snapshot could be
        // taken arbitrarily late — and an explicit
        // `announce_capabilities(X)` landing in between would be
        // reverted to the pre-`X` set, dropping capabilities the
        // operator just announced from both the wire and this node's
        // own self-index until something else announces. Same clobber
        // TOCTOU the RT-3 loop closed by passing `None`.
        let mesh_for_announce = Arc::clone(self);
        let service_for_log = service.to_string();
        tokio::spawn(async move {
            if let Err(e) = mesh_for_announce.reannounce_current_capabilities().await {
                tracing::warn!(
                    error = %e,
                    service = %service_for_log,
                    "serve_rpc: auto re-announce failed",
                );
            }
        });

        Ok(ServeHandle {
            channel_hash,
            registration_id,
            service: service.to_string(),
            _bridge: bridge,
            _response_drain: Some(response_drain),
            mesh: Arc::clone(self),
            #[cfg(test)]
            origin_node_cache: origin_node_cache.clone(),
        })
    }

    /// Streaming variant of [`Self::serve_rpc`]. The handler
    /// receives an [`RpcResponseSink`](crate::adapter::net::cortex::RpcResponseSink)
    /// it writes chunks to via `sink.send(body)`; returning
    /// `Ok(())` closes the stream cleanly, `Err(_)` closes with
    /// an error frame.
    ///
    /// Wire-level identical to the unary path apart from the
    /// per-chunk `nrpc-streaming` header markers
    /// (`continue` / `end`). Same auto-registration of
    /// `<service>.requests` + `<service>.replies.` prefix.
    pub fn serve_rpc_streaming<H: RpcStreamingHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
    ) -> Result<ServeHandle, ServeError> {
        let request_channel = ChannelName::new(&format!("{service}.requests"))
            .map_err(|e| ServeError::InvalidServiceName(e.to_string()))?;
        let channel_hash = request_channel.hash();
        // The channel policy nRPC requires is installed here, by the
        // one seam every serve shape passes through, before anything
        // is registered, advertised, or spawned.
        //
        // It used to be the SDK wrapper's job. Node, Python and Go/C
        // call `MeshNode::serve_rpc*` directly and never did it, so on
        // their strict-by-default registries a successful registration
        // still could not complete a single call: `<service>.requests`
        // and `<service>.replies.*` were unknown channels and every
        // request was refused. A protocol prerequisite belongs to the
        // protocol, not to whichever wrapper remembers.
        //
        // Install-if-absent, so an operator ACL registered before
        // serving survives untouched.
        if let Some(registry) = self.channel_configs() {
            registry.install_rpc_service_defaults(service)?;
        }
        let (tx, mut rx) = tokio::sync::mpsc::channel::<RpcInboundEvent>(1024);

        // T1.2 cache: bridge populates from inbound.from_node, emit
        // closure consults to skip roster fan-out. See the unary
        // serve_rpc above for the full rationale.
        let origin_node_cache: RpcOriginNodeCache = Arc::new(BoundedLru::new());

        let mesh_for_emit = Arc::clone(self);
        let service_for_emit = service.to_string();
        let server_origin = self.identity_origin_hash();
        let origin_node_cache_for_emit = Arc::clone(&origin_node_cache);
        // Async emit so the streaming fold's pump can `.await` each
        // publish — guarantees per-call chunk ordering on the wire.
        let emit: RpcAsyncResponseEmitter =
            Arc::new(move |from_node, caller_origin, call_id, resp| {
                let mesh = Arc::clone(&mesh_for_emit);
                let service = service_for_emit.clone();
                let target_hint =
                    origin_node_cache_for_emit.get((from_node, caller_origin, call_id));
                // AV-4 item 4: a streaming call fires many RESPONSE frames;
                // retire its cached route only on the terminal frame (the
                // direct hint for THIS frame was already captured above).
                if streaming_response_is_terminal(&resp) {
                    origin_node_cache_for_emit.remove((from_node, caller_origin, call_id));
                }
                Box::pin(async move {
                    let reply_channel_name = format!("{service}.replies.{caller_origin:016x}");
                    let reply_channel = match ChannelName::new(&reply_channel_name) {
                        Ok(c) => c,
                        Err(e) => {
                            tracing::warn!(error = %e, channel = %reply_channel_name,
                                "rpc serve_rpc_streaming: invalid reply channel name");
                            return;
                        }
                    };
                    let meta = EventMeta::new(
                        crate::adapter::net::cortex::DISPATCH_RPC_RESPONSE,
                        0,
                        server_origin,
                        call_id,
                        0,
                    );
                    let mut buf = Vec::with_capacity(EVENT_META_SIZE + 64);
                    buf.extend_from_slice(&meta.to_bytes());
                    resp.encode_into(&mut buf);
                    // PERF_AUDIT §3.10: compute hash + stream_id at the
                    // call site. These legacy streaming paths don't yet
                    // cache the triple via `BoundedLru<u64, CachedReplyChannel>`;
                    // wiring them up is a follow-up — for now the
                    // compute happens here per response, same as the
                    // pre-fix in-function shape.
                    let reply_channel_id = ChannelId::new(reply_channel.clone());
                    let reply_channel_hash = reply_channel_id.hash();
                    let reply_stream_id = MeshNode::publish_stream_id(&reply_channel_id);
                    if let Err(e) = publish_response_to_caller(
                        &mesh,
                        caller_origin,
                        target_hint,
                        &reply_channel,
                        reply_channel_hash,
                        reply_stream_id,
                        Bytes::from(buf),
                        ResponseRouteFallback::RosterOnStaleDirect,
                    )
                    .await
                    {
                        tracing::warn!(error = %e,
                            caller_origin = format!("{:#x}", caller_origin),
                            call_id,
                            "rpc serve_rpc_streaming: chunk publish failed");
                    }
                })
            });

        // Attach per-service metrics so the spawned handler tasks
        // + pump task bump server-side counters (including the
        // streaming-only `streaming_chunks_emitted_total`).
        let metrics_handle = self.rpc_metrics_arc().for_service(service);
        // The bridge's shared callee gate bumps the per-service
        // `capability_denied_total`; the denial itself is emitted by
        // `emit_capability_denial` (unicast to the authenticated
        // session peer — NC2), so no emit clone is needed here.
        let metrics_for_bridge = Arc::clone(&metrics_handle);
        let fold = Arc::new(Mutex::new(
            RpcServerStreamingFold::new(handler as Arc<dyn RpcStreamingHandler>, emit)
                .with_metrics(metrics_handle),
        ));
        let dispatcher: RpcInboundDispatcher = Arc::new(move |ev| {
            let _ = tx.try_send(ev);
        });
        // Register the service + refresh the self-indexed
        // announcement BEFORE installing the dispatcher, exactly as
        // the unary path does: the callee-side gate reads the local
        // fold, so a self-announcement carrying `nrpc:<service>`
        // must exist the moment the first inbound event lands —
        // otherwise the gate would deny legitimate callers of a
        // just-registered service (see the unary `serve_rpc`
        // comment + `CODE_REVIEW_2026_05_19_CAPABILITY_AUTH.md`
        // H1 / H2).
        //
        // OA2-E0.1: register FIRST (vacant-only); a duplicate leaves
        // no service tag behind. The tag still lands before the
        // bridge task runs the gate.
        let Some(registration_id) = self.register_rpc_inbound(channel_hash, dispatcher) else {
            return Err(ServeError::AlreadyServing(service.to_string()));
        };
        self.rpc_local_services_arc().insert(
            service.to_string(),
            registration_id,
            CapabilityVisibility::Public,
        );
        self.index_self_with_local_services();
        let origin_node_cache_for_bridge = Arc::clone(&origin_node_cache);
        let mesh_for_bridge = Arc::clone(self);
        let service_for_bridge = service.to_string();
        let bridge = tokio::spawn(async move {
            let tag = format!("nrpc:{}", service_for_bridge);
            while let Some(inbound) = rx.recv().await {
                // The shared callee preflight (see the unary bridge).
                match bridge_preflight(
                    &mesh_for_bridge,
                    &origin_node_cache_for_bridge,
                    &inbound,
                    &service_for_bridge,
                    &tag,
                    &metrics_for_bridge,
                ) {
                    BridgePreflight::Proceed(frame) => {
                        // AV-1 item 1: authenticated-peer-bound fold drive, on
                        // the preflight's stripped frame (E1.6 / §8).
                        if let Err(e) = fold.lock().apply_inbound(&frame) {
                            tracing::warn!(error = %e, "rpc serve_rpc_streaming: fold apply error");
                        }
                    }
                    BridgePreflight::Drop => continue,
                    BridgePreflight::Deny {
                        claimed_origin,
                        call_id,
                        from_node,
                    } => {
                        metrics_for_bridge
                            .capability_denied_total
                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        // A non-`Ok` status closes the caller's stream
                        // regardless of streaming headers; NC2 delivers it
                        // only to the authenticated session peer.
                        emit_capability_denial(
                            &mesh_for_bridge,
                            &service_for_bridge,
                            claimed_origin,
                            call_id,
                            from_node,
                        )
                        .await;
                        continue;
                    }
                }
            }
        });
        Ok(ServeHandle {
            channel_hash,
            registration_id,
            service: service.to_string(),
            _bridge: bridge,
            // Streaming/duplex variants still spawn per emit (§8a covers the
            // unary hot path); no drainer.
            _response_drain: None,
            mesh: Arc::clone(self),
            #[cfg(test)]
            origin_node_cache: origin_node_cache.clone(),
        })
    }

    /// Register a client-streaming nRPC handler for `service`.
    /// Mirror of [`Self::serve_rpc_streaming`] but using the
    /// request-side fold ([`RpcStreamingRequestFold`]) — the
    /// handler receives one stream of REQUEST_CHUNK bodies and
    /// emits one terminal RESPONSE.
    ///
    /// Wires two emit callbacks:
    /// - A sync [`RpcResponseEmitter`] for the terminal RESPONSE
    ///   (single emit per call, no ordering concern).
    /// - An [`RpcRequestGrantEmitter`] for upload-direction
    ///   credit grants, which publishes [`DISPATCH_RPC_REQUEST_GRANT`]
    ///   events on the caller's reply channel.
    ///
    /// Bidi streaming plan (Phase C).
    pub fn serve_rpc_client_stream<H: RpcClientStreamingHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
    ) -> Result<ServeHandle, ServeError> {
        let request_channel = ChannelName::new(&format!("{service}.requests"))
            .map_err(|e| ServeError::InvalidServiceName(e.to_string()))?;
        let channel_hash = request_channel.hash();
        // The channel policy nRPC requires is installed here, by the
        // one seam every serve shape passes through, before anything
        // is registered, advertised, or spawned.
        //
        // It used to be the SDK wrapper's job. Node, Python and Go/C
        // call `MeshNode::serve_rpc*` directly and never did it, so on
        // their strict-by-default registries a successful registration
        // still could not complete a single call: `<service>.requests`
        // and `<service>.replies.*` were unknown channels and every
        // request was refused. A protocol prerequisite belongs to the
        // protocol, not to whichever wrapper remembers.
        //
        // Install-if-absent, so an operator ACL registered before
        // serving survives untouched.
        if let Some(registry) = self.channel_configs() {
            registry.install_rpc_service_defaults(service)?;
        }
        let (tx, mut rx) = tokio::sync::mpsc::channel::<RpcInboundEvent>(1024);

        // T1.2 cache — see serve_rpc above for full rationale.
        let origin_node_cache: RpcOriginNodeCache = Arc::new(BoundedLru::new());

        let mesh_for_emit = Arc::clone(self);
        let service_for_emit = service.to_string();
        let server_origin = self.identity_origin_hash();

        // Terminal RESPONSE emitter — sync because there's only
        // one RESPONSE per call (no per-call ordering concern that
        // would require an async-await between chunks).
        let emit_resp_mesh = Arc::clone(&mesh_for_emit);
        let emit_resp_service = service_for_emit.clone();
        let origin_node_cache_for_emit = Arc::clone(&origin_node_cache);
        let emit_resp: RpcResponseEmitter =
            Arc::new(move |from_node, caller_origin, call_id, resp| {
                let mesh = Arc::clone(&emit_resp_mesh);
                let service = emit_resp_service.clone();
                let target_hint =
                    origin_node_cache_for_emit.get((from_node, caller_origin, call_id));
                tokio::spawn(async move {
                    let reply_channel_name = format!("{service}.replies.{caller_origin:016x}");
                    let reply_channel = match ChannelName::new(&reply_channel_name) {
                        Ok(c) => c,
                        Err(e) => {
                            tracing::warn!(error = %e, channel = %reply_channel_name,
                                "rpc serve_rpc_client_stream: invalid reply channel name");
                            return;
                        }
                    };
                    let meta = EventMeta::new(
                        crate::adapter::net::cortex::DISPATCH_RPC_RESPONSE,
                        0,
                        server_origin,
                        call_id,
                        0,
                    );
                    let mut buf = Vec::with_capacity(EVENT_META_SIZE + 64);
                    buf.extend_from_slice(&meta.to_bytes());
                    resp.encode_into(&mut buf);
                    // PERF_AUDIT §3.10: compute hash + stream_id at the
                    // call site. These legacy streaming paths don't yet
                    // cache the triple via `BoundedLru<u64, CachedReplyChannel>`;
                    // wiring them up is a follow-up — for now the
                    // compute happens here per response, same as the
                    // pre-fix in-function shape.
                    let reply_channel_id = ChannelId::new(reply_channel.clone());
                    let reply_channel_hash = reply_channel_id.hash();
                    let reply_stream_id = MeshNode::publish_stream_id(&reply_channel_id);
                    if let Err(e) = publish_response_to_caller(
                        &mesh,
                        caller_origin,
                        target_hint,
                        &reply_channel,
                        reply_channel_hash,
                        reply_stream_id,
                        Bytes::from(buf),
                        ResponseRouteFallback::RosterOnStaleDirect,
                    )
                    .await
                    {
                        tracing::warn!(error = %e,
                            caller_origin = format!("{:#x}", caller_origin),
                            call_id,
                            "rpc serve_rpc_client_stream: terminal RESPONSE publish failed");
                    }
                });
                // AV-4 item 4: a client-streaming call emits exactly one
                // terminal RESPONSE — retire its cached response route now
                // (the direct hint for it was already captured above).
                origin_node_cache_for_emit.remove((from_node, caller_origin, call_id));
            });

        // REQUEST_GRANT emitter — coalesces per-chunk credits into
        // a single drainer task that batches by call_id. Avoids the
        // tokio::spawn-per-emit storm under bursting.
        let emit_grant = build_request_grant_emitter(
            Arc::clone(&mesh_for_emit),
            service_for_emit.clone(),
            server_origin,
            "serve_rpc_client_stream",
        );

        let metrics_handle = self.rpc_metrics_arc().for_service(service);
        // NC1: the bridge now runs the shared callee gate, so it needs
        // a metrics handle of its own (the denial is emitted by
        // `emit_capability_denial`, not the fold's emitter).
        let metrics_for_bridge = Arc::clone(&metrics_handle);
        let fold = Arc::new(Mutex::new(
            RpcStreamingRequestFold::new(handler as Arc<dyn RpcClientStreamingHandler>, emit_resp)
                .with_grant_emitter(emit_grant)
                .with_metrics(metrics_handle),
        ));
        let dispatcher: RpcInboundDispatcher = Arc::new(move |ev| {
            let _ = tx.try_send(ev);
        });
        // OA2-E0.1: vacant-only register; a duplicate fails without
        // disturbing the incumbent registration.
        let Some(registration_id) = self.register_rpc_inbound(channel_hash, dispatcher) else {
            return Err(ServeError::AlreadyServing(service.to_string()));
        };
        // OA2-E0 (Kyra E0 review): publish the token-owned service
        // registration AND refresh the self-index BEFORE the bridge is
        // exposed, so no inbound event can be processed before the
        // local registration/discovery state exists (the unary and
        // response-streaming paths already do this). The dispatcher
        // above only buffers into the mpsc; the bridge that drains it
        // is spawned LAST.
        self.rpc_local_services_arc().insert(
            service.to_string(),
            registration_id,
            CapabilityVisibility::Public,
        );
        self.index_self_with_local_services();
        let origin_node_cache_for_bridge = Arc::clone(&origin_node_cache);
        let service_for_bridge = service.to_string();
        let mesh_for_bridge = Arc::clone(self);
        let bridge = tokio::spawn(async move {
            let tag = format!("nrpc:{}", service_for_bridge);
            while let Some(inbound) = rx.recv().await {
                // NC1: the SAME shared callee preflight the unary /
                // response-streaming bridges run — client-streaming
                // used to skip may_execute entirely, leaving it
                // transport-authenticated but not capability-authorized.
                match bridge_preflight(
                    &mesh_for_bridge,
                    &origin_node_cache_for_bridge,
                    &inbound,
                    &service_for_bridge,
                    &tag,
                    &metrics_for_bridge,
                ) {
                    BridgePreflight::Proceed(frame) => {
                        // Gate-3: a relayed/untrusted caller cannot be issued
                        // secure upload grants (no e2e recipient correlation),
                        // so reject a flow-controlled REQUEST here — BEFORE the
                        // fold — rather than admit it and silently starve it of
                        // grants (partial execution then an unexplained stall).
                        if reject_relayed_flow_controlled_request(
                            &mesh_for_bridge,
                            &metrics_for_bridge,
                            &inbound,
                            &service_for_bridge,
                            &tag,
                        ) {
                            continue;
                        }
                        // AV-1 item 1: authenticated-peer-bound fold drive, on
                        // the preflight's stripped frame (E1.6 / §8).
                        if let Err(e) = fold.lock().apply_inbound(&frame) {
                            tracing::warn!(error = %e,
                                "rpc serve_rpc_client_stream: fold apply error");
                        }
                    }
                    BridgePreflight::Drop => continue,
                    BridgePreflight::Deny {
                        claimed_origin,
                        call_id,
                        from_node,
                    } => {
                        metrics_for_bridge
                            .capability_denied_total
                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        emit_capability_denial(
                            &mesh_for_bridge,
                            &service_for_bridge,
                            claimed_origin,
                            call_id,
                            from_node,
                        )
                        .await;
                        continue;
                    }
                }
            }
        });
        Ok(ServeHandle {
            channel_hash,
            registration_id,
            service: service.to_string(),
            _bridge: bridge,
            // Streaming/duplex variants still spawn per emit (§8a covers the
            // unary hot path); no drainer.
            _response_drain: None,
            mesh: Arc::clone(self),
            #[cfg(test)]
            origin_node_cache: origin_node_cache.clone(),
        })
    }

    /// Client-streaming variant of [`Self::call`]. Returns a
    /// [`ClientStreamCallRaw`] handle the caller pushes N items
    /// into via `send`, then `finish` to await the terminal
    /// RESPONSE.
    ///
    /// **Lazy initial REQUEST.** This method does NOT publish a
    /// REQUEST to the wire. It only ensures the caller's reply
    /// subscription is set up and registers the pending entry; the
    /// initial REQUEST is emitted by the first `send` (or by
    /// `finish` for the zero-item degenerate path).
    ///
    /// Sets `FLAG_RPC_CLIENT_STREAMING_REQUEST` on the initial
    /// REQUEST so the server's request-streaming fold knows to
    /// open a request-side stream. Optional `request_window_initial`
    /// header opts into upload-direction flow control.
    ///
    /// Bidi streaming plan (Phase C).
    pub async fn call_client_stream(
        self: &Arc<Self>,
        target_node_id: u64,
        service: &str,
        opts: CallOptions,
    ) -> Result<ClientStreamCallRaw, RpcError> {
        // Org admission is unary-only (E1.8): a proof intent on a streaming call
        // shape is a caller error, never a silently-ignored security intent.
        if opts.org_proof_intent.is_some() {
            return Err(RpcError::Codec {
                direction: CodecDirection::Encode,
                message: "org admission (org_proof_intent) is unary-only; use `call` for a \
                          protected service"
                    .to_string(),
            });
        }
        // `request_window_initial = Some(0)` would deadlock the
        // caller: every `send` awaits a credit, but the initial
        // REQUEST is lazy (not emitted until the first send), so
        // the server never sees the call and never publishes a
        // GRANT. Reject up front — `None` means "unbounded credit",
        // any positive value opts into flow control.
        if matches!(opts.request_window_initial, Some(0)) {
            return Err(RpcError::Codec {
                direction: CodecDirection::Encode,
                message: "request_window_initial must be None or >= 1; Some(0) deadlocks send"
                    .to_string(),
            });
        }
        // T1.3: per-service route cache (see PERF_AUDIT
        // 2026-05-19). One DashMap::get + Arc::clone instead of
        // 2 format! + 2 ChannelName::new + xxhash per call.
        let route = self.rpc_route_or_no_route(target_node_id, service)?;
        let self_origin = self.identity_origin_hash();
        self.ensure_reply_subscription(
            target_node_id,
            service,
            route.reply_channel.clone(),
            route.reply_hash,
        )
        .await?;

        let call_id = mint_random_call_id();
        let pending = self.rpc_client_pending();
        let (terminal_rx, mut grant_rx) =
            pending.register_client_streaming(call_id, target_node_id);

        // Build the header set + flags we'll queue for the initial
        // REQUEST (deferred to the first send / finish).
        let mut initial_flags = FLAG_RPC_CLIENT_STREAMING_REQUEST;
        let mut initial_headers: Vec<(String, Vec<u8>)> = Vec::new();
        if let Some(tc) = opts.trace_context.as_ref() {
            initial_flags |= FLAG_RPC_PROPAGATE_TRACE;
            initial_headers.extend(build_trace_headers(tc));
        }
        if let Some(window) = opts.request_window_initial {
            initial_headers.push((
                HEADER_NRPC_REQUEST_WINDOW_INITIAL.to_string(),
                window.to_string().into_bytes(),
            ));
        }
        initial_headers.extend(opts.request_headers.iter().cloned());

        // Per-call credit semaphore when flow control is opted in.
        // Initial permits = the caller's declared window. Refilled
        // by REQUEST_GRANT events arriving on the reply channel,
        // pumped through `grant_rx` by the spawned `grant_pump`.
        let credit_sem = opts
            .request_window_initial
            .map(|n| Arc::new(tokio::sync::Semaphore::new(n as usize)));
        let grant_pump = credit_sem.as_ref().map(|sem| {
            let sem = Arc::clone(sem);
            tokio::spawn(async move {
                while let Some(credits) = grant_rx.recv().await {
                    add_request_grant_credits(&sem, credits);
                }
            })
        });

        let deadline_ns = opts.deadline.map(instant_to_unix_nanos).unwrap_or(0);
        let observer = StreamingObserverState::new(Arc::clone(self), target_node_id, service, 0);
        let cancel_keep_alive = arm_stream_cancel(self, &opts, &pending, call_id);
        // See `remember_cancel_publish_runtime`.
        remember_cancel_publish_runtime();
        Ok(ClientStreamCallRaw {
            mesh: Arc::clone(self),
            target_node_id,
            request_channel: route.request_channel.clone(),
            request_channel_hash: route.request_channel_hash,
            request_stream_id: route.request_stream_id,
            self_origin,
            call_id,
            service: service.to_string(),
            initial_headers,
            initial_flags,
            deadline_ns,
            credit_sem,
            grant_pump,
            terminal_rx: Some(terminal_rx),
            state: ClientStreamState::JustOpened,
            started: Instant::now(),
            observer,
            _cancel_keep_alive: cancel_keep_alive,
        })
    }

    /// Register a duplex nRPC handler for `service`. Composes
    /// [`Self::serve_rpc_client_stream`] (request-side stream)
    /// with [`Self::serve_rpc_streaming`] (response-side multi-
    /// fire emit) via [`RpcDuplexFold`].
    ///
    /// Wires THREE emit callbacks:
    /// - Async [`RpcAsyncResponseEmitter`] for response chunks +
    ///   the terminal frame (per-call ordering required because
    ///   the response side is multi-fire).
    /// - [`RpcRequestGrantEmitter`] for upload-direction credit
    ///   grants (one per consumed request chunk when flow
    ///   control is opted into).
    ///
    /// Bidi streaming plan (Phase D).
    pub fn serve_rpc_duplex<H: RpcDuplexHandler>(
        self: &Arc<Self>,
        service: &str,
        handler: Arc<H>,
    ) -> Result<ServeHandle, ServeError> {
        let request_channel = ChannelName::new(&format!("{service}.requests"))
            .map_err(|e| ServeError::InvalidServiceName(e.to_string()))?;
        let channel_hash = request_channel.hash();
        // The channel policy nRPC requires is installed here, by the
        // one seam every serve shape passes through, before anything
        // is registered, advertised, or spawned.
        //
        // It used to be the SDK wrapper's job. Node, Python and Go/C
        // call `MeshNode::serve_rpc*` directly and never did it, so on
        // their strict-by-default registries a successful registration
        // still could not complete a single call: `<service>.requests`
        // and `<service>.replies.*` were unknown channels and every
        // request was refused. A protocol prerequisite belongs to the
        // protocol, not to whichever wrapper remembers.
        //
        // Install-if-absent, so an operator ACL registered before
        // serving survives untouched.
        if let Some(registry) = self.channel_configs() {
            registry.install_rpc_service_defaults(service)?;
        }
        let (tx, mut rx) = tokio::sync::mpsc::channel::<RpcInboundEvent>(1024);

        // T1.2 cache — see serve_rpc above for full rationale.
        let origin_node_cache: RpcOriginNodeCache = Arc::new(BoundedLru::new());

        let mesh_for_emit = Arc::clone(self);
        let service_for_emit = service.to_string();
        let server_origin = self.identity_origin_hash();

        // Async response emitter — per-call ordering matters here
        // because the response side is multi-fire (same rationale
        // as serve_rpc_streaming).
        let emit_resp_mesh = Arc::clone(&mesh_for_emit);
        let emit_resp_service = service_for_emit.clone();
        let origin_node_cache_for_emit = Arc::clone(&origin_node_cache);
        let emit_resp: RpcAsyncResponseEmitter =
            Arc::new(move |from_node, caller_origin, call_id, resp| {
                let mesh = Arc::clone(&emit_resp_mesh);
                let service = emit_resp_service.clone();
                let target_hint =
                    origin_node_cache_for_emit.get((from_node, caller_origin, call_id));
                // AV-4 item 4: retire the cached route only on the duplex
                // call's terminal RESPONSE frame (the direct hint for THIS
                // frame was already captured above).
                if streaming_response_is_terminal(&resp) {
                    origin_node_cache_for_emit.remove((from_node, caller_origin, call_id));
                }
                Box::pin(async move {
                    let reply_channel_name = format!("{service}.replies.{caller_origin:016x}");
                    let reply_channel = match ChannelName::new(&reply_channel_name) {
                        Ok(c) => c,
                        Err(e) => {
                            tracing::warn!(error = %e, channel = %reply_channel_name,
                                "rpc serve_rpc_duplex: invalid reply channel name");
                            return;
                        }
                    };
                    let meta = EventMeta::new(
                        crate::adapter::net::cortex::DISPATCH_RPC_RESPONSE,
                        0,
                        server_origin,
                        call_id,
                        0,
                    );
                    let mut buf = Vec::with_capacity(EVENT_META_SIZE + 64);
                    buf.extend_from_slice(&meta.to_bytes());
                    resp.encode_into(&mut buf);
                    // PERF_AUDIT §3.10: compute hash + stream_id at the
                    // call site. These legacy streaming paths don't yet
                    // cache the triple via `BoundedLru<u64, CachedReplyChannel>`;
                    // wiring them up is a follow-up — for now the
                    // compute happens here per response, same as the
                    // pre-fix in-function shape.
                    let reply_channel_id = ChannelId::new(reply_channel.clone());
                    let reply_channel_hash = reply_channel_id.hash();
                    let reply_stream_id = MeshNode::publish_stream_id(&reply_channel_id);
                    if let Err(e) = publish_response_to_caller(
                        &mesh,
                        caller_origin,
                        target_hint,
                        &reply_channel,
                        reply_channel_hash,
                        reply_stream_id,
                        Bytes::from(buf),
                        ResponseRouteFallback::RosterOnStaleDirect,
                    )
                    .await
                    {
                        tracing::warn!(error = %e,
                            caller_origin = format!("{:#x}", caller_origin),
                            call_id,
                            "rpc serve_rpc_duplex: chunk publish failed");
                    }
                })
            });

        // Request-direction grant emitter — same coalescing
        // drainer shape as serve_rpc_client_stream.
        let emit_grant = build_request_grant_emitter(
            Arc::clone(&mesh_for_emit),
            service_for_emit.clone(),
            server_origin,
            "serve_rpc_duplex",
        );

        let metrics_handle = self.rpc_metrics_arc().for_service(service);
        // NC1: clone the metrics handle for the bridge's shared callee
        // gate (the denial is emitted by `emit_capability_denial`).
        let metrics_for_bridge = Arc::clone(&metrics_handle);
        let fold = Arc::new(Mutex::new(
            RpcDuplexFold::new(handler as Arc<dyn RpcDuplexHandler>, emit_resp)
                .with_grant_emitter(emit_grant)
                .with_metrics(metrics_handle),
        ));
        let dispatcher: RpcInboundDispatcher = Arc::new(move |ev| {
            let _ = tx.try_send(ev);
        });
        // OA2-E0.1: vacant-only register; a duplicate fails without
        // disturbing the incumbent registration.
        let Some(registration_id) = self.register_rpc_inbound(channel_hash, dispatcher) else {
            return Err(ServeError::AlreadyServing(service.to_string()));
        };
        // OA2-E0 (Kyra E0 review): publish + self-index BEFORE the
        // bridge is exposed (see serve_rpc_client_stream). The
        // dispatcher only buffers; the bridge drains it LAST.
        self.rpc_local_services_arc().insert(
            service.to_string(),
            registration_id,
            CapabilityVisibility::Public,
        );
        self.index_self_with_local_services();
        let origin_node_cache_for_bridge = Arc::clone(&origin_node_cache);
        let service_for_bridge = service.to_string();
        let mesh_for_bridge = Arc::clone(self);
        let bridge = tokio::spawn(async move {
            let tag = format!("nrpc:{}", service_for_bridge);
            while let Some(inbound) = rx.recv().await {
                // NC1: the shared callee preflight — duplex used to skip
                // may_execute entirely (transport-authenticated but not
                // capability-authorized).
                match bridge_preflight(
                    &mesh_for_bridge,
                    &origin_node_cache_for_bridge,
                    &inbound,
                    &service_for_bridge,
                    &tag,
                    &metrics_for_bridge,
                ) {
                    BridgePreflight::Proceed(frame) => {
                        // Gate-3: a relayed/untrusted caller cannot be issued
                        // secure upload grants (no e2e recipient correlation),
                        // so reject a flow-controlled REQUEST here — BEFORE the
                        // fold — rather than admit it and silently starve it of
                        // grants (partial execution then an unexplained stall).
                        if reject_relayed_flow_controlled_request(
                            &mesh_for_bridge,
                            &metrics_for_bridge,
                            &inbound,
                            &service_for_bridge,
                            &tag,
                        ) {
                            continue;
                        }
                        // AV-1 item 1: authenticated-peer-bound fold drive, on
                        // the preflight's stripped frame (E1.6 / §8).
                        if let Err(e) = fold.lock().apply_inbound(&frame) {
                            tracing::warn!(error = %e,
                                "rpc serve_rpc_duplex: fold apply error");
                        }
                    }
                    BridgePreflight::Drop => continue,
                    BridgePreflight::Deny {
                        claimed_origin,
                        call_id,
                        from_node,
                    } => {
                        metrics_for_bridge
                            .capability_denied_total
                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                        emit_capability_denial(
                            &mesh_for_bridge,
                            &service_for_bridge,
                            claimed_origin,
                            call_id,
                            from_node,
                        )
                        .await;
                        continue;
                    }
                }
            }
        });
        Ok(ServeHandle {
            channel_hash,
            registration_id,
            service: service.to_string(),
            _bridge: bridge,
            // Streaming/duplex variants still spawn per emit (§8a covers the
            // unary hot path); no drainer.
            _response_drain: None,
            mesh: Arc::clone(self),
            #[cfg(test)]
            origin_node_cache: origin_node_cache.clone(),
        })
    }

    /// Duplex variant of [`Self::call`]. Returns a
    /// [`DuplexCallRaw`] handle with both upload (`send`,
    /// `finish_sending`) and download (`next`, or impl
    /// `futures::Stream`) surfaces. Use `into_split` to peel off
    /// the two halves for the "encoder task + decoder task"
    /// shape.
    ///
    /// Initial REQUEST sets BOTH `FLAG_RPC_CLIENT_STREAMING_REQUEST`
    /// AND `FLAG_RPC_STREAMING_RESPONSE`. Lazy publish — the
    /// initial REQUEST flies on the first `send` (or on
    /// `finish_sending` for the zero-item degenerate path).
    ///
    /// Bidi streaming plan (Phase D).
    pub async fn call_duplex(
        self: &Arc<Self>,
        target_node_id: u64,
        service: &str,
        opts: CallOptions,
    ) -> Result<DuplexCallRaw, RpcError> {
        // Org admission is unary-only (E1.8): a proof intent on a streaming call
        // shape is a caller error, never a silently-ignored security intent.
        if opts.org_proof_intent.is_some() {
            return Err(RpcError::Codec {
                direction: CodecDirection::Encode,
                message: "org admission (org_proof_intent) is unary-only; use `call` for a \
                          protected service"
                    .to_string(),
            });
        }
        // Same deadlock guard as `call_client_stream`: Some(0)
        // means "send must await a credit that can never arrive"
        // because the initial REQUEST is lazy.
        if matches!(opts.request_window_initial, Some(0)) {
            return Err(RpcError::Codec {
                direction: CodecDirection::Encode,
                message: "request_window_initial must be None or >= 1; Some(0) deadlocks send"
                    .to_string(),
            });
        }
        // §31 — the DOWNLOAD direction needs the same guard, and
        // `call_duplex` only had the upload one. `call_streaming` rejects
        // `stream_window_initial == Some(0)` up front; duplex validated the
        // upload window and then emitted `nrpc-stream-window-initial: 0`
        // verbatim. The server's response pump awaits one credit per chunk
        // and the caller's auto-grant only fires on CONSUMED chunks, so the
        // first chunk can never be delivered: a hung call plus a server-side
        // pump and semaphore held until the deadline.
        if matches!(opts.stream_window_initial, Some(0)) {
            return Err(RpcError::Codec {
                direction: CodecDirection::Encode,
                message:
                    "stream_window_initial must be None or >= 1; Some(0) deadlocks the response pump"
                        .to_string(),
            });
        }
        // T1.3: per-service route cache (see PERF_AUDIT
        // 2026-05-19). One DashMap::get + Arc::clone instead of
        // 2 format! + 2 ChannelName::new + xxhash per call.
        let route = self.rpc_route_or_no_route(target_node_id, service)?;
        let self_origin = self.identity_origin_hash();
        self.ensure_reply_subscription(
            target_node_id,
            service,
            route.reply_channel.clone(),
            route.reply_hash,
        )
        .await?;

        let call_id = mint_random_call_id();
        let pending = self.rpc_client_pending();
        let (chunks_rx, mut grant_rx) = pending.register_duplex(call_id, target_node_id);

        let mut initial_flags = FLAG_RPC_CLIENT_STREAMING_REQUEST | FLAG_RPC_STREAMING_RESPONSE;
        let mut initial_headers: Vec<(String, Vec<u8>)> = Vec::new();
        if let Some(tc) = opts.trace_context.as_ref() {
            initial_flags |= FLAG_RPC_PROPAGATE_TRACE;
            initial_headers.extend(build_trace_headers(tc));
        }
        if let Some(window) = opts.request_window_initial {
            initial_headers.push((
                HEADER_NRPC_REQUEST_WINDOW_INITIAL.to_string(),
                window.to_string().into_bytes(),
            ));
        }
        if let Some(window) = opts.stream_window_initial {
            initial_headers.push((
                HEADER_NRPC_STREAM_WINDOW_INITIAL.to_string(),
                window.to_string().into_bytes(),
            ));
        }
        initial_headers.extend(opts.request_headers.iter().cloned());

        let credit_sem = opts
            .request_window_initial
            .map(|n| Arc::new(tokio::sync::Semaphore::new(n as usize)));
        let grant_pump = credit_sem.as_ref().map(|sem| {
            let sem = Arc::clone(sem);
            tokio::spawn(async move {
                while let Some(credits) = grant_rx.recv().await {
                    add_request_grant_credits(&sem, credits);
                }
            })
        });

        let deadline_ns = opts.deadline.map(instant_to_unix_nanos).unwrap_or(0);
        let observer = StreamingObserverState::new(Arc::clone(self), target_node_id, service, 0);
        // Cancel keep-alive lives on the shared Arc<DuplexInner>
        // so it survives into_split — the watcher exits only when
        // BOTH the sink AND stream halves drop, matching the
        // existing CANCEL-on-drop semantics.
        let cancel_keep_alive = arm_stream_cancel(self, &opts, &pending, call_id);
        // This handle may be dropped by a foreign thread — a Python
        // object freed by GC, an FFI release — so record the runtime now,
        // while we are certainly on one.
        remember_cancel_publish_runtime();
        let inner = Arc::new(DuplexInner {
            mesh: Arc::clone(self),
            target_node_id,
            request_channel: route.request_channel.clone(),
            request_channel_hash: route.request_channel_hash,
            request_stream_id: route.request_stream_id,
            self_origin,
            call_id,
            initial_sent: std::sync::atomic::AtomicBool::new(false),
            clean_close: std::sync::atomic::AtomicBool::new(false),
            observer,
            _cancel_keep_alive: Some(cancel_keep_alive),
        });
        let sink = DuplexSink {
            inner: Arc::clone(&inner),
            service: service.to_string(),
            initial_headers,
            initial_flags,
            deadline_ns,
            credit_sem,
            grant_pump,
            state: ClientStreamState::JustOpened,
        };
        let stream = DuplexStream {
            inner,
            chunks_rx,
            done: false,
        };
        Ok(DuplexCallRaw { sink, stream })
    }

    /// Streaming variant of [`Self::call`]. Returns an
    /// [`RpcStream`] that yields chunks (as `Result<Bytes, RpcError>`)
    /// until the server closes the stream.
    ///
    /// Sets `FLAG_RPC_STREAMING_RESPONSE` on the request so the
    /// server's streaming fold knows to expect multi-fire emits.
    /// Same lazy reply-subscription + direct-unicast REQUEST
    /// as the unary `call` path.
    ///
    /// Cancellation: dropping the returned `RpcStream` emits a
    /// CANCEL to the server (best-effort) and discards any
    /// in-flight chunks.
    pub async fn call_streaming(
        self: &Arc<Self>,
        target_node_id: u64,
        service: &str,
        payload: Bytes,
        opts: CallOptions,
    ) -> Result<RpcStream, RpcError> {
        // Org admission is unary-only (E1.8): a proof intent on a streaming call
        // shape is a caller error, never a silently-ignored security intent.
        if opts.org_proof_intent.is_some() {
            return Err(RpcError::Codec {
                direction: CodecDirection::Encode,
                message: "org admission (org_proof_intent) is unary-only; use `call` for a \
                          protected service"
                    .to_string(),
            });
        }
        // `stream_window_initial = Some(0)` would deadlock the
        // RESPONSE direction by default: server's pump awaits one
        // credit per chunk, the caller's auto-grant only fires on
        // consumed chunks, and the first chunk can never be
        // delivered. `None` means "unbounded credit"; any positive
        // value opts into flow control. Reject up front — symmetric
        // with the request-direction guard in `call_client_stream`.
        if matches!(opts.stream_window_initial, Some(0)) {
            return Err(RpcError::Codec {
                direction: CodecDirection::Encode,
                message: "stream_window_initial must be None or >= 1; Some(0) deadlocks the response pump"
                    .to_string(),
            });
        }
        // T1.3: per-service route cache. One DashMap::get + Arc::clone
        // on the hot path instead of 2 format! + 2 ChannelName::new +
        // xxhash per call.
        let route = self.rpc_route_or_no_route(target_node_id, service)?;
        let self_origin = self.identity_origin_hash();
        self.ensure_reply_subscription(
            target_node_id,
            service,
            route.reply_channel.clone(),
            route.reply_hash,
        )
        .await?;

        let call_id = mint_random_call_id();
        let pending = self.rpc_client_pending();
        // S-4 part 2: bind the pending entry to the wire-session
        // peer the request is dispatched to. The fold's deliver
        // gate rejects RESPONSE frames whose from_node doesn't
        // match, so a leaked call_id alone can't spoof a reply.
        let rx = pending.register_streaming(call_id, target_node_id);

        // Build the REQUEST: STREAMING_RESPONSE flag plus optional
        // trace-context headers / propagate-trace flag, same as
        // unary `call`. Plus the optional flow-control header
        // (`nrpc-stream-window-initial`) when the caller opted in
        // via `CallOptions::stream_window_initial`.
        let mut flags = FLAG_RPC_STREAMING_RESPONSE;
        let mut headers = Vec::new();
        if let Some(tc) = opts.trace_context.as_ref() {
            flags |= FLAG_RPC_PROPAGATE_TRACE;
            headers.extend(build_trace_headers(tc));
        }
        if let Some(window) = opts.stream_window_initial {
            headers.push((
                HEADER_NRPC_STREAM_WINDOW_INITIAL.to_string(),
                window.to_string().into_bytes(),
            ));
        }
        // Append caller-supplied request headers (Phase 9b — same
        // semantics as the unary `call` path).
        headers.extend(opts.request_headers.iter().cloned());
        let req = RpcRequestPayload {
            service: service.to_string(),
            deadline_ns: opts.deadline.map(instant_to_unix_nanos).unwrap_or(0),
            flags,
            headers,
            body: payload.clone(),
        };
        let meta = EventMeta::new(DISPATCH_RPC_REQUEST, 0, self_origin, call_id, 0);
        let mut buf = Vec::with_capacity(EVENT_META_SIZE + RPC_ROUTE_V1_SIZE + req.body.len() + 32);
        buf.extend_from_slice(&meta.to_bytes());
        encode_rpc_route(&mut buf, route.request_channel_hash);
        req.encode_into(&mut buf);

        let payload_bytes = Bytes::from(buf);
        if let Err(e) = self
            .publish_to_peer(
                target_node_id,
                route.request_channel_hash,
                route.request_stream_id,
                /* reliable */ true,
                std::slice::from_ref(&payload_bytes),
            )
            .await
        {
            pending.cancel(call_id);
            return Err(RpcError::Transport(e));
        }

        let request_bytes_len = payload_bytes.len() as u32;
        // Cancel keep-alive lives on the returned RpcStream so the
        // watcher exits cleanly when the stream drops without cancel.
        let cancel_keep_alive = arm_stream_cancel(self, &opts, &pending, call_id);
        // See `remember_cancel_publish_runtime` — a stream handed to a
        // binding can be dropped off-runtime.
        remember_cancel_publish_runtime();
        Ok(RpcStream {
            mesh: Arc::clone(self),
            target_node_id,
            request_channel: route.request_channel.clone(),
            // PERF_AUDIT §3.10 — cache the channel hash + stream
            // id from `route` so per-chunk grants in `poll_next`
            // don't re-run `ChannelId::new` + xxh3.
            request_channel_hash: route.request_channel_hash,
            request_stream_id: route.request_stream_id,
            self_origin,
            call_id,
            inner: rx,
            done: false,
            stream_window: opts.stream_window_initial,
            grant_pending: 0,
            _cancel_keep_alive: cancel_keep_alive,
            observer: StreamingObserverState::new(
                Arc::clone(self),
                target_node_id,
                service,
                request_bytes_len,
            ),
        })
    }

    /// Find every node currently advertising `service` via the
    /// `nrpc:<service>` capability tag. Returns node IDs in
    /// roster order; the caller picks one (or use [`Self::call_service`]
    /// for the round-robin shortcut).
    ///
    /// Pre-Phase 2: requires the target nodes to have called
    /// `serve_rpc` AND `announce_capabilities` so the
    /// `nrpc:<service>` tag has propagated through capability
    /// announcements. The local node's own services are NOT
    /// automatically included (callers don't typically invoke
    /// themselves via the network — for in-process invocation,
    /// the user has the handler directly).
    pub fn find_service_nodes(&self, service: &str) -> Vec<u64> {
        use crate::adapter::net::behavior::capability::CapabilityFilter;
        use crate::adapter::net::behavior::fold::capability_bridge;
        let tag = format!("nrpc:{service}");
        let filter = CapabilityFilter::default().require_tag(tag);
        capability_bridge::find_nodes_matching(self.capability_fold(), &filter)
    }

    /// Every node publicly advertising `nrpc:<service>` whose announcement
    /// carries a currently valid verified owner projection, with candidate
    /// and owner sampled from ONE capability-fold snapshot
    /// (SUBNET_AUTH_SDK_PLAN.md R1).
    ///
    /// This is the discovery read behind `OrgClient::call_exported`: a
    /// subnet-exported registration announces on the public plane
    /// ([`CapabilityVisibility::Public`]), so the caller derives its
    /// authority relation from the VERIFIED owner org — never from a
    /// caller-claimed or separately-read value. Calling
    /// [`Self::find_service_nodes`] and `owner_org_for` as two reads could
    /// pair a live candidate with a projection a floor retraction or
    /// announcement replacement already killed; the underlying
    /// one-snapshot query makes that tear unrepresentable.
    ///
    /// Unowned public candidates are not returned — they are ordinary
    /// public services, not exported-plane candidates. A candidate node
    /// without a live AEAD entity pin is dropped: without the pin it has
    /// no entity-layer identity to authorize against, and org-protected
    /// RPC is direct-session-only regardless (OA2-E0.3). Results are in
    /// ascending provider-`EntityId` order — deterministic, load-blind;
    /// no sensing or load balancing is consulted.
    ///
    /// **The live pin must equal the entity the projection was verified
    /// for** (review-10 P1-1). The fold query returns the exact
    /// publisher, so this seam does not resolve `NodeId → EntityId` and
    /// trust the answer: it resolves, compares, and drops the candidate
    /// on any mismatch. A node id is the low 8 bytes of an entity id, so
    /// two distinct entities can present the same one; peer death clears
    /// pin and fold record separately, and a fresh direct announcement
    /// installs its pin before applying its fold record. Without this
    /// equality a caller could disclose a request-bound signed
    /// organization proof and its capability grant to an entity that
    /// never published the sampled owned capability.
    ///
    /// [`CapabilityVisibility::Public`]: crate::adapter::net::org_admission_gate::CapabilityVisibility::Public
    pub fn public_owned_service_providers(&self, service: &str) -> Vec<PublicOwnedProvider> {
        use crate::adapter::net::behavior::fold::capability_bridge;
        let tag = format!("nrpc:{service}");
        let mut out: Vec<PublicOwnedProvider> =
            capability_bridge::public_owned_providers(self.capability_fold(), &tag)
                .into_iter()
                .filter_map(|publisher| {
                    let pinned = self.peer_entity_id(publisher.node_id)?;
                    // Fail closed on a pin that names a different entity
                    // than the one whose owner cert was verified. Not a
                    // liveness check — an identity check.
                    if pinned != publisher.member {
                        tracing::debug!(
                            node_id = format!("{:#x}", publisher.node_id),
                            "dropping exported candidate: the live session pin names a \
                             different entity than the verified ownership projection"
                        );
                        return None;
                    }
                    Some(PublicOwnedProvider {
                        provider: pinned,
                        owner_org: publisher.owner_org,
                    })
                })
                .collect();
        out.sort_unstable_by(|a, b| a.provider.as_bytes().cmp(b.provider.as_bytes()));
        out
    }

    /// Issue an RPC call to `service`, picking one node from
    /// those advertising the `nrpc:<service>` tag in the local
    /// capability index according to `opts.routing_policy`.
    ///
    /// Returns `RpcError::NoRoute` if no nodes advertise the
    /// service (or if `opts.filter_unhealthy` is set and every
    /// candidate is unavailable per the local `ProximityGraph`).
    pub async fn call_service(
        self: &Arc<Self>,
        service: &str,
        payload: Bytes,
        opts: CallOptions,
    ) -> Result<RpcReply, RpcError> {
        let mut candidates = self.find_service_nodes(service);
        if candidates.is_empty() {
            return Err(RpcError::NoRoute {
                target: 0,
                reason: format!(
                    "no nodes advertise `nrpc:{service}` (have any servers \
                     for this service called serve_rpc + announce_capabilities?)"
                ),
            });
        }

        // Health filtering. Skip candidates the proximity graph
        // marks unhealthy (`!is_available()`). Candidates with no
        // proximity entry at all are KEPT — absence of evidence
        // is not evidence of unhealth, and a freshly-announced
        // service shouldn't be filtered just because pingwaves
        // haven't propagated yet.
        //
        // The bridge: each candidate's session-layer `node_id: u64`
        // is mapped to the entity-layer `[u8; 32]` via
        // `MeshNode::entity_id_for_node`. The proximity graph is
        // keyed on the entity id.
        if opts.filter_unhealthy {
            let proximity = self.proximity_graph();
            candidates.retain(|node_id| match self.entity_id_for_node(*node_id) {
                Some(entity_id) => match proximity.get_node(&entity_id) {
                    Some(node) => node.is_available(),
                    None => true, // no proximity data → keep
                },
                None => true, // no entity-id mapping → keep
            });
            if candidates.is_empty() {
                return Err(RpcError::NoRoute {
                    target: 0,
                    reason: format!(
                        "every node advertising `nrpc:{service}` is marked \
                         unhealthy by the local proximity graph",
                    ),
                });
            }
        }

        // Sort once so consistent-hash policies (Sticky) produce
        // a stable ordering across calls regardless of how the
        // capability index returned the candidates, and so the
        // LowestLatency-with-no-proximity-data fallback is
        // deterministic. Cheap — the candidate set is typically
        // small.
        candidates.sort_unstable();

        // OA-2 authority split (Kyra #47 final): the caller's authorization for a
        // PROTECTED call is the org proof the PROVIDER's live admission gate
        // verifies — NOT the legacy `may_execute` announcement allow-list. Branch
        // the candidate authorization on the intent so protected routing is
        // semantically consistent with a direct protected `call()`:
        //
        //   * protected (`Some` intent) → do NOT apply `may_execute`. A legacy
        //     allow-list that excludes the caller must not delete a valid
        //     protected provider (the caller's authority is the proof, not the
        //     announcement). Keep ONLY the candidate that IS the exact pinned
        //     provider the proof binds — it already advertises `nrpc:<service>`
        //     (else it wouldn't be a `find_service_nodes` candidate), and its own
        //     org gate is the authority. Fail LOCALLY if the bound provider isn't
        //     advertising, rather than minting a proof for a peer that can't be
        //     selected. `call` re-checks the binding (defense in depth).
        //   * public (`None`) → the existing v0.4 caller-side `may_execute` gate,
        //     unchanged (permissive announcements admit any caller). See
        //     `docs/internal/plans/CAPABILITY_AUTH_PLAN.md` §3.
        //
        // Health filtering has already run above; this filtering precedes
        // `select_target` so routing never picks a peer the call would only
        // reject afterward.
        if let Some(intent) = opts.org_proof_intent.as_ref() {
            candidates
                .retain(|node_id| self.peer_entity_id(*node_id).as_ref() == Some(&intent.provider));
            if candidates.is_empty() {
                return Err(RpcError::Codec {
                    direction: CodecDirection::Encode,
                    message: format!(
                        "org admission: no advertising candidate for `nrpc:{service}` matches \
                         the proof's bound provider"
                    ),
                });
            }
        } else {
            let tag = format!("nrpc:{service}");
            use crate::adapter::net::behavior::fold::capability_bridge;
            let self_id = self.node_id();
            let any_candidate = candidates[0];
            let fold = self.capability_fold();
            // PERF_AUDIT §4.2 — batch the per-candidate gate so the fold read
            // lock is taken once and the caller's subnet + groups are parsed
            // once, not N times.
            let verdicts = capability_bridge::may_execute_batch(fold, &candidates, &tag, self_id);
            let mut iter = verdicts.into_iter();
            candidates.retain(|_| iter.next().unwrap_or(false));
            if candidates.is_empty() {
                return Err(RpcError::CapabilityDenied {
                    // No authorized target; surface one of the originally-
                    // advertised candidates so the caller can correlate the
                    // denial with a real peer.
                    target: any_candidate,
                    capability: service.to_string(),
                });
            }
        }

        let target = self.select_target(&candidates, &opts.routing_policy);
        self.call(target, service, payload, opts).await
    }

    /// Capability-routed server-streaming call. Same routing as
    /// [`call_service`] — capability-fold lookup, health filter,
    /// routing-policy sort, capability-auth gate, target selection —
    /// but the terminal step is [`call_streaming`] instead of
    /// [`call`]. Returns the substrate's `RpcStream` so callers can
    /// drive an `async for chunk in stream:` loop.
    ///
    /// Use cases: an agent invoking a long-running tool that emits
    /// progress + a terminal result, a fan-out subscriber that wants
    /// streaming chunks from whatever node currently advertises the
    /// service, any consumer that today reaches for
    /// `find_service_nodes` → manual target selection → `call_streaming`
    /// and ends up re-implementing the cap-auth gate `call_service`
    /// already enforces.
    ///
    /// Honors `CallOptions::cancel_token` (v3) and
    /// `CallOptions::deadline` exactly like `call_streaming`.
    ///
    /// [`call_service`]: Self::call_service
    /// [`call_streaming`]: Self::call_streaming
    /// [`call`]: Self::call
    pub async fn call_service_streaming(
        self: &Arc<Self>,
        service: &str,
        payload: Bytes,
        opts: CallOptions,
    ) -> Result<RpcStream, RpcError> {
        // Org admission is unary-only (E1.8): reject a proof intent at the TOP,
        // BEFORE discovery / target selection (Kyra #47 tail). Falling through to
        // `find_service_nodes` + `select_target` would advance round-robin /
        // consistent-hash routing state (or surface an unrelated NoRoute) before
        // the promised unary-only failure — a caller error must not perturb
        // routing.
        if opts.org_proof_intent.is_some() {
            return Err(RpcError::Codec {
                direction: CodecDirection::Encode,
                message: "org admission (org_proof_intent) is unary-only; use `call_service` \
                          for a protected service"
                    .to_string(),
            });
        }
        let mut candidates = self.find_service_nodes(service);
        if candidates.is_empty() {
            return Err(RpcError::NoRoute {
                target: 0,
                reason: format!(
                    "no nodes advertise `nrpc:{service}` (have any servers \
                     for this service called serve_rpc + announce_capabilities?)"
                ),
            });
        }

        // Health filter — mirrors `call_service`. Candidates with no
        // proximity entry are kept (absence of evidence ≠ evidence of
        // unhealth); only candidates the proximity graph marks
        // explicitly unavailable get dropped.
        if opts.filter_unhealthy {
            let proximity = self.proximity_graph();
            candidates.retain(|node_id| match self.entity_id_for_node(*node_id) {
                Some(entity_id) => match proximity.get_node(&entity_id) {
                    Some(node) => node.is_available(),
                    None => true,
                },
                None => true,
            });
            if candidates.is_empty() {
                return Err(RpcError::NoRoute {
                    target: 0,
                    reason: format!(
                        "every node advertising `nrpc:{service}` is marked \
                         unhealthy by the local proximity graph",
                    ),
                });
            }
        }

        // Deterministic ordering so Sticky / LowestLatency-fallback
        // pick stably across calls — mirrors `call_service`.
        candidates.sort_unstable();

        // v0.4 capability-auth caller-side gate. Same as `call_service`:
        // filter the candidate set BEFORE target selection so the
        // routing policy never picks a peer the caller can't reach.
        let tag = format!("nrpc:{service}");
        use crate::adapter::net::behavior::fold::capability_bridge;
        let self_id = self.node_id();
        let any_candidate = candidates[0];
        let fold = self.capability_fold();
        // PERF_AUDIT §4.2 — batch the per-candidate gate. See the
        // mirror site at `:3093`.
        let verdicts = capability_bridge::may_execute_batch(fold, &candidates, &tag, self_id);
        let mut iter = verdicts.into_iter();
        candidates.retain(|_| iter.next().unwrap_or(false));
        if candidates.is_empty() {
            return Err(RpcError::CapabilityDenied {
                target: any_candidate,
                capability: service.to_string(),
            });
        }

        let target = self.select_target(&candidates, &opts.routing_policy);
        self.call_streaming(target, service, payload, opts).await
    }

    /// Select a single target from `candidates` according to
    /// `policy`. Caller has already ensured `candidates` is
    /// non-empty and sorted (so `Sticky` is consistent across
    /// calls).
    fn select_target(&self, candidates: &[u64], policy: &RoutingPolicy) -> u64 {
        match policy {
            RoutingPolicy::RoundRobin => {
                // `fetch_add(1)` on a dedicated cursor — NOT a
                // `load(call_id)` — so two concurrent
                // `call_service` invocations always observe
                // distinct values and pick distinct targets.
                let n = self
                    .rpc_round_robin_cursor_arc()
                    .fetch_add(1, Ordering::Relaxed);
                candidates[(n as usize) % candidates.len()]
            }
            RoutingPolicy::Random => {
                // Lightweight RNG via a fresh fetch_add (same
                // counter, separate per-call value) mixed through
                // xxh3. Sufficient for load distribution;
                // not cryptographically random.
                let n = self
                    .rpc_round_robin_cursor_arc()
                    .fetch_add(1, Ordering::Relaxed);
                let mixed = xxhash_rust::xxh3::xxh3_64(&n.to_le_bytes());
                candidates[(mixed as usize) % candidates.len()]
            }
            RoutingPolicy::Sticky { key } => {
                // Consistent-hash to a position in the (sorted)
                // candidate list. Same key + same candidate set =
                // same target. A change to the candidate set
                // (server failover) reshuffles roughly 1/N of keys.
                let h = xxhash_rust::xxh3::xxh3_64(&key.to_le_bytes());
                candidates[(h as usize) % candidates.len()]
            }
            RoutingPolicy::LowestLatency => {
                // Walk candidates, look up each via the bridge
                // → proximity graph, pick the smallest
                // `latency_us`. Candidates without a proximity
                // entry (no observed pingwave or no entity-id
                // mapping yet) are treated as `u64::MAX` so they
                // sort to the bottom — a known-fast node beats an
                // unknown one.
                //
                // Determinism on tie / no-data: `best_node` starts
                // at `candidates[0]` (the lexicographically first
                // sorted candidate), so all-ties or all-unknown
                // collapse to that consistent fallback.
                let proximity = self.proximity_graph();
                let mut best_node = candidates[0];
                let mut best_latency = u64::MAX;
                for &node_id in candidates {
                    let lat = self
                        .entity_id_for_node(node_id)
                        .and_then(|eid| proximity.get_node(&eid))
                        .map(|n| n.latency_us)
                        .unwrap_or(u64::MAX);
                    if lat < best_latency {
                        best_latency = lat;
                        best_node = node_id;
                    }
                }
                best_node
            }
        }
    }

    /// Issue an RPC call to `target_node_id` for `service`.
    ///
    /// Phase 1 — direct entity-to-entity addressing. The caller
    /// specifies which target to send to; service discovery (the
    /// "find me a healthy instance of X" lookup) is Phase 2.
    ///
    /// Lazily subscribes the local node's `RpcClientFold` to
    /// `<service>.replies.<self_origin>` from `target_node_id` on
    /// the first call to that (target, service) pair. The
    /// subscription is reused across subsequent calls.
    ///
    /// On `opts.deadline` expiring OR the future being dropped,
    /// emits a CANCEL event so the server can drop the in-flight
    /// handler.
    pub async fn call(
        self: &Arc<Self>,
        target_node_id: u64,
        service: &str,
        payload: Bytes,
        mut opts: CallOptions,
    ) -> Result<RpcReply, RpcError> {
        // `started_total` brackets the entire call for the
        // `RpcObserver` latency field; the substrate-internal
        // `started` further down (set after the subscription
        // setup) drives the existing `RpcReply::latency_ns`
        // accounting so observers and Prometheus metrics
        // measure slightly different spans but stay consistent
        // within their own surface.
        let started_total = Instant::now();
        let request_bytes_len = payload.len() as u32;
        // Per-service route cache: one `DashMap::get(&str)` +
        // `Arc::clone` on the hot path instead of 2 `format!` +
        // 2 `ChannelName::new` + xxhash per call (T1.3 perf audit
        // — `docs/internal/misc/PERF_AUDIT_2026_05_19_NRPC.md`).
        let route = self.rpc_route_or_no_route(target_node_id, service)?;
        let self_origin = self.identity_origin_hash();

        // Allocate a fresh call_id. Random u64 from getrandom; a
        // sequential counter would let any session peer that
        // observed one of their own call_ids predict the next-
        // allocated ids and ship spoofed RESPONSE frames on the
        // victim's reply channel. Random u64 collides with
        // probability 2^-64 per call and is unguessable from
        // another peer's perspective.
        let call_id = mint_random_call_id();

        // Build the REQUEST envelope. If a trace context is set,
        // emit `traceparent` / `tracestate` headers and signal
        // via `FLAG_RPC_PROPAGATE_TRACE` so the server's fold
        // populates `RpcContext::trace_context`.
        let (flags, mut headers) = match opts.trace_context.as_ref() {
            Some(tc) => (FLAG_RPC_PROPAGATE_TRACE, build_trace_headers(tc)),
            None => (0u16, Vec::new()),
        };
        // Append caller-supplied request headers (e.g. the
        // `net-where` predicate header for Phase 9b
        // predicate-pushdown). Auto-generated headers come first
        // so name collisions resolve to caller-overrides via the
        // server-side `predicate_from_rpc_headers` first-match
        // semantics.
        // PERF_AUDIT §3.11 — `opts` is owned by this function and
        // its `request_headers` are unused after this point;
        // `Vec::append(&mut other)` drains `other` into `headers`
        // with zero allocation, vs the pre-fix
        // `.iter().cloned()` which deep-cloned each
        // `(String, Vec<u8>)` pair into a fresh entry.
        headers.append(&mut opts.request_headers);
        let mut req = RpcRequestPayload {
            service: service.to_string(),
            deadline_ns: opts.deadline.map(instant_to_unix_nanos).unwrap_or(0),
            flags,
            headers,
            body: payload.clone(),
        };
        // E2.1 / Kyra #47 B3: finalize a protected call ATOMICALLY and validate
        // the FINAL wire before registering the pending oneshot, so a local
        // construction failure cannot leak a pending entry and an over-cap
        // finalized frame cannot panic/truncate at encode.
        if let Some(intent) = opts.org_proof_intent.as_ref() {
            // The proof binds EXACTLY ONE provider (P). Refuse to publish it to a
            // transport target that is not P: look up the pinned entity for
            // `target_node_id` and require it to equal `intent.provider`.
            // Publishing an A-bound proof to provider B would DISCLOSE the
            // credential to the wrong peer and can only end in a remote binding
            // denial — fail the caller LOCALLY instead (Kyra #47 tail). An
            // unpinned target (no TOFU binding yet) is refused too: we cannot
            // prove it is P.
            match self.peer_entity_id(target_node_id) {
                Some(pinned) if pinned == intent.provider => {}
                Some(_) => {
                    return Err(RpcError::Codec {
                        direction: CodecDirection::Encode,
                        message: format!(
                            "org admission: proof provider does not match the pinned entity \
                             of target {target_node_id:#x}"
                        ),
                    });
                }
                None => {
                    return Err(RpcError::Codec {
                        direction: CodecDirection::Encode,
                        message: format!(
                            "org admission: target {target_node_id:#x} has no pinned entity \
                             to bind the proof to"
                        ),
                    });
                }
            }
            // Exactly ONE proof header may ride, and only the builder sets it:
            // reject a caller-supplied one here rather than appending a second
            // and letting the provider deny MultipleHeaders.
            if req
                .headers
                .iter()
                .any(|(name, _)| name == ORG_ADMISSION_HEADER)
            {
                // Local caller-input error, before any network work AND before
                // the metrics guard is created — no `in_flight` bump to undo and
                // no CallOutcome to record.
                return Err(RpcError::Codec {
                    direction: CodecDirection::Encode,
                    message: "org admission: request already carries a net-org-admission header"
                        .to_string(),
                });
            }
            // Sign over the FINALIZED request (the digest strips the header, so
            // caller + provider agree), append exactly one proof header, then
            // validate the FINAL bounds — 32 supplied headers + the proof header
            // would otherwise be 33 > MAX_RPC_HEADERS and panic (debug) /
            // truncate (release) at `encode_into`.
            let header = sign_admission_proof(intent, call_id, &req)?;
            req.headers.push(header);
            req.validate_wire_bounds().map_err(|e| RpcError::Codec {
                direction: CodecDirection::Encode,
                message: format!("org admission: finalized request exceeds wire bounds: {e}"),
            })?;
        }

        // Caller-side metrics guard, created ONLY after all fallible LOCAL
        // request construction (provider binding, proof signing, final wire
        // bounds) has succeeded (Kyra #47 tail): a call rejected on local caller
        // input never got off the ground, so it must not bump `in_flight` or
        // record any outcome. From here on the guard bumps `in_flight`
        // immediately; each early-return path calls `metrics_guard.record(...)`
        // with the outcome, and Drop records the latency + bumps the matching
        // counter. A future dropped before any `record(...)` call (e.g. a hedge
        // loser) leaves the guard with `outcome = None` so `in_flight`
        // decrements but no outcome is double-counted.
        let metrics_registry = self.rpc_metrics_arc();
        let mut metrics_guard = CallMetricsGuard::new(metrics_registry.for_service(service));

        // Lazy reply-channel subscription — AFTER the request (incl. any proof)
        // is finalized + wire-validated, so a malformed protected call fails
        // before any subscription work. Once per (target, service); the reply
        // channel + hash come from the cached `RpcRoute` (an `Arc<str>` clone).
        if let Err(e) = self
            .ensure_reply_subscription(
                target_node_id,
                service,
                route.reply_channel.clone(),
                route.reply_hash,
            )
            .await
        {
            metrics_guard.record(CallOutcome::NoRoute);
            self.fire_rpc_observer_outbound(
                target_node_id,
                service,
                started_total.elapsed().as_millis() as u32,
                crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Error(e.to_string()),
                request_bytes_len,
                0,
            );
            return Err(e);
        }

        // Register the oneshot only NOW — after ALL fallible local construction
        // (proof sign + final bounds) — so an error above returns WITHOUT leaking
        // a pending entry. Still before publish, so a very-fast RESPONSE has
        // somewhere to land (S-4 part 2: bound to target_node_id, so the deliver
        // gate rejects a RESPONSE spoofed from any other session peer).
        let pending = self.rpc_client_pending();
        let rx = pending.register(call_id, target_node_id);

        let meta = EventMeta::new(DISPATCH_RPC_REQUEST, 0, self_origin, call_id, 0);
        let mut buf = Vec::with_capacity(EVENT_META_SIZE + RPC_ROUTE_V1_SIZE + req.body.len() + 32);
        buf.extend_from_slice(&meta.to_bytes());
        encode_rpc_route(&mut buf, route.request_channel_hash);
        req.encode_into(&mut buf);

        // Send the REQUEST directly to `target_node_id` via
        // `publish_to_peer`, bypassing the local subscriber roster
        // lookup. The roster-based `Mesh::publish` would consult
        // `dispatch_recipients(channel)` against the caller's local
        // roster, which has no knowledge of who serves this service
        // (no Subscribe message ever propagated from the server back
        // to the caller — `serve_rpc` is local-only). For Phase 1
        // direct addressing we know the target, so direct-send is
        // the right primitive.
        //
        // The receiver routes via the per-channel-hash dispatcher
        // hook (channel_hash is stamped on the wire by
        // publish_to_peer).
        let started = Instant::now();
        // Request channel hash + stream_id come from the cached
        // route — no `ChannelId::new` clone + xxhash per call.
        let payload_bytes = Bytes::from(buf);
        if let Err(e) = self
            .publish_to_peer(
                target_node_id,
                route.request_channel_hash,
                route.request_stream_id,
                /* reliable */ true,
                std::slice::from_ref(&payload_bytes),
            )
            .await
        {
            pending.cancel(call_id);
            // Distinguish "I don't know how to reach this peer"
            // from a generic transport blip: when the publish path
            // surfaces a no-session error, that's NoRoute (the
            // routing layer's job, retry won't help). Other
            // transport errors stay as Transport so retry is
            // applicable.
            let err = if classify_publish_no_session(&e) {
                metrics_guard.record(CallOutcome::NoRoute);
                RpcError::NoRoute {
                    target: target_node_id,
                    reason: e.to_string(),
                }
            } else {
                metrics_guard.record(CallOutcome::Transport);
                RpcError::Transport(e)
            };
            self.fire_rpc_observer_outbound(
                target_node_id,
                service,
                started_total.elapsed().as_millis() as u32,
                crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Error(err.to_string()),
                request_bytes_len,
                0,
            );
            return Err(err);
        }

        // From here on, the REQUEST is in flight on the server.
        // Wrap the rest of the call in an RAII guard whose Drop
        // fires CANCEL if `guard.completed` isn't set — covering:
        //  - the call future being dropped mid-flight (e.g. hedge
        //    loser, select!-cancelled future, caller awaiting a
        //    `JoinHandle` that gets cancelled).
        //  - the timeout path (we leave `completed=false` so Drop
        //    handles CANCEL emission; no need for a separate
        //    `send_rpc_cancel` call).
        //  - the cancel_token path (same: leave completed=false,
        //    Drop emits CANCEL).
        // See `remember_cancel_publish_runtime`.
        remember_cancel_publish_runtime();
        let mut guard = UnaryCallGuard {
            pending: Arc::clone(&pending),
            mesh: Arc::clone(self),
            target_node_id,
            request_channel: route.request_channel.clone(),
            self_origin,
            call_id,
            completed: false,
        };

        // Substrate cancel-token plumbing (v3 / C-S1). When the
        // caller set `opts.cancel_token`, register a Notify against
        // the per-mesh cancel_registry. The select! arm below
        // observes the cancel signal and short-circuits to
        // RpcError::Cancelled, leaving guard.completed = false so
        // Drop fires CANCEL on the wire. Release the registry
        // entry once the call resolves so the registry doesn't
        // grow unboundedly.
        let cancel_token = opts.cancel_token.unwrap_or(0);
        let cancel_notify = self.cancel_registry().register_notify(cancel_token);

        // Race the receiver against the deadline AND the cancel
        // signal. Each branch lifts to the same outcome shape
        // (Result<Result<RpcResponsePayload, _>, Elapsed>) so the
        // existing post-match logic stays unchanged for the ok /
        // timeout paths; the cancel arm returns early via
        // fire_unary_cancel_outcome — leaves guard.completed=false
        // so Drop emits CANCEL on the wire.
        let outcome: Result<Result<RpcResponsePayload, _>, tokio::time::error::Elapsed> =
            match opts.deadline {
                None => {
                    tokio::select! {
                        biased;
                        _ = cancel_notify.notified() => {
                            return Err(fire_unary_cancel_outcome(
                                self,
                                &mut metrics_guard,
                                cancel_token,
                                target_node_id,
                                service,
                                started_total,
                                request_bytes_len,
                            ));
                        }
                        r = rx => Ok(r),
                    }
                }
                Some(deadline) => {
                    let timeout_at = deadline.saturating_duration_since(Instant::now());
                    tokio::select! {
                        biased;
                        _ = cancel_notify.notified() => {
                            return Err(fire_unary_cancel_outcome(
                                self,
                                &mut metrics_guard,
                                cancel_token,
                                target_node_id,
                                service,
                                started_total,
                                request_bytes_len,
                            ));
                        }
                        r = tokio::time::timeout(timeout_at, rx) => r,
                    }
                }
            };

        // Whichever non-cancel path won, release the registry
        // entry. Idempotent if the cancel arm already released.
        self.cancel_registry().release(cancel_token);

        let resp = match outcome {
            Ok(Ok(resp)) => {
                guard.completed = true;
                resp
            }
            Ok(Err(_recv_err)) => {
                // Sender dropped externally — pending entry is
                // already gone (someone else removed it). Mark
                // completed so Drop doesn't fire a useless CANCEL
                // for a server that's no longer tracking this id.
                guard.completed = true;
                metrics_guard.record(CallOutcome::Transport);
                let err = RpcError::Transport(AdapterError::Connection(
                    "rpc client pending sender dropped (no response will arrive)".into(),
                ));
                self.fire_rpc_observer_outbound(
                    target_node_id,
                    service,
                    started_total.elapsed().as_millis() as u32,
                    crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Error(
                        err.to_string(),
                    ),
                    request_bytes_len,
                    0,
                );
                return Err(err);
            }
            Err(_elapsed) => {
                // Timeout: leave `completed=false` so Drop emits
                // CANCEL automatically; surface Timeout to caller.
                metrics_guard.record(CallOutcome::Timeout);
                self.fire_rpc_observer_outbound(
                    target_node_id,
                    service,
                    started_total.elapsed().as_millis() as u32,
                    crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Timeout,
                    request_bytes_len,
                    0,
                );
                return Err(RpcError::Timeout {
                    elapsed_ms: started.elapsed().as_millis() as u64,
                });
            }
        };

        // Map the wire status onto the public Result type.
        if resp.status.is_ok() {
            metrics_guard.record(CallOutcome::Ok);
            let response_bytes_len = resp.body.len() as u32;
            self.fire_rpc_observer_outbound(
                target_node_id,
                service,
                started_total.elapsed().as_millis() as u32,
                crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Ok,
                request_bytes_len,
                response_bytes_len,
            );
            Ok(RpcReply {
                body: resp.body,
                headers: resp.headers,
                latency_ns: started.elapsed().as_nanos() as u64,
            })
        } else {
            metrics_guard.record(CallOutcome::ServerError);
            let status = resp.status.to_wire();
            let response_bytes_len = resp.body.len() as u32;
            let message = String::from_utf8(resp.body.to_vec())
                .unwrap_or_else(|e| format!("<{} bytes of non-utf8 body>", e.into_bytes().len()));
            self.fire_rpc_observer_outbound(
                target_node_id,
                service,
                started_total.elapsed().as_millis() as u32,
                crate::adapter::net::cortex::rpc_observer::RpcCallStatus::Error(message.clone()),
                request_bytes_len,
                response_bytes_len,
            );
            // v0.4 capability-auth: callee-side defense-in-depth
            // surfaces as a wire `CapabilityDenied` status. Map it
            // back to the typed `RpcError::CapabilityDenied` so
            // application code sees the same variant regardless of
            // which side of the gate fired.
            if matches!(resp.status, RpcStatus::CapabilityDenied) {
                return Err(RpcError::CapabilityDenied {
                    target: target_node_id,
                    capability: service.to_string(),
                });
            }
            Err(RpcError::ServerError {
                status,
                message,
                headers: resp.headers,
            })
        }
    }

    // ----------------------------------------------------------------
    // Internal helpers.
    // ----------------------------------------------------------------

    /// Lazy-subscribe `reply_channel` from `target_node_id` and
    /// register an inbound dispatcher that drives the per-Mesh
    /// `RpcClientFold`. Idempotent — subsequent calls for the
    /// same (target, service) pair are no-ops.
    ///
    /// **Bounded** at [`MAX_REPLY_SUBSCRIPTIONS`]: a caller talking
    /// to many short-lived (target, service) pairs would otherwise
    /// grow the registry indefinitely. Past the cap we refuse the
    /// new subscription with `NoRoute` rather than evict an
    /// existing one (eviction could rip out a healthy in-flight
    /// reply path).
    ///
    /// **Dispatcher reuse**: the reply-channel name embeds the
    /// CALLER's `self_origin`, NOT the target's, so a single
    /// caller talking to multiple servers for the same service
    /// reuses the same reply channel (same hash). We register the
    /// dispatcher only if the slot is unoccupied; subsequent
    /// (target, service) pairs that hash to the same slot are
    /// allowed to share the existing dispatcher (which routes to
    /// the same per-Mesh `pending` map regardless of target). A
    /// genuine cross-service hash collision is detected at
    /// `serve_rpc` time (the AlreadyServing path) for the server
    /// side; on the caller side here, sharing the dispatcher is
    /// the correct behavior because all RESPONSE events route
    /// through the same `RpcClientPending` keyed by `call_id`.
    async fn ensure_reply_subscription(
        self: &Arc<Self>,
        target_node_id: u64,
        service: &str,
        reply_channel: ChannelName,
        reply_hash: ChannelHash,
    ) -> Result<(), RpcError> {
        let registry = self.rpc_reply_subscriptions_arc();
        // PERF_AUDIT §3.5 — DashMap keyed by
        // `(target, xxh3_64(service))`. Pre-fix this was a global
        // `Mutex<Vec<(u64, String)>>` that every concurrent RPC
        // caller took on every call to scan the Vec with a String
        // compare per entry — all callers serialized on it. Now the
        // hot path is one shard-local read with a single String
        // compare against the slot's stored service name (xxh3 is
        // not collision-free; see `reply_subscription_covers`).
        let service_hash = xxhash_rust::xxh3::xxh3_64(service.as_bytes());
        if reply_subscription_covers(&registry, target_node_id, service_hash, service) {
            return Ok(());
        }
        // The failure-generation snapshot the fence at the bottom
        // compares against, recorded by the attempt that SUCCEEDS.
        //
        // Each attempt snapshots BEFORE its subscribe `await`, because
        // everything from there on can be overtaken by
        // `target_node_id`'s session failing: the failure path evicts
        // this registry, but it can only evict entries that exist when
        // it runs, and ours does not exist yet. See
        // `peer_failure_generation`.
        //
        // Per ATTEMPT, never once for the whole loop. A failure BETWEEN
        // attempts is precisely what the retry recovers from, so fencing
        // a later successful subscribe against a pre-failure snapshot
        // would discard a valid cache entry and report `NoRoute` for a
        // call that had just succeeded — turning the self-healing R5
        // exists to provide back into the permanent failure it replaced.
        // Only the snapshot belonging to the succeeding attempt means
        // anything.
        //
        // Hence `None` here rather than a snapshot taken at this point:
        // every read happens after the loop, so a value taken here could
        // only ever be the wrong one, and seeding a placeholder would
        // fence against a generation no attempt ever observed.
        let mut gen_before: Option<u64> = None;
        // Cap the registry. `len()` on DashMap is approximate under
        // concurrent churn (it sums shard counts under shard reads,
        // not a global lock), which is exactly the semantics we
        // want here — the cap is a soft guard against a runaway
        // caller, not a precise invariant. Past the cap, new
        // entries are refused.
        if registry.len() >= MAX_REPLY_SUBSCRIPTIONS {
            return Err(RpcError::NoRoute {
                target: target_node_id,
                reason: format!(
                    "reply-subscription registry at cap ({} entries); refusing new \
                     (target={target_node_id:#x}, service={service:?}). Caller should \
                     reuse an existing target+service pair or shrink the active set.",
                    MAX_REPLY_SUBSCRIPTIONS,
                ),
            });
        }

        // Subscribe to our own reply channel from the target so the
        // target's roster has us as a subscriber when the server's
        // emit closure publishes the RESPONSE.
        //
        // H3 ordering rule: the reply prefix is origin-BOUND on the
        // server, and that binding is evaluated against the TOFU pin
        // the server installs from our signature-verified direct
        // capability announcement. If we have never announced to this
        // target — or the pin was dropped when a previous session
        // failed — the subscribe is rejected as `Unauthorized`, which
        // is a *retryable* answer rather than a permanent one.
        //
        // So: on failure, republish our current capability baseline
        // (`reannounce_current_capabilities` is the clobber-safe
        // republish — it re-reads the baseline under the announce lock
        // rather than snapshotting it outside, so it cannot lose a
        // concurrent explicit announce), give the announcement a moment
        // to land and be verified, and retry. The happy path is
        // unchanged: one attempt, no announce, no sleep.
        let mut last_err = None;
        for attempt in 0..REPLY_SUBSCRIBE_ATTEMPTS {
            let gen_this_attempt = self.peer_failure_generation(target_node_id);
            match self
                .subscribe_channel_reporting_reason(target_node_id, reply_channel.clone())
                .await
            {
                Ok(()) => {
                    gen_before = Some(gen_this_attempt);
                    last_err = None;
                    break;
                }
                Err(failure) => {
                    // Two INDEPENDENT decisions, deliberately not fused:
                    //
                    // 1. Is this rejection worth retrying at all? Only an
                    //    `Unauthorized` is. Anything else — the peer is
                    //    gone, throttling us, or does not know the
                    //    channel — returns immediately, because waiting
                    //    and asking again cannot change the answer.
                    //
                    // 2. Should THIS attempt also emit a corrective
                    //    capability announce? Only the first one per
                    //    target, ever.
                    //
                    // Fusing them (the original `retryable = warrants &&
                    // claim`) made the latch silently eat retry budget:
                    // attempt 0 claimed the latch and announced, then
                    // attempt 1's rejection found the latch already
                    // claimed, read that as "not retryable" and broke —
                    // abandoning the announcement it had just sent while
                    // it was still in flight. The retry loop exists
                    // precisely to cover that flight time, so the two
                    // must stay separate.
                    //
                    // The bound on amplification is unaffected: it lives
                    // on the announce, not on the retry.
                    let retryable = failure.warrants_reannounce();
                    last_err = Some(failure.into_adapter_error());
                    if !retryable || attempt + 1 == REPLY_SUBSCRIBE_ATTEMPTS {
                        break;
                    }
                    // `Unauthorized` alone is not a precise signal: the
                    // publisher returns it for cap-filter, token,
                    // visibility, queue-group and missing-TokenCache
                    // rejections as well as the origin pin, and the
                    // membership wire cannot currently carry a more
                    // specific reason (an unknown reason byte is a hard
                    // decode error on existing peers, so a new
                    // `AckReason` needs the versioned cutover the H1
                    // constraint set describes). Since we cannot tell a
                    // missing pin from a policy denial, the corrective
                    // announce is bounded structurally instead: at most
                    // ONE per target, ever — cleared only when that
                    // peer's session fails, which is exactly when a
                    // fresh pin is genuinely needed. Without that bound,
                    // one persistently-denying target would turn every
                    // RPC into extra capability broadcasts, because the
                    // corrective path bypasses the rate limit.
                    //
                    // `reannounce_for_authorization`, NOT the routine
                    // republish: the routine path coalesces inside
                    // `min_announce_interval` (10 s by default) and
                    // returns Ok without sending, so the retry would
                    // wait out the backoff and fail for exactly the
                    // same missing-pin reason. Bypassing coalescing is
                    // the whole point here.
                    //
                    // Announce failures are not fatal — the retry may
                    // still succeed if the pin arrives by another route
                    // — but they must not CONSUME the target's one
                    // claim. The claim has to be taken before the send
                    // (two callers racing on the same target must not
                    // both announce), so a send that failed would
                    // otherwise leave this target unable to ever get a
                    // corrective announce until an unrelated peer
                    // failure cleared the latch. Refund it: nothing was
                    // broadcast, so there is nothing to bound.
                    if self.claim_corrective_announce(target_node_id) {
                        if let Err(e) = self.reannounce_for_authorization().await {
                            tracing::debug!(
                                target = format!("{target_node_id:#x}"),
                                error = %e,
                                "corrective capability announce failed to send; \
                                 releasing the claim so a later call can retry"
                            );
                            self.release_corrective_announce(target_node_id);
                        }
                    }
                    // Back off whether or not we announced. On the
                    // attempts after the latch is spent we are waiting
                    // out the flight time of the announce attempt 0
                    // sent.
                    tokio::time::sleep(REPLY_SUBSCRIBE_BACKOFF * (attempt as u32 + 1)).await;
                }
            }
        }
        if let Some(e) = last_err {
            return Err(RpcError::NoRoute {
                target: target_node_id,
                reason: format!(
                    "reply-channel subscribe rejected by {target_node_id:#x} ({e}). \
                     The reply channel is bound to this node's announced identity; \
                     if this persists, the target has not pinned our EntityId \
                     (no signature-verified direct capability announcement has \
                     been received from us)."
                ),
            });
        }

        // Register the inbound dispatcher only if the slot is
        // unoccupied. The reply-channel name embeds *self_origin*,
        // not the target, so multiple targets serving the same
        // service share one reply channel + one dispatcher. The
        // existing dispatcher routes to the same per-Mesh
        // `RpcClientPending` keyed by call_id, so reuse is safe.
        if !self.rpc_inbound_dispatcher_registered(reply_hash) {
            let pending = self.rpc_client_pending();
            let fold = Arc::new(Mutex::new(RpcClientFold::new(pending)));
            // S-4 part 2: use `apply_inbound` so the wire-session
            // peer's NodeId (resolved in mesh.rs's dispatch site)
            // flows into the fold's deliver gate. The legacy
            // `RedexFold::apply` shim delivers with from_node=0,
            // which would defeat the binding.
            let dispatcher: RpcInboundDispatcher = Arc::new(move |ev| {
                fold.lock().apply_inbound(&ev);
            });
            // Race-safe via VACANT-ONLY registration (OA2-E0.1): a
            // concurrent caller might have registered between our
            // `registered` check and here. If so, `register_rpc_inbound`
            // returns `None` (occupied) and leaves the incumbent
            // dispatcher UNTOUCHED — our fresh fold is simply dropped.
            // The incumbent routes to the same shared `pending` map, so
            // reuse is correct; no restore dance is needed. We don't
            // retain the returned id — the reply dispatcher is a
            // long-lived caller-side registration with no ServeHandle.
            let _ = self.register_rpc_inbound(reply_hash, dispatcher);
        }

        let _ = reply_hash; // captured into the dispatcher above; surfaced for debug
                            // `insert` is idempotent — a concurrent caller that beat us
                            // to it just overwrote the slot with the identical value.
                            // On a genuine xxh3 collision between two service names on
                            // the same target, the slot flips to whichever service
                            // subscribed last and the other re-subscribes on its next
                            // call (idempotent, correct, merely un-cached). Cap drift
                            // past MAX_REPLY_SUBSCRIPTIONS during a concurrent insert
                            // race is bounded by the number of concurrent callers,
                            // which operators tune separately.
                            // A missing snapshot means no attempt reported success, which the
                            // `last_err` return above already covers — so this is
                            // unreachable. Checked BEFORE the insert so the unreachable case
                            // cannot cache anything: the one thing this block must never do
                            // is leave a cache entry standing that nothing verified.
        let Some(gen_before) = gen_before else {
            return Err(RpcError::NoRoute {
                target: target_node_id,
                reason: format!(
                    "reply-channel subscribe to {target_node_id:#x} completed with \
                     no recorded outcome; refusing to cache an unverified \
                     subscription. Retry — the next call re-subscribes."
                ),
            });
        };

        registry.insert(
            (target_node_id, service_hash),
            ReplySubscription {
                service: Arc::from(service),
                written_at_generation: gen_before,
            },
        );

        // Fence. If the target's session failed since the snapshot taken
        // before the SUCCEEDING subscribe attempt, the eviction that ran
        // for it could not have removed the entry we only just inserted,
        // so remove it ourselves. Failures before that attempt are not
        // our concern — the retry already recovered from them. The
        // subscribe we performed is void either way — the target dropped
        // its whole roster on failure — and leaving the entry behind
        // would make every subsequent call skip the re-subscribe and
        // publish replies into a channel we are not rostered on.
        //
        // Order matters: insert THEN check. Checking first would leave
        // the same gap one step earlier. The eviction bumps the
        // generation BEFORE its retain, which is what makes exactly one
        // of the two removals certain to fire — if the retain ran before
        // our insert then the bump did too and we observe it here; if it
        // runs after, it takes the entry itself.
        //
        // Rolls back OUR entry, not whatever is in the slot. Removing by
        // key alone let a fenced older call delete an entry a NEWER
        // post-recovery call had just established, after which that
        // newer caller believed it was cached and re-subscribed
        // needlessly on its next RPC. Matching the stamp fixes it: any
        // call that ran after the failure we just detected wrote a
        // different generation, so its entry survives. An entry stamped
        // with the same generation is either ours or a concurrent call
        // that started where we did — and that call reaches this same
        // fence and rolls back too, so removing it is right either way.
        if self.peer_failure_generation(target_node_id) != gen_before {
            registry.remove_if(&(target_node_id, service_hash), |_, entry| {
                entry.written_at_generation == gen_before
            });
            return Err(RpcError::NoRoute {
                target: target_node_id,
                reason: format!(
                    "session with {target_node_id:#x} failed while subscribing to the \
                     reply channel; the target dropped our roster entry, so the \
                     subscribe did not survive. Retry — the next call re-subscribes."
                ),
            });
        }
        Ok(())
    }
}

/// PERF_AUDIT §3.5 — hot-path membership check for the
/// reply-subscription registry. Returns `true` only when the slot
/// for `(target, xxh3(service))` exists AND the stored service
/// name matches exactly. xxh3_64 is neither collision-free nor
/// cryptographic; a hash-only hit that skipped the subscribe for
/// a *different* service would silently drop that service's
/// replies — the reply channel name embeds the service, so being
/// in the target's roster for the colliding service's channel
/// does nothing for this one. Verifying the stored name turns a
/// collision into a per-call re-subscribe (idempotent, harmless)
/// instead of a correctness bug.
fn reply_subscription_covers(
    registry: &dashmap::DashMap<(u64, u64), ReplySubscription>,
    target_node_id: u64,
    service_hash: u64,
    service: &str,
) -> bool {
    registry
        .get(&(target_node_id, service_hash))
        .is_some_and(|entry| entry.value().service.as_ref() == service)
}

/// Hard cap on the number of distinct (target_node_id, service)
/// pairs the caller-side reply-subscription registry will hold.
/// Past the cap, the lazy-subscribe path inside [`MeshNode::call`]
/// refuses new entries with [`RpcError::NoRoute`]. 1024 is
/// generous for any realistic deployment — a caller that needs
/// more should reuse existing reply paths.
pub const MAX_REPLY_SUBSCRIPTIONS: usize = 1024;

/// How many times `ensure_reply_subscription` attempts the reply-channel
/// subscribe before giving up.
///
/// The reply prefix is origin-bound on the server (H3), and that binding
/// resolves against the TOFU pin installed from our signature-verified
/// direct capability announcement. A caller making its first call — or
/// one whose pin was dropped with a failed session — can legitimately
/// race ahead of its own announcement, so a single rejection is not
/// evidence of a permanent authorization failure. Three attempts covers
/// the announce + verify + pin round trip without turning a genuine
/// denial into a long stall.
const REPLY_SUBSCRIBE_ATTEMPTS: usize = 3;

/// Base backoff between reply-subscribe attempts; multiplied by the
/// attempt number, so waits are ~8 ms then ~16 ms.
///
/// Deliberately small. The corrective announce and the retry travel the
/// same session as the subscribe, so the wait only has to cover the
/// peer's receive-and-verify of an announcement it already has in hand —
/// not a fresh round trip. Sizing it generously would be actively
/// harmful: this cost lands on a caller's FIRST call to a target, and a
/// first call is frequently the one under a latency policy. At 75 ms the
/// hedge suite's 50 ms hedge window elapsed before the primary leg's
/// request was even sent, so the primary never ran and the policy
/// silently degraded to "always use the backup".
const REPLY_SUBSCRIBE_BACKOFF: std::time::Duration = std::time::Duration::from_millis(8);

/// Mint a random 64-bit call_id. Used as the correlation token
/// for REQUEST/RESPONSE pairing. The fold keys pending oneshots on
/// this value; any session peer with publish access to the reply
/// channel could ship a forged RESPONSE if it could guess the
/// value. Sequential u64s are predictable from any peer that
/// observes a single allocation; random u64s collide with 2^-64
/// probability per call and are unpredictable to observing peers.
///
/// **PERF_AUDIT §3.8** — pre-fix this called `getrandom::fill` for
/// 8 bytes per RPC — one OS entropy syscall per call
/// (BCryptGenRandom on Windows, ~200-400 ns; somewhat cheaper on
/// Linux). Now each thread refills a small pool of raw OS entropy
/// ([`CALL_ID_ENTROPY_POOL_BYTES`]) with a single `getrandom`
/// syscall and hands out 8 bytes per call, amortizing the syscall
/// across [`CALL_ID_ENTROPY_POOL_BYTES`]/8 mints.
///
/// Every minted id is still raw OS entropy — NOT the output of a
/// userspace PRNG — so the unpredictability-to-peers property is
/// byte-for-byte identical to the pre-§3.8 per-call fill. (An
/// earlier draft of this fix streamed ids from a thread-local
/// SplitMix64; that was unsound for this threat model: call_ids
/// are sent to callees by design, and SplitMix64's output
/// finalizer is a public bijection, so a single observed id
/// reveals the generator state and with it every FUTURE call_id
/// minted on that thread — letting one callee forge responses to
/// races on calls addressed to other peers. Raw pooled entropy
/// has no such state to recover.)
///
/// If the pool refill fails, falls back to a process-global
/// monotonic counter rather than returning `0`: two concurrent
/// callers that both minted `0` would `register(0, …)` over each
/// other, so the first caller's oneshot closes with
/// `RecvError::Closed` (a spurious `Transport` error, not the clean
/// timeout the all-distinct path yields). The counter keeps ids
/// distinct (predictable on entropy failure, but the S-4
/// `from_node` gate still blocks cross-peer forgery, and such calls
/// time out anyway). `getrandom::fill` failure is a fatal-
/// environment signal (no `/dev/urandom`, broken syscall) and the
/// broader stack won't be functional anyway; the pool cursor is
/// left exhausted so the next mint retries the refill. `0` is
/// reserved as a sentinel and never returned.
/// Mint the `net-org-admission` proof header for a protected unary call (E2.1):
/// sign an [`OrgCallProof`] binding THIS `call_id` and the finalized `req` (via
/// the shared [`org_request_digest`], which strips any admission header, so the
/// caller signing and the provider verifying derive the SAME digest) under the
/// caller's [`OrgProofIntent`]. Returns the single header the caller appends.
fn sign_admission_proof(
    intent: &OrgProofIntent,
    call_id: u64,
    req: &RpcRequestPayload,
) -> Result<(String, Vec<u8>), RpcError> {
    // The intent's capability must match the invoked service (`nrpc:<service>`),
    // else the provider would deny `CapabilityMismatch` — fail the caller locally
    // (Kyra #47 tail).
    let expected = CapabilityAuthorityId::for_tag(&format!("nrpc:{}", req.service));
    if intent.capability != expected {
        return Err(RpcError::Codec {
            direction: CodecDirection::Encode,
            message: format!(
                "org admission: intent capability does not match the invoked service `{}`",
                req.service
            ),
        });
    }
    // The requested TTL must be an honest, finite lifetime the provider will
    // accept: fail the CALLER locally unless `1..=MAX_ORG_PROOF_TTL_SECS`
    // (Kyra #47 tail). This is the SAME ceiling (`org_call::MAX_ORG_PROOF_TTL_SECS`,
    // 30 s) the provider enforces at verify time (§2.3), so a caller cannot mint a
    // proof the provider is guaranteed to reject as `TtlTooLong`. We do NOT clamp:
    // silently capping would mint a proof with a lifetime the caller did not
    // request. 0 is rejected too — a proof that expires within the same whole
    // second is not a usable credential and only differs from a live one inside
    // the provider's clock-skew tolerance, so it must not be treated as a valid
    // request.
    if intent.proof_ttl_secs == 0 || intent.proof_ttl_secs > MAX_ORG_PROOF_TTL_SECS {
        return Err(RpcError::Codec {
            direction: CodecDirection::Encode,
            message: format!(
                "org admission: proof TTL {}s out of range (1..={MAX_ORG_PROOF_TTL_SECS})",
                intent.proof_ttl_secs
            ),
        });
    }
    let digest = org_request_digest(req).map_err(|e| RpcError::Codec {
        direction: CodecDirection::Encode,
        message: format!("org admission: request digest failed: {e}"),
    })?;
    // Derive the expiry from a NANOSECOND base (Kyra #47 tail): `current_timestamp()`
    // is whole seconds, so `secs * 1e9` truncates the sub-second remainder and
    // expires a proof up to ~1s early; a nanosecond `now` avoids that.
    let ttl_secs = intent.proof_ttl_secs;
    let now_ns = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    let expiry = now_ns.saturating_add(ttl_secs.saturating_mul(1_000_000_000));
    let proof = OrgCallProof::sign_for_call(
        &intent.caller,
        intent.membership.clone(),
        intent.dispatcher.clone(),
        intent.capability_grant.clone(),
        intent.acting_org,
        intent.provider_owner_org,
        intent.provider.clone(),
        call_id,
        intent.capability,
        expiry,
        digest,
    );
    let bytes = proof.encode().map_err(|e| RpcError::Codec {
        direction: CodecDirection::Encode,
        message: format!("org admission: proof encode failed: {e}"),
    })?;
    Ok((ORG_ADMISSION_HEADER.to_string(), bytes))
}

fn mint_random_call_id() -> u64 {
    thread_local! {
        // (pool, cursor). Cursor starts exhausted so the first
        // mint on each thread performs the initial refill.
        static CALL_ID_ENTROPY_POOL: std::cell::RefCell<([u8; CALL_ID_ENTROPY_POOL_BYTES], usize)> = const {
            std::cell::RefCell::new(([0u8; CALL_ID_ENTROPY_POOL_BYTES], CALL_ID_ENTROPY_POOL_BYTES))
        };
    }
    CALL_ID_ENTROPY_POOL.with(|cell| {
        let mut pool = cell.borrow_mut();
        let (buf, cursor) = &mut *pool;
        if *cursor >= CALL_ID_ENTROPY_POOL_BYTES {
            if getrandom::fill(buf).is_err() {
                // Entropy unavailable. Do NOT return 0 — concurrent
                // callers would all mint 0 and clobber each other's
                // pending entries. A process-global counter keeps ids
                // distinct (starts at 1, so it is non-zero until it
                // wraps the full u64 range, at which point the 0 is
                // mapped to 1 below).
                static CALL_ID_FALLBACK: std::sync::atomic::AtomicU64 =
                    std::sync::atomic::AtomicU64::new(1);
                let id = CALL_ID_FALLBACK.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                return if id == 0 { 1 } else { id };
            }
            *cursor = 0;
        }
        let mut id = [0u8; 8];
        id.copy_from_slice(&buf[*cursor..*cursor + 8]);
        *cursor += 8;
        // Reserve 0 as the "no correlation" sentinel: on the ~1-in-2^64
        // chance the pool yields all-zero bytes, remap to a fixed non-zero.
        match u64::from_le_bytes(id) {
            0 => 1,
            id => id,
        }
    })
}

/// Per-thread OS-entropy pool size for [`mint_random_call_id`].
/// 64 ids (512 bytes) per `getrandom` syscall — the syscall cost
/// is dominated by the fixed kernel round-trip, so batching 64
/// mints recovers ~98% of the per-call overhead while keeping the
/// amount of buffered future-id entropy per thread small.
const CALL_ID_ENTROPY_POOL_BYTES: usize = 64 * 8;

// ============================================================================
// Internal: tiny shims so the `serve_rpc` / `call` impls stay
// readable. The underlying state lives on `MeshNode`; these just
// rename the accessor methods locally.
// ============================================================================

impl MeshNode {
    fn rpc_client_pending(&self) -> Arc<crate::adapter::net::cortex::RpcClientPending> {
        self.rpc_client_pending_arc()
    }
    fn identity_origin_hash(&self) -> u64 {
        self.public_key_origin_hash()
    }

    /// Caller-side helper that pairs `rpc_route_for_service` with
    /// the `RpcError::NoRoute { target, reason }` mapping every
    /// `Mesh::call*` entry point needs. Returning `Arc<RpcRoute>`
    /// keeps the hot-path allocation profile of the cache intact
    /// (one refcount bump per caller).
    fn rpc_route_or_no_route(
        &self,
        target_node_id: u64,
        service: &str,
    ) -> Result<Arc<super::mesh::RpcRoute>, RpcError> {
        self.rpc_route_for_service(service)
            .map_err(|reason| RpcError::NoRoute {
                target: target_node_id,
                reason,
            })
    }
}

// `proximity_graph()` is already a public accessor on MeshNode
// (see the existing `pub fn proximity_graph(&self) -> &Arc<...>`).
// `select_target` uses it directly; no shim needed.

// ============================================================================
// Errors.
// ============================================================================

/// Errors returned by [`MeshNode::serve_rpc`].
#[derive(Debug, thiserror::Error)]
pub enum ServeError {
    /// The service name fails channel-name validation.
    #[error("invalid service name: {0}")]
    InvalidServiceName(String),
    /// A handler for this service is already registered on this
    /// node. Drop the prior `ServeHandle` to free the slot.
    #[error("already serving service `{0}` on this node")]
    AlreadyServing(String),
    /// The descriptor announces `pricing_terms`, but this serve path
    /// has no payment-admission gate — an announced price this path
    /// cannot enforce must never reach discovery (callers would see a
    /// priced tool that serves free). Serve paid tools via the SDK's
    /// `Mesh::serve_tool_paid` (native gate), or publish through the
    /// MCP adapter's `ServerPublisher::publish_tools` with a
    /// `payment_admission` gate.
    #[error(
        "tool `{0}` announces pricing_terms but this serve path cannot enforce payment — \
         serve paid tools via Mesh::serve_tool_paid, or publish via \
         ServerPublisher::publish_tools with payment_admission"
    )]
    UnenforceablePricing(String),
    /// The gated serve path (`Mesh::serve_tool_paid`) got a descriptor
    /// with **no** `pricing_terms`: a payment gate on an unannounced
    /// price means every caller is refused with no way to know why.
    /// Announce the price (the gate enforces it), or serve the tool
    /// free via `Mesh::serve_tool`.
    #[error(
        "tool `{0}` is served through the payment gate but announces no pricing_terms — \
         attach terms to the descriptor, or serve it free via Mesh::serve_tool"
    )]
    MissingPricingTerms(String),
    /// A protected (`serve_rpc_protected`) registration was attempted with no
    /// installed node authority (E1.1). Org admission needs the provider's
    /// proven owner org + revocation store; without them the handler could
    /// never admit, so registration is refused up front rather than serving a
    /// service that denies every call.
    #[error(
        "protected service `{0}` requires an installed node authority; adopt one before serving"
    )]
    ProtectedAuthorityRequired(String),
    /// A protected registration was given an admission mode that is not
    /// org-protected (`PublicAuthenticated`), or otherwise failed the
    /// [`RegisteredRpcService::protected`] shape check.
    #[error("invalid protected registration: {0}")]
    InvalidProtectedRegistration(String),
    /// A subnet-exported registration whose declared crossing is not
    /// currently authorized (SUBNET_AUTH_PLAN.md D7): no boundary set
    /// or gateway credentials installed, the binding is not an exact
    /// declared boundary, exact `EXPORT` is absent, or the epochs /
    /// expiry / floors have moved past the binding.
    #[error("subnet export not authorized: {0}")]
    SubnetExportUnauthorized(String),
}

/// A publicly announced provider of a service together with its
/// currently verified owner organization, both sampled from one
/// capability-fold snapshot (SUBNET_AUTH_SDK_PLAN.md R1).
///
/// Produced only by [`MeshNode::public_owned_service_providers`]; the
/// projection is the ingest-verified owner cert's org, floor-retractable,
/// never a caller-claimed value. `provider` is the entity the projection
/// itself named AND the live session pin, which that seam requires to be
/// equal — never a node-id resolution the caller has to trust.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublicOwnedProvider {
    /// The provider entity: the verified publisher, confirmed against
    /// its live AEAD session pin.
    pub provider: crate::adapter::net::identity::EntityId,
    /// The provider's verified owner organization.
    pub owner_org: crate::adapter::net::behavior::org::OrgId,
}

/// The admission shape for a unary serve registration (E1.1), threaded from the
/// public `serve_rpc` / protected `serve_rpc_protected` wrappers into the shared
/// `serve_rpc_unary_impl`. Streaming / duplex have no protected form (E1.8).
enum UnaryAdmission {
    /// Legacy v0.4 public: `PublicAuthenticated` + a trivial allow-all policy.
    Public,
    /// Org-protected: an org admission mode + the explicit provider policy.
    Protected {
        admission: OrgAdmission,
        provider_policy: OrgProviderPolicy,
    },
    /// OA3-4b1 owner-scoped: `OwnerScoped` visibility (emitted only as an
    /// encrypted owner-audience announcement, never plaintext),
    /// [`OrgAdmission::OwnerDelegated`] invocation authority, and an explicit
    /// provider policy.
    OwnerScoped { provider_policy: OrgProviderPolicy },
    /// OA3-4b2 granted-audience: `GrantedAudience` visibility (emitted only as an
    /// encrypted grant-audience announcement, never plaintext),
    /// [`OrgAdmission::CrossOrgGranted`] invocation authority, and an explicit
    /// provider policy.
    Granted { provider_policy: OrgProviderPolicy },
    /// SUBNET_AUTH_PLAN.md D7: an org-protected registration additionally
    /// bound to ONE exact declared subnet crossing. Dispatch revalidates
    /// the binding against live gateway/boundary/epoch state per call,
    /// BEFORE org admission; discovery visibility stays `Public` —
    /// subnet export is an execution boundary, not a discovery mode.
    SubnetExported {
        admission: OrgAdmission,
        export: SubnetExportBinding,
        provider_policy: OrgProviderPolicy,
    },
    /// Test-only (review-7 RED negative control): a protected registration whose
    /// dispatch bypasses ONLY `verify_org_admission`. Not reachable from any
    /// production serve wrapper; compiled out entirely without `cfg(test)`.
    #[cfg(test)]
    ProtectedRedWitnessDisabled {
        admission: OrgAdmission,
        provider_policy: OrgProviderPolicy,
    },
}

impl UnaryAdmission {
    /// The announcement visibility this registration mode carries — the
    /// discriminator the local-service registry stores so emission can exclude
    /// owner-scoped / granted `nrpc:` tags from the plaintext broadcast
    /// (OA3-4b1 / OA3-4b2).
    fn visibility(&self) -> CapabilityVisibility {
        match self {
            Self::Public | Self::Protected { .. } | Self::SubnetExported { .. } => {
                CapabilityVisibility::Public
            }
            Self::OwnerScoped { .. } => CapabilityVisibility::OwnerScoped,
            Self::Granted { .. } => CapabilityVisibility::GrantedAudience,
            #[cfg(test)]
            Self::ProtectedRedWitnessDisabled { .. } => CapabilityVisibility::Public,
        }
    }

    /// The response-routing policy this registration mode carries.
    ///
    /// A legacy public service keeps the AV-5 roster fallback: an honest
    /// caller that reconnected under a new `NodeId` (its cached direct route
    /// went stale) is still reachable through its signed subscriber roster
    /// subscription, so a pre-send miss fans out rather than dropping.
    ///
    /// Every org-protected mode is [`ResponseRouteFallback::DirectOnly`]. The
    /// roster leg buys them nothing — admission already required a pinned
    /// direct session ([`resolve_direct_caller`] refuses a caller it cannot
    /// bind to the AEAD-authenticated peer), so a protected response always
    /// has an authenticated unicast target or no legitimate destination at
    /// all. And it costs them the confidentiality guarantee the mode exists
    /// to provide: `<service>.replies.<caller_origin>` is auto-registered as
    /// a DEFAULT-PERMISSIVE prefix by the SDK
    /// (`sdk::mesh_rpc::auto_register_rpc_channels`), and `authorize_subscribe`
    /// does not bind a subscriber to the origin named in the channel, so ANY
    /// peer may hold a live subscription to another caller's reply channel.
    /// Roster-fanning a `CrossOrgGranted` response onto that channel
    /// discloses an org-confidential body to every such subscriber.
    ///
    /// The two reachable triggers are both ordinary operation, not attack
    /// preconditions: eviction from the `RPC_CALLER_CACHE_CAP`-bounded route
    /// cache under concurrency, and `PeerPublishOutcome::NoSession` when the
    /// caller's session dropped between admission and send. Dropping the
    /// frame in both cases is correct — the caller times out, which is the
    /// same outcome it already gets from a full response drainer channel.
    fn response_route_fallback(&self) -> ResponseRouteFallback {
        match self {
            Self::Public => ResponseRouteFallback::RosterOnStaleDirect,
            Self::Protected { .. }
            | Self::OwnerScoped { .. }
            | Self::Granted { .. }
            | Self::SubnetExported { .. } => ResponseRouteFallback::DirectOnly,
            // The RED negative control must route exactly like the protected
            // registration it is the control FOR, or the witness would differ
            // from production on the response leg as well as the gate.
            #[cfg(test)]
            Self::ProtectedRedWitnessDisabled { .. } => ResponseRouteFallback::DirectOnly,
        }
    }
}

// ============================================================================
// Typed-call helper.
// ============================================================================

/// Wire-shape failures from [`typed_call`]. Distinct variants
/// for transport (no route, timeout, etc.) vs codec (serde /
/// postcard) so service-specific client error enums can wrap
/// each independently. Server-level (application) errors are
/// decoded into `Resp` itself — the client matches on the
/// resulting `Resp::Error(...)` variant.
#[derive(Debug, thiserror::Error)]
pub enum TypedCallError {
    /// Transport-level failure surfaced by [`MeshNode::call`].
    #[error("transport: {0}")]
    Transport(#[from] RpcError),
    /// Request serialization or response deserialization failed.
    #[error("codec: {0}")]
    Codec(String),
}

impl From<postcard::Error> for TypedCallError {
    fn from(e: postcard::Error) -> Self {
        Self::Codec(e.to_string())
    }
}

/// Send a postcard-encoded request to a remote RPC service and
/// decode the postcard-encoded reply. The shared shape every
/// substrate-internal RPC client wants:
///
/// 1. `postcard::to_allocvec(request)` → wire body.
/// 2. `MeshNode::call(target, service, body, opts{deadline})`.
/// 3. `postcard::from_bytes::<Resp>(reply.body)`.
///
/// Caller wraps the returned `Resp` in its own typed-error
/// surface (typically a `Server` variant that holds the
/// service-specific error enum decoded from `Resp`). Returning
/// `TypedCallError` here keeps the wrapper code to a one-line
/// `From<TypedCallError>` impl per client.
pub async fn typed_call<Req, Resp>(
    mesh: &std::sync::Arc<crate::adapter::net::MeshNode>,
    target_node_id: u64,
    service: &str,
    request: &Req,
    deadline: std::time::Duration,
) -> Result<Resp, TypedCallError>
where
    Req: serde::Serialize,
    Resp: serde::de::DeserializeOwned,
{
    let body = postcard::to_allocvec(request)?;
    let opts = CallOptions {
        deadline: Some(std::time::Instant::now() + deadline),
        ..Default::default()
    };
    let reply = mesh
        .call(target_node_id, service, Bytes::from(body), opts)
        .await?;
    Ok(postcard::from_bytes(&reply.body)?)
}

// ============================================================================
// Helpers.
// ============================================================================

/// Detect the "no session to the target node id" sub-case of
/// [`AdapterError::Connection`]. The publish path can surface
/// this through one of two messages depending on which inner
/// helper landed it:
///
///   - `"publish: no session for subscriber {hash}"` — emitted
///     by `mesh.rs::publish_to_peer` when the subscriber-roster
///     path can't find an active session.
///   - `"no session to publisher {hash}"` — emitted by the lower
///     mesh.rs send path when there's no active session to the
///     target's publisher record at all.
///
/// Both mean "I can't reach this peer". When we observe either,
/// we surface as [`RpcError::NoRoute`] rather than `Transport`
/// because retrying the same target without a session is
/// pointless and the right behavior for a routing helper is to
/// try a different target.
fn classify_publish_no_session(err: &AdapterError) -> bool {
    match err {
        AdapterError::Connection(msg) => {
            msg.contains("no session for subscriber") || msg.contains("no session to publisher")
        }
        _ => false,
    }
}

fn instant_to_unix_nanos(instant: Instant) -> u64 {
    // `Instant` is monotonic and not wall-clock — convert via the
    // delta from now plus current SystemTime. The result drifts
    // marginally with wall-clock skew but is good enough for
    // server-side deadline-already-passed short-circuits (which are
    // the only consumer of `deadline_ns`).
    let now_instant = Instant::now();
    let now_wall = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0);
    if instant >= now_instant {
        let delta = instant.duration_since(now_instant);
        now_wall.saturating_add(delta.as_nanos() as u64)
    } else {
        let delta = now_instant.duration_since(instant);
        now_wall.saturating_sub(delta.as_nanos() as u64)
    }
}

#[allow(dead_code)]
fn _ensure_send_sync() {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<ServeHandle>();
    assert_send_sync::<RpcCancellationToken>();
    assert_send_sync::<RpcContext>();
    assert_send_sync::<RpcHandlerError>();
    assert_send_sync::<RpcStatus>();
    assert_send_sync::<RpcReply>();
    assert_send_sync::<CallOptions>();
}

#[cfg(test)]
mod reply_subscribe_retry_tests {
    /// The retry condition and the corrective-announce latch are two
    /// separate decisions, and re-fusing them is a silent regression:
    /// the loop still compiles, still retries once, and only misbehaves
    /// on a caller's very first call to a target — precisely the case
    /// the retry exists for.
    ///
    /// The failure it reintroduces: attempt 0 rejected, claims the
    /// latch, announces. Attempt 1 rejected (the announce is still in
    /// flight), finds the latch spent, reads `false` as "not retryable"
    /// and breaks — throwing away the remaining attempt and returning
    /// `NoRoute` for a target that would have accepted a moment later.
    ///
    /// Structural rather than behavioural: exercising the loop needs two
    /// live sessions and a server that rejects exactly twice. So pin the
    /// shape instead — the latch may appear only as a statement guarding
    /// the announce, never inside the expression bound to `retryable`.
    ///
    /// Scans the production function only. `ensure_reply_subscription`
    /// is above every `#[cfg(test)]` module in this file, so truncating
    /// at the first one keeps this test from matching its own prose.
    #[test]
    fn the_announce_latch_does_not_gate_the_retry() {
        let src = include_str!("mesh_rpc.rs");
        let start = src
            .find("    async fn ensure_reply_subscription(")
            .expect("ensure_reply_subscription must exist");
        let end = src
            .find("\n#[cfg(test)]")
            .expect("this file has test modules");
        assert!(
            start < end,
            "ensure_reply_subscription moved below the test modules; this scan \
             would read its own source"
        );
        let body = &src[start..end];

        let retryable = body
            .find("let retryable = ")
            .expect("the retry decision must still be a named binding");
        let stmt_end = body[retryable..]
            .find(';')
            .expect("the retryable binding must terminate");
        let binding = &body[retryable..retryable + stmt_end];
        assert!(
            !binding.contains("claim_corrective_announce"),
            "regression: the once-per-target announce latch is back inside the \
             retry condition ({binding:?}). Attempt 1 would then read a spent \
             latch as a permanent denial and abandon the announcement attempt \
             0 had just sent. The latch bounds ANNOUNCES, not attempts."
        );
        assert!(
            binding.contains("warrants_reannounce"),
            "the retry condition must remain the `Unauthorized` test — \
             retrying anything else cannot change the answer"
        );
        assert!(
            body.contains("if self.claim_corrective_announce(target_node_id) {"),
            "regression: the corrective announce must stay behind the \
             once-per-target latch, or one persistently-denying target turns \
             every RPC into extra rate-limit-bypassing capability broadcasts"
        );
    }
}

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

    /// KC7 (Kyra E1 audit) — the response-route cache is populated
    /// ONLY for a trustworthy destination. Because the cache is keyed
    /// on the wire-claimed `origin_hash`, a frame whose claimed origin
    /// does not match the AEAD-authenticated `from_node` peer's OWN
    /// origin (a malicious node stamping a victim's origin), a control
    /// frame, an unpinned peer, or the loopback sentinel must NEVER
    /// establish a destination — so a denied/forged frame can't
    /// redirect a legitimate call's response.
    #[test]
    fn response_route_trust_requires_authenticated_direct_origin() {
        let victim_origin = 0x1111_2222_3333_4444u64;
        let peer_node = 0xABCDu64;

        // Honest: REQUEST, authenticated peer's own origin → trusted.
        assert!(response_route_is_trustworthy(
            peer_node,
            Some(DISPATCH_RPC_REQUEST),
            victim_origin,
            Some(victim_origin),
        ));

        // Forged: the claim (victim_origin) ≠ the authenticated peer's
        // real origin → REFUSED (the poison the fix prevents).
        assert!(!response_route_is_trustworthy(
            peer_node,
            Some(DISPATCH_RPC_REQUEST),
            victim_origin,
            Some(0x9999_9999_9999_9999),
        ));

        // Control frames never establish routing, even authenticated.
        for dispatch in [
            DISPATCH_RPC_CANCEL,
            DISPATCH_RPC_REQUEST_CHUNK,
            DISPATCH_RPC_REQUEST_GRANT,
        ] {
            assert!(!response_route_is_trustworthy(
                peer_node,
                Some(dispatch),
                victim_origin,
                Some(victim_origin),
            ));
        }

        // Unpinned peer (no authenticated entity) → refused.
        assert!(!response_route_is_trustworthy(
            peer_node,
            Some(DISPATCH_RPC_REQUEST),
            victim_origin,
            None,
        ));

        // Loopback/test sentinel (from_node == 0) → refused.
        assert!(!response_route_is_trustworthy(
            0,
            Some(DISPATCH_RPC_REQUEST),
            victim_origin,
            Some(victim_origin),
        ));

        // Non-decodable dispatch → refused.
        assert!(!response_route_is_trustworthy(
            peer_node,
            None,
            victim_origin,
            Some(victim_origin),
        ));
    }

    /// The crafted-origin memory-amplification guard (cubic P2): the reply-
    /// channel / origin-node caches are keyed by the *wire-claimed*
    /// `caller_origin`, which a single authed peer can vary freely. Spraying
    /// far more distinct origins than the capacity must NOT grow the cache —
    /// it stays pinned at `RPC_CALLER_CACHE_CAP`, evicting the coldest.
    #[test]
    fn origin_keyed_lru_bounds_under_crafted_origin_flood() {
        let cache: BoundedLru<(u64, u64), u64> = BoundedLru::new();
        let flood = (RPC_CALLER_CACHE_CAP as u64) * 4;
        for origin in 0..flood {
            // Call-scoped key: a peer sprays distinct `(origin, call_id)`
            // keys just as easily as distinct origins; the LRU still
            // bounds the footprint.
            cache.insert((origin, origin), origin);
        }
        assert_eq!(
            cache.0.lock().len(),
            RPC_CALLER_CACHE_CAP,
            "cache must stay at its capacity bound under a crafted-origin flood"
        );
        // The most-recently-seen window survives; the cold prefix is evicted.
        assert_eq!(cache.get((flood - 1, flood - 1)), Some(flood - 1));
        assert_eq!(cache.get((0, 0)), None);
    }

    /// PERF_AUDIT §3.8 — `mint_random_call_id` mints thousands of
    /// values from the pooled-entropy path, all of which must be
    /// distinct in practice (a duplicate would let two in-flight
    /// calls collide on the per-Mesh pending map). 100k samples is
    /// far below the 2^32 birthday-paradox boundary, so a
    /// regression that recycled pool bytes (cursor mis-advance,
    /// missed refill) would fail loudly. The loop also crosses the
    /// pool-refill boundary thousands of times (pool holds 64 ids),
    /// pinning the refill/cursor arithmetic.
    #[test]
    fn mint_random_call_id_produces_distinct_values_across_thousands_of_calls() {
        let mut seen = std::collections::HashSet::with_capacity(100_000);
        for _ in 0..100_000 {
            let id = super::mint_random_call_id();
            // 0 is the fallback sentinel — should not appear under
            // a working `getrandom` refill.
            assert_ne!(id, 0, "fallback-zero path triggered unexpectedly");
            assert!(seen.insert(id), "duplicate call_id minted: {:#x}", id);
        }
    }

    /// PERF_AUDIT §3.8 — minted ids are raw OS entropy: count
    /// set-bits across 10k mints and assert the fraction is near
    /// 0.5. A pool-management bug that handed out the zeroed
    /// initial buffer (or re-served a stale window) would skew
    /// this hard; properly random 64-bit ids have expected ~0.5
    /// set bits per sample with O(1/sqrt(N)) tolerance.
    #[test]
    fn mint_random_call_id_set_bit_density_is_balanced() {
        let n = 10_000u64;
        let mut total_set: u64 = 0;
        for _ in 0..n {
            total_set += super::mint_random_call_id().count_ones() as u64;
        }
        let bits_total = n * 64;
        let fraction = total_set as f64 / bits_total as f64;
        // Expected 0.5; tolerance generous (~3σ) to keep the test
        // reliable while still catching collapsed-pool regressions.
        assert!(
            (fraction - 0.5).abs() < 0.02,
            "set-bit density {} is too far from 0.5 — pool may be mismanaged",
            fraction
        );
    }

    /// PERF_AUDIT §3.5 — the reply-subscription registry's hot
    /// path must be a `(target, xxh3(service))` lookup, not a
    /// `Mutex<Vec<(u64, String)>>` linear scan. Pin the contract
    /// via `reply_subscription_covers` (the exact hot-path check):
    /// 1. distinct (target, service) pairs are distinct keys —
    ///    same service against two targets, and two services
    ///    against one target, never alias;
    /// 2. repeat insert of the same pair is idempotent and the
    ///    fast path keeps answering `true`;
    /// 3. an xxh3 COLLISION (same hash, different service name)
    ///    must NOT count as covered — a false positive here would
    ///    skip a needed subscribe and silently drop the colliding
    ///    service's replies. The stored-name verification turns it
    ///    into a re-subscribe instead;
    /// 4. the cap is enforced via `len()`, not a separate counter
    ///    that could drift.
    #[test]
    fn reply_subscriptions_keyed_by_target_and_service_hash() {
        use dashmap::DashMap;
        let registry: DashMap<(u64, u64), ReplySubscription> = DashMap::new();
        let h_a = xxhash_rust::xxh3::xxh3_64(b"svc-a");
        let h_b = xxhash_rust::xxh3::xxh3_64(b"svc-b");
        // Same target, different services → distinct entries.
        registry.insert(
            (0xAA, h_a),
            ReplySubscription {
                service: Arc::from("svc-a"),
                written_at_generation: 0,
            },
        );
        registry.insert(
            (0xAA, h_b),
            ReplySubscription {
                service: Arc::from("svc-b"),
                written_at_generation: 0,
            },
        );
        assert!(super::reply_subscription_covers(
            &registry, 0xAA, h_a, "svc-a"
        ));
        assert!(super::reply_subscription_covers(
            &registry, 0xAA, h_b, "svc-b"
        ));
        // Same service, different targets → distinct entries.
        assert!(!super::reply_subscription_covers(
            &registry, 0xBB, h_a, "svc-a"
        ));
        registry.insert(
            (0xBB, h_a),
            ReplySubscription {
                service: Arc::from("svc-a"),
                written_at_generation: 0,
            },
        );
        assert!(super::reply_subscription_covers(
            &registry, 0xBB, h_a, "svc-a"
        ));
        // Idempotent — repeat insert overwrites with the identical
        // value; the fast path keeps answering true.
        registry.insert(
            (0xAA, h_a),
            ReplySubscription {
                service: Arc::from("svc-a"),
                written_at_generation: 0,
            },
        );
        assert!(super::reply_subscription_covers(
            &registry, 0xAA, h_a, "svc-a"
        ));
        assert_eq!(registry.len(), 3);
        // xxh3 collision: "svc-evil" hashing to h_a (forced here —
        // xxh3_64 collisions are computable offline since the hash
        // isn't cryptographic) must NOT cover "svc-a"'s slot, and
        // vice versa. The hash-only DashSet shape this replaced
        // answered `true` and silently skipped the subscribe.
        assert!(
            !super::reply_subscription_covers(&registry, 0xAA, h_a, "svc-evil"),
            "hash collision must not satisfy the membership check for a \
             different service name"
        );
        // After the colliding service legitimately subscribes (slot
        // overwritten), the original service degrades to
        // re-subscribe — covered must flip to false for it, never
        // silently true for both.
        registry.insert(
            (0xAA, h_a),
            ReplySubscription {
                service: Arc::from("svc-evil"),
                written_at_generation: 0,
            },
        );
        assert!(super::reply_subscription_covers(
            &registry, 0xAA, h_a, "svc-evil"
        ));
        assert!(!super::reply_subscription_covers(
            &registry, 0xAA, h_a, "svc-a"
        ));
    }

    /// The fence rollback must remove the entry ITS OWN call wrote, and
    /// leave a newer one alone.
    ///
    /// The losing sequence, which removing by key alone produced: call A
    /// snapshots generation 0 and inserts; the peer fails and recovers;
    /// call B snapshots generation 1, subscribes successfully on the new
    /// session and inserts; call A finally reaches its fence, sees the
    /// generation moved, and deletes B's entry. B's caller believes it
    /// is subscribed — it is, and correctly so — but the cache no longer
    /// says so, and its next RPC re-subscribes for nothing.
    ///
    /// Not a correctness hole (the redundant subscribe is idempotent),
    /// which is why the stamp is cheap insurance rather than a fix for
    /// data loss. Modelled rather than raced: two RPC calls interleaving
    /// around a session failure is not something the harness schedules
    /// deterministically.
    #[test]
    fn the_fence_rollback_spares_a_newer_calls_entry() {
        use dashmap::DashMap;
        let registry: DashMap<(u64, u64), ReplySubscription> = DashMap::new();
        let key = (0xAAu64, xxhash_rust::xxh3::xxh3_64(b"svc"));

        // Call A, at generation 0.
        registry.insert(
            key,
            ReplySubscription {
                service: Arc::from("svc"),
                written_at_generation: 0,
            },
        );
        // Peer fails and recovers; call B re-subscribes at generation 1.
        registry.insert(
            key,
            ReplySubscription {
                service: Arc::from("svc"),
                written_at_generation: 1,
            },
        );

        // Call A's fence fires late. Its rollback must be a no-op.
        registry.remove_if(&key, |_, entry| entry.written_at_generation == 0);
        assert!(
            super::reply_subscription_covers(&registry, key.0, key.1, "svc"),
            "the late rollback deleted a newer call's entry; that caller is \
             genuinely subscribed and will now re-subscribe for nothing"
        );

        // …and when the entry IS the one that call wrote, it goes.
        registry.remove_if(&key, |_, entry| entry.written_at_generation == 1);
        assert!(
            !super::reply_subscription_covers(&registry, key.0, key.1, "svc"),
            "a call must still be able to roll back its own entry — leaving it \
             is the stale-cache bug the fence exists to prevent"
        );
    }

    /// PERF_AUDIT §3.3 — grant-stall backstop check for the
    /// window/2 auto-grant coalescing. Simulates the full
    /// credit loop for every window 1..=64: the server starts
    /// with `window` credits and consumes one per chunk; the
    /// client accumulates via `accumulate_auto_grant` and only
    /// flushes at the threshold. Asserts:
    /// 1. liveness — an actively-polling consumer never observes
    ///    the server starved (credits exhausted with nothing left
    ///    to poll), i.e. withholding sub-threshold credits cannot
    ///    deadlock the stream and no timer/drop backstop is needed;
    /// 2. coalescing — grant-packet count stays at
    ///    ~chunks / (window/2), and is strictly fewer than one
    ///    grant per chunk once window ≥ 4 (the integration suite
    ///    only exercises window=2, whose threshold degenerates
    ///    to per-chunk).
    #[test]
    fn auto_grant_coalescing_never_starves_the_server_pump() {
        for window in 1u32..=64 {
            let chunks = 1_000u32;
            let mut server_credits = window as u64;
            let mut pending = 0u32;
            let mut sent = 0u32;
            let mut delivered = 0u32;
            let mut grants = 0u32;
            while delivered < chunks {
                // Server pump: send while credits remain.
                while server_credits > 0 && sent < chunks {
                    server_credits -= 1;
                    sent += 1;
                }
                assert!(
                    sent > delivered,
                    "window {window}: server starved while the consumer is actively \
                     polling (credits {server_credits}, pending {pending}, \
                     sent {sent}, delivered {delivered})"
                );
                // Consumer polls exactly one chunk.
                delivered += 1;
                if let Some(amount) = super::accumulate_auto_grant(&mut pending, window) {
                    grants += 1;
                    server_credits += amount as u64;
                }
            }
            let threshold = (window / 2).max(1);
            assert!(
                grants <= chunks / threshold + 1,
                "window {window}: {grants} grant packets exceeds the \
                 coalesced cadence bound of {}",
                chunks / threshold + 1
            );
            if window >= 4 {
                assert!(
                    grants < chunks,
                    "window {window}: coalescing must emit fewer grants than chunks"
                );
            }
        }
    }

    /// `get` promotes to most-recently-used, so a touched entry outlives an
    /// untouched one when the cache overflows by one — confirming the wrapper
    /// gives true LRU semantics (a hot caller isn't evicted out from under an
    /// in-flight exchange).
    #[test]
    fn origin_keyed_lru_get_promotes_to_mru() {
        let cache: BoundedLru<(u64, u64), u64> = BoundedLru::new();
        for origin in 0..(RPC_CALLER_CACHE_CAP as u64) {
            cache.insert((origin, 0), origin);
        }
        // Touch (0, 0) (otherwise the LRU), then overflow by one entry.
        assert_eq!(cache.get((0, 0)), Some(0));
        cache.insert((u64::MAX, 0), 1);
        assert_eq!(
            cache.get((0, 0)),
            Some(0),
            "touched entry must survive eviction"
        );
        assert_eq!(
            cache.get((1, 0)),
            None,
            "the now-LRU entry (1) must be evicted"
        );
    }

    /// R2-5 (Kyra addendum): the response-route cache is keyed by the
    /// FULL `(from_node, origin, call_id)` — so two authenticated
    /// sessions pinned to the SAME entity/origin that submit the SAME
    /// call_id resolve to their OWN destination and retiring one leaves
    /// the other intact. (With the AV-4 `(origin, call_id)` key the
    /// second session's insert clobbered the first, and either response
    /// could route to the wrong session.)
    #[test]
    fn response_route_cache_is_session_scoped_and_retires_per_call() {
        let cache: BoundedLru<(u64, u64, u64), u64> = BoundedLru::new();
        const ORIGIN: u64 = 0xAA;
        const CALL: u64 = 7; // SAME call_id for both sessions
        const NODE_A: u64 = 0x10;
        const NODE_B: u64 = 0x20;
        // Two sessions, same origin, SAME call_id.
        cache.insert((NODE_A, ORIGIN, CALL), NODE_A);
        cache.insert((NODE_B, ORIGIN, CALL), NODE_B);
        // No clobber — each resolves to its own session.
        assert_eq!(cache.get((NODE_A, ORIGIN, CALL)), Some(NODE_A));
        assert_eq!(cache.get((NODE_B, ORIGIN, CALL)), Some(NODE_B));
        // Retiring session A's route leaves session B's intact.
        cache.remove((NODE_A, ORIGIN, CALL));
        assert_eq!(cache.get((NODE_A, ORIGIN, CALL)), None);
        assert_eq!(cache.get((NODE_B, ORIGIN, CALL)), Some(NODE_B));
    }

    /// AV-4 item 4: the multi-fire (server-streaming / duplex) emit
    /// closures retire the cached route only on the TERMINAL frame.
    /// `streaming_response_is_terminal` treats a non-`Ok` status
    /// (error / cancel / deadline) or the explicit `nrpc-streaming:
    /// end` marker as terminal; an `Ok` `continue` chunk is not.
    #[test]
    fn streaming_terminal_detection_recognizes_end_and_errors() {
        use crate::adapter::net::cortex::{
            HEADER_NRPC_STREAMING, HEADER_NRPC_STREAMING_CONTINUE, HEADER_NRPC_STREAMING_END,
        };
        let continue_chunk = RpcResponsePayload {
            status: RpcStatus::Ok,
            headers: vec![(
                HEADER_NRPC_STREAMING.to_string(),
                HEADER_NRPC_STREAMING_CONTINUE.to_vec(),
            )],
            body: Bytes::from_static(b"chunk"),
        };
        assert!(
            !streaming_response_is_terminal(&continue_chunk),
            "a continue chunk must NOT be treated as terminal",
        );
        let end_chunk = RpcResponsePayload {
            status: RpcStatus::Ok,
            headers: vec![(
                HEADER_NRPC_STREAMING.to_string(),
                HEADER_NRPC_STREAMING_END.to_vec(),
            )],
            body: Bytes::new(),
        };
        assert!(
            streaming_response_is_terminal(&end_chunk),
            "the nrpc-streaming end marker is terminal",
        );
        let error_frame = RpcResponsePayload {
            status: RpcStatus::Internal,
            headers: vec![],
            body: Bytes::from_static(b"boom"),
        };
        assert!(
            streaming_response_is_terminal(&error_frame),
            "a non-Ok status is terminal",
        );
    }
}

#[cfg(test)]
mod roster_fallback_tests {
    use super::*;
    use crate::adapter::net::{EntityKeypair, MeshNodeConfig};
    use std::net::SocketAddr;
    use std::time::Duration;

    /// R3-1: the upload-grant routing policy. A trusted authenticated
    /// session (`from_node != 0`) gets a `DirectOnly` grant aimed at its
    /// OWN node — so a grant can never roster-fan to a same-origin sibling
    /// and refill the wrong call's request semaphore. The loopback /
    /// relayed-public sentinel (`from_node == 0`, no trusted direct route)
    /// keeps the roster path. Composes with
    /// [`direct_only_frame_drops_while_normal_response_rosters_when_peer_gone`],
    /// which proves `DirectOnly` delivers ONLY to the target and drops
    /// otherwise — together: a grant reaches only its initiating session.
    ///
    /// Red-witness: reverting the grant drainer to an unconditional roster
    /// `mesh.publish` (pre-R3-1) makes this return the roster policy for a
    /// real session.
    #[test]
    fn request_grant_route_is_direct_only_for_authenticated_sessions() {
        assert_eq!(
            request_grant_route(0xABCD),
            (Some(0xABCD), ResponseRouteFallback::DirectOnly),
            "a real authenticated session must get a DirectOnly grant to its own node",
        );
        assert_eq!(
            request_grant_route(0),
            (None, ResponseRouteFallback::RosterOnStaleDirect),
            "the loopback/relayed sentinel keeps the roster path",
        );
    }

    /// Gate-3: the upload-grant route is classified ONCE at admission from the
    /// SAME authenticated-origin equality as response-route trust — never from
    /// `from_node != 0` alone. Direct (pinned origin == claimed) →
    /// `TrustedDirect(node)`; the loopback sentinel → `Loopback`; a nonzero
    /// last hop whose pinned origin != the claimed caller origin (a relayed
    /// frame or forged origin), or an unpinned peer, → `RelayedOrUntrusted`.
    /// Two authenticated sessions sharing one origin + call_id but a different
    /// `from_node` each classify to their OWN `TrustedDirect(node)` — distinct
    /// grant targets, no coalescing collision (witness 3).
    ///
    /// Red-witness: reverting to `from_node != 0 ⇒ TrustedDirect` collapses the
    /// forged/relayed and unpinned cases to `TrustedDirect`, failing here.
    #[test]
    fn classify_request_grant_route_matches_authenticated_origin_equality() {
        const ORIGIN: u64 = 0x1111_2222_3333_4444;
        const NODE_A: u64 = 0xABCD;
        const NODE_B: u64 = 0xBEEF;
        // Direct: the pinned last-hop origin equals the claimed caller origin.
        assert_eq!(
            classify_request_grant_route(NODE_A, ORIGIN, Some(ORIGIN)),
            RequestGrantRoute::TrustedDirect(NODE_A),
        );
        // Relayed / forged: the claim differs from the pinned last-hop origin.
        assert_eq!(
            classify_request_grant_route(NODE_A, ORIGIN, Some(0x9999_9999_9999_9999)),
            RequestGrantRoute::RelayedOrUntrusted,
        );
        // Unpinned peer (connected but never announced) → untrusted.
        assert_eq!(
            classify_request_grant_route(NODE_A, ORIGIN, None),
            RequestGrantRoute::RelayedOrUntrusted,
        );
        // Loopback / test sentinel.
        assert_eq!(
            classify_request_grant_route(0, ORIGIN, Some(ORIGIN)),
            RequestGrantRoute::Loopback,
        );
        // Two direct sessions, same origin (+ implicitly same call_id),
        // different authenticated node → distinct TrustedDirect targets.
        assert_eq!(
            classify_request_grant_route(NODE_A, ORIGIN, Some(ORIGIN)),
            RequestGrantRoute::TrustedDirect(NODE_A),
        );
        assert_eq!(
            classify_request_grant_route(NODE_B, ORIGIN, Some(ORIGIN)),
            RequestGrantRoute::TrustedDirect(NODE_B),
        );
    }

    /// Build a canonical REQUEST frame (`EventMeta ‖ RpcRouteV1 ‖
    /// RpcRequestPayload`) with a chosen payload (EventMeta) origin, call_id,
    /// dispatch, flags, and optional upload-window header — the exact shape a
    /// serve fold decodes at `RPC_FRAME_BODY_OFFSET`.
    fn rpc_request_frame(
        payload_origin: u64,
        call_id: u64,
        dispatch: u8,
        service: &str,
        flags: u16,
        window: Option<&[u8]>,
    ) -> Bytes {
        let headers = match window {
            Some(w) => vec![(HEADER_NRPC_REQUEST_WINDOW_INITIAL.to_string(), w.to_vec())],
            None => vec![],
        };
        let payload = RpcRequestPayload {
            service: service.to_string(),
            deadline_ns: 0,
            flags,
            headers,
            body: Bytes::new(),
        };
        let mut buf = EventMeta::new(dispatch, 0, payload_origin, call_id, 0)
            .to_bytes()
            .to_vec();
        encode_rpc_route(&mut buf, 0);
        buf.extend_from_slice(&payload.encode());
        Bytes::from(buf)
    }

    /// Gate-3: [`reject_relayed_flow_controlled_request`] rejects a REQUEST
    /// ONLY when it is both relayed/untrusted (pinned last-hop origin != the
    /// claimed origin) AND actually flow-controlled (a valid upload-window
    /// header). Without a valid window the upload is the unbounded fast path
    /// with no grant emitter, so even a relayed caller is admitted; a direct
    /// or loopback caller is always admitted; only the initial REQUEST is
    /// classified. Uses the SAME decoder + `parse_request_window_initial`
    /// predicate as the fold (no divergent parser).
    ///
    /// Red-witness: rejecting every initial REQUEST (ignoring the window
    /// header) fails the "relayed + absent/malformed window → admitted" cases;
    /// classifying from `from_node != 0` fails the relayed case.
    #[tokio::test]
    async fn reject_relayed_flow_controlled_request_rejects_only_relayed_flow_controlled_uploads() {
        use std::sync::atomic::Ordering;
        let server = build_server().await;
        let metrics = server.rpc_metrics_arc().for_service("svc.upload");
        const DIRECT_NODE: u64 = 0x51;
        const RELAY_NODE: u64 = 0x52;

        let direct_entity = EntityKeypair::generate().entity_id().clone();
        let relay_entity = EntityKeypair::generate().entity_id().clone();
        let direct_origin = direct_entity.origin_hash();
        let relay_origin = relay_entity.origin_hash();
        server.test_pin_peer_entity(DIRECT_NODE, direct_entity);
        server.test_pin_peer_entity(RELAY_NODE, relay_entity);
        let victim_origin = relay_origin ^ 0xFFFF_FFFF; // guaranteed distinct

        let chan = ChannelId::new(ChannelName::new("svc.upload.requests").unwrap()).hash();
        let frame = |from_node: u64,
                     claimed_origin: u64,
                     call_id: u64,
                     dispatch: u8,
                     window: Option<&[u8]>| {
            RpcInboundEvent {
                channel_hash: chan,
                origin_hash: claimed_origin,
                from_node,
                payload: rpc_request_frame(
                    claimed_origin,
                    call_id,
                    dispatch,
                    "svc.upload",
                    FLAG_RPC_CLIENT_STREAMING_REQUEST,
                    window,
                ),
            }
        };
        let reject = |ev: &RpcInboundEvent| {
            reject_relayed_flow_controlled_request(
                &server,
                &metrics,
                ev,
                "svc.upload",
                "nrpc:svc.upload",
            )
        };
        let rejected = || {
            metrics
                .relayed_flow_controlled_rejected_total
                .load(Ordering::Relaxed)
        };

        // Relayed + VALID upload-window header → rejected (metric +1).
        assert!(
            reject(&frame(
                RELAY_NODE,
                victim_origin,
                1,
                DISPATCH_RPC_REQUEST,
                Some(b"32")
            )),
            "a relayed flow-controlled caller must be rejected before the fold",
        );
        assert_eq!(
            rejected(),
            1,
            "the relayed flow-controlled REQUEST metered once"
        );

        // Relayed + ABSENT window → admitted (unbounded upload, no grant path).
        assert!(
            !reject(&frame(
                RELAY_NODE,
                victim_origin,
                2,
                DISPATCH_RPC_REQUEST,
                None
            )),
            "a relayed caller without a window header is unbounded-upload and admitted",
        );
        // Relayed + MALFORMED window → admitted (fold treats it as absent).
        assert!(
            !reject(&frame(
                RELAY_NODE,
                victim_origin,
                3,
                DISPATCH_RPC_REQUEST,
                Some(b"not-a-number")
            )),
            "a malformed window header parses as absent, matching the fold",
        );
        // Direct + valid window → admitted (pinned origin == claimed).
        assert!(
            !reject(&frame(
                DIRECT_NODE,
                direct_origin,
                4,
                DISPATCH_RPC_REQUEST,
                Some(b"32")
            )),
            "a directly authenticated flow-controlled caller is admitted",
        );
        // Loopback + valid window → admitted.
        assert!(
            !reject(&frame(0, 0xDEAD_BEEF, 5, DISPATCH_RPC_REQUEST, Some(b"32"))),
            "the loopback sentinel is admitted",
        );
        // A CHUNK from the relayed session (even with a window) → not classified.
        assert!(
            !reject(&frame(
                RELAY_NODE,
                victim_origin,
                1,
                DISPATCH_RPC_REQUEST_CHUNK,
                Some(b"32")
            )),
            "only the initial REQUEST is classified; control frames pass through",
        );

        assert_eq!(
            rejected(),
            1,
            "only the one relayed flow-controlled REQUEST was metered"
        );
    }

    /// A client-streaming handler that records each invocation.
    struct RanClientStream(std::sync::Arc<std::sync::atomic::AtomicUsize>);
    #[async_trait::async_trait]
    impl crate::adapter::net::cortex::RpcClientStreamingHandler for RanClientStream {
        async fn call(
            &self,
            _ctx: crate::adapter::net::cortex::RpcStreamingContext,
            mut requests: crate::adapter::net::cortex::RequestStream,
        ) -> Result<RpcResponsePayload, RpcHandlerError> {
            use futures::StreamExt;
            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            while requests.next().await.is_some() {}
            Ok(RpcResponsePayload {
                status: RpcStatus::Ok,
                headers: vec![],
                body: Bytes::new(),
            })
        }
    }

    /// A duplex handler that records each invocation.
    struct RanDuplex(std::sync::Arc<std::sync::atomic::AtomicUsize>);
    #[async_trait::async_trait]
    impl crate::adapter::net::cortex::RpcDuplexHandler for RanDuplex {
        async fn call(
            &self,
            _ctx: crate::adapter::net::cortex::RpcStreamingContext,
            mut requests: crate::adapter::net::cortex::RequestStream,
            _responses: crate::adapter::net::cortex::RpcResponseSink,
        ) -> Result<(), RpcHandlerError> {
            use futures::StreamExt;
            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            while requests.next().await.is_some() {}
            Ok(())
        }
    }

    /// Poll `get` until it reaches at least `want`, bounded (~2s).
    async fn wait_until_at_least(get: impl Fn() -> u64, want: u64) -> bool {
        for _ in 0..200 {
            if get() >= want {
                return true;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        get() >= want
    }

    /// Gate-3 end-to-end (client-streaming): drive the REAL registered
    /// `serve_rpc_client_stream` bridge with crafted `RpcInboundEvent`s and
    /// assert it rejects BEFORE the fold. A packet/payload origin mismatch and
    /// a relayed flow-controlled REQUEST are dropped (metered; the handler
    /// never runs); a relayed REQUEST without a window header and a directly-
    /// authenticated flow-controlled REQUEST are admitted (the handler runs).
    /// Proves the bridge actually runs the checks BEFORE `apply_inbound` — a
    /// pure helper test could not (it would stay green if a bridge moved the
    /// rejection after the fold or stopped calling it).
    #[tokio::test]
    async fn client_stream_bridge_rejects_before_fold_end_to_end() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let server = build_server().await;
        let ran = std::sync::Arc::new(AtomicUsize::new(0));
        let serve = server
            .serve_rpc_client_stream("cs", std::sync::Arc::new(RanClientStream(ran.clone())))
            .expect("serve client-stream");
        let channel_hash = serve.channel_hash;
        let metrics = server.rpc_metrics_arc().for_service("cs");

        const DIRECT_NODE: u64 = 0x61;
        const RELAY_NODE: u64 = 0x62;
        let direct_entity = EntityKeypair::generate().entity_id().clone();
        let relay_entity = EntityKeypair::generate().entity_id().clone();
        let direct_origin = direct_entity.origin_hash();
        let relay_origin = relay_entity.origin_hash();
        server.test_pin_peer_entity(DIRECT_NODE, direct_entity);
        server.test_pin_peer_entity(RELAY_NODE, relay_entity);
        let victim = relay_origin ^ 0xFFFF_FFFF;

        let event = |from_node: u64,
                     packet_origin: u64,
                     payload_origin: u64,
                     dispatch: u8,
                     call_id: u64,
                     window: Option<&[u8]>| {
            RpcInboundEvent {
                channel_hash,
                origin_hash: packet_origin,
                from_node,
                payload: rpc_request_frame(
                    payload_origin,
                    call_id,
                    dispatch,
                    "cs",
                    FLAG_RPC_CLIENT_STREAMING_REQUEST,
                    window,
                ),
            }
        };

        // A. Packet origin != payload origin (direct node) → dropped in preflight
        //    BEFORE the capability gate, the response-route cache, and the fold.
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(
                DIRECT_NODE,
                direct_origin,
                victim,
                DISPATCH_RPC_REQUEST,
                1,
                Some(b"32")
            )
        ));
        assert!(
            wait_until_at_least(
                || metrics
                    .packet_origin_mismatch_dropped_total
                    .load(Ordering::Relaxed),
                1
            )
            .await,
            "an origin-mismatch frame is dropped and metered",
        );
        // Deterministic, no sleep: the metric bump and the cache write live in
        // the SAME synchronous preflight, so once the counter is visible the
        // frame's drop has returned — the response-route cache was never touched.
        assert_eq!(
            serve.origin_node_cache.get((DIRECT_NODE, direct_origin, 1)),
            None,
            "an origin-mismatch frame must not mutate the response-route cache",
        );

        // B. Relayed (packet == payload == victim; pinned relay origin != victim),
        //    flow-controlled → rejected before the fold. Its route is
        //    untrustworthy, so even on the preflight Proceed path nothing caches.
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(
                RELAY_NODE,
                victim,
                victim,
                DISPATCH_RPC_REQUEST,
                2,
                Some(b"32")
            )
        ));
        assert!(
            wait_until_at_least(
                || metrics
                    .relayed_flow_controlled_rejected_total
                    .load(Ordering::Relaxed),
                1
            )
            .await,
            "a relayed flow-controlled frame is rejected and metered",
        );
        assert_eq!(
            serve.origin_node_cache.get((RELAY_NODE, victim, 2)),
            None,
            "a relayed frame must not mutate the response-route cache",
        );

        // C. Continuation after a rejected initial: a CHUNK for the SAME (call 2)
        //    that was just rejected. The initial never entered the fold, so no
        //    request stream exists; the CHUNK reaches the fold and is a silent
        //    no-op — no handler, no grant/response — and, being a control frame
        //    rather than a flow-controlled initial REQUEST, it must NOT re-count
        //    the per-call rejection counter.
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(
                RELAY_NODE,
                victim,
                victim,
                DISPATCH_RPC_REQUEST_CHUNK,
                2,
                None
            )
        ));

        // D. Relayed but NO window header → admitted (unbounded upload); handler
        //    runs. Reaching `ran >= 1` is the FIFO barrier: this bridge is a
        //    single consumer, so frames A–C (all delivered earlier) are fully
        //    processed by the time D's handler runs.
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(RELAY_NODE, victim, victim, DISPATCH_RPC_REQUEST, 3, None)
        ));
        assert!(
            wait_until_at_least(|| ran.load(Ordering::SeqCst) as u64, 1).await,
            "a relayed non-flow-controlled REQUEST is admitted and the handler runs",
        );
        assert_eq!(
            metrics
                .relayed_flow_controlled_rejected_total
                .load(Ordering::Relaxed),
            1,
            "per-call counter: the continuation CHUNK must not re-count the rejection",
        );

        // E. Direct, flow-controlled → admitted; handler runs (2 total). An
        //    accepted, authenticated direct frame is the positive control: it
        //    DOES cache its response route (proving the None assertions above are
        //    meaningful, not vacuous).
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(
                DIRECT_NODE,
                direct_origin,
                direct_origin,
                DISPATCH_RPC_REQUEST,
                4,
                Some(b"32")
            )
        ));
        assert!(
            wait_until_at_least(|| ran.load(Ordering::SeqCst) as u64, 2).await,
            "a direct flow-controlled REQUEST is admitted and the handler runs",
        );
        assert_eq!(
            serve.origin_node_cache.get((DIRECT_NODE, direct_origin, 4)),
            Some(DIRECT_NODE),
            "an accepted authenticated direct frame DOES cache its response route",
        );

        // Deterministic negatives via the FIFO barrier: `ran == 2` (exactly the
        // two admitted frames) proves the two rejected frames AND the
        // continuation CHUNK never entered the fold — so no active-call state, no
        // grant emission/coalescing, and no direct/roster response publication
        // (all fold-driven) occurred for them.
        assert_eq!(
            ran.load(Ordering::SeqCst),
            2,
            "only the two admitted frames ever ran the handler",
        );
        assert_eq!(
            metrics
                .packet_origin_mismatch_dropped_total
                .load(Ordering::Relaxed),
            1,
        );
        assert_eq!(
            metrics
                .relayed_flow_controlled_rejected_total
                .load(Ordering::Relaxed),
            1,
        );
    }

    /// Gate-3 end-to-end (duplex): the duplex bridge likewise rejects a
    /// packet/payload origin mismatch and a relayed flow-controlled REQUEST
    /// BEFORE the fold, and admits a directly-authenticated flow-controlled
    /// REQUEST.
    #[tokio::test]
    async fn duplex_bridge_rejects_before_fold_end_to_end() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        let server = build_server().await;
        let ran = std::sync::Arc::new(AtomicUsize::new(0));
        let serve = server
            .serve_rpc_duplex("dx", std::sync::Arc::new(RanDuplex(ran.clone())))
            .expect("serve duplex");
        let channel_hash = serve.channel_hash;
        let metrics = server.rpc_metrics_arc().for_service("dx");

        const DIRECT_NODE: u64 = 0x71;
        const RELAY_NODE: u64 = 0x72;
        let direct_entity = EntityKeypair::generate().entity_id().clone();
        let relay_entity = EntityKeypair::generate().entity_id().clone();
        let direct_origin = direct_entity.origin_hash();
        let relay_origin = relay_entity.origin_hash();
        server.test_pin_peer_entity(DIRECT_NODE, direct_entity);
        server.test_pin_peer_entity(RELAY_NODE, relay_entity);
        let victim = relay_origin ^ 0xFFFF_FFFF;
        let dx_flags = FLAG_RPC_CLIENT_STREAMING_REQUEST | FLAG_RPC_STREAMING_RESPONSE;

        let event = |from_node: u64,
                     packet_origin: u64,
                     payload_origin: u64,
                     dispatch: u8,
                     call_id: u64,
                     window: Option<&[u8]>| {
            RpcInboundEvent {
                channel_hash,
                origin_hash: packet_origin,
                from_node,
                payload: rpc_request_frame(
                    payload_origin,
                    call_id,
                    dispatch,
                    "dx",
                    dx_flags,
                    window,
                ),
            }
        };

        // A. Origin mismatch → dropped in preflight; the response-route cache is
        //    never touched (metric bump + non-write share one synchronous call).
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(
                DIRECT_NODE,
                direct_origin,
                victim,
                DISPATCH_RPC_REQUEST,
                1,
                Some(b"32")
            )
        ));
        assert!(
            wait_until_at_least(
                || metrics
                    .packet_origin_mismatch_dropped_total
                    .load(Ordering::Relaxed),
                1
            )
            .await,
            "an origin-mismatch frame is dropped and metered on the duplex bridge",
        );
        assert_eq!(
            serve.origin_node_cache.get((DIRECT_NODE, direct_origin, 1)),
            None,
            "an origin-mismatch frame must not mutate the response-route cache",
        );

        // B. Relayed flow-controlled → rejected before the fold; nothing caches.
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(
                RELAY_NODE,
                victim,
                victim,
                DISPATCH_RPC_REQUEST,
                2,
                Some(b"32")
            )
        ));
        assert!(
            wait_until_at_least(
                || metrics
                    .relayed_flow_controlled_rejected_total
                    .load(Ordering::Relaxed),
                1
            )
            .await,
            "a relayed flow-controlled frame is rejected and metered on the duplex bridge",
        );
        assert_eq!(
            serve.origin_node_cache.get((RELAY_NODE, victim, 2)),
            None,
            "a relayed frame must not mutate the response-route cache",
        );

        // C. Continuation after the rejected initial: a CHUNK for the SAME call 2.
        //    No stream was opened, so it is a fold no-op; being a control frame it
        //    must not re-count the per-call rejection.
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(
                RELAY_NODE,
                victim,
                victim,
                DISPATCH_RPC_REQUEST_CHUNK,
                2,
                None
            )
        ));

        // D. Direct flow-controlled → admitted; handler runs. `ran >= 1` is the
        //    FIFO barrier proving frames A–C were fully processed. The accepted
        //    frame is the positive cache control.
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            event(
                DIRECT_NODE,
                direct_origin,
                direct_origin,
                DISPATCH_RPC_REQUEST,
                3,
                Some(b"32")
            )
        ));
        assert!(
            wait_until_at_least(|| ran.load(Ordering::SeqCst) as u64, 1).await,
            "a direct flow-controlled duplex REQUEST is admitted and the handler runs",
        );
        assert_eq!(
            serve.origin_node_cache.get((DIRECT_NODE, direct_origin, 3)),
            Some(DIRECT_NODE),
            "an accepted authenticated direct frame DOES cache its response route",
        );

        // FIFO barrier: exactly the one admitted frame ran the handler — the two
        // rejected frames and the continuation CHUNK never entered the fold, so
        // no state / grant / publication occurred for them; counters stay per-call.
        assert_eq!(
            ran.load(Ordering::SeqCst),
            1,
            "only the one admitted frame ran the duplex handler",
        );
        assert_eq!(
            metrics
                .packet_origin_mismatch_dropped_total
                .load(Ordering::Relaxed),
            1,
        );
        assert_eq!(
            metrics
                .relayed_flow_controlled_rejected_total
                .load(Ordering::Relaxed),
            1,
        );
    }

    async fn build_server() -> Arc<MeshNode> {
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let cfg = MeshNodeConfig::new(addr, [0x42u8; 32])
            .with_heartbeat_interval(Duration::from_millis(200))
            .with_session_timeout(Duration::from_secs(10))
            .with_handshake(3, Duration::from_secs(2));
        Arc::new(
            MeshNode::new(EntityKeypair::generate(), cfg)
                .await
                .expect("MeshNode::new"),
        )
    }

    /// A provider `MeshNode` owned by org B with an installed authority, for the
    /// protected-admission witnesses. Returns (server, node entity P, org B, a
    /// scratch dir the caller removes at the end).
    async fn protected_provider(
        tag: &str,
    ) -> (
        Arc<MeshNode>,
        crate::adapter::net::identity::EntityId,
        crate::adapter::net::behavior::org::OrgKeypair,
        std::path::PathBuf,
    ) {
        use crate::adapter::net::behavior::org::{OrgKeypair, OrgMembershipCert};
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        // The directory is deliberately LEFT BEHIND when the test finishes, and
        // that is not an oversight. It holds the authority's revocation
        // `.lock` sidecar, and `OrgRevocationStore` keys its PROCESS-GLOBAL
        // core registry by that sidecar's `(device, inode)` so two path
        // aliases of one sidecar share one live view (AV-9). Deleting it frees
        // the inode while this node's core is still registered; Linux recycles
        // a freed inode immediately, so the NEXT store opened anywhere in this
        // test binary can land on it, derive the same `BackingId`, and join
        // THIS test's core — reading its floors, its poison bit and its
        // generation, and writing to a path that no longer exists.
        //
        // The victims are whichever tests are scheduled next, so it surfaces
        // as unrelated failures in varying combinations rather than as one
        // deterministic break. Only the deletion at the START of the helper
        // remains, and it can free nothing: the path is per-test.
        let dir = std::env::temp_dir().join(format!("net-oa2-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");
        (server, node_entity, org_b, dir)
    }

    /// An owner-delegated proof intent for `caller_kp` acting in org B, targeting
    /// `provider` on `nrpc:svc`.
    fn owner_delegated_intent(
        caller_kp: EntityKeypair,
        org_b: &crate::adapter::net::behavior::org::OrgKeypair,
        provider: crate::adapter::net::identity::EntityId,
    ) -> OrgProofIntent {
        use crate::adapter::net::behavior::org::OrgMembershipCert;
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, OrgDispatcherGrant,
        };
        let caller_entity = caller_kp.entity_id().clone();
        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let membership =
            OrgMembershipCert::try_issue(org_b, caller_entity.clone(), 1, 3600).expect("cert");
        let dispatcher =
            OrgDispatcherGrant::try_issue(org_b, caller_entity, DispatcherScope::Exact(cap), 3600)
                .expect("dispatcher");
        OrgProofIntent {
            caller: std::sync::Arc::new(caller_kp),
            membership,
            dispatcher,
            capability_grant: None,
            acting_org: org_b.org_id(),
            provider_owner_org: org_b.org_id(),
            provider,
            capability: cap,
            proof_ttl_secs: 30,
        }
    }

    /// Kyra #47 B2: the admission replay guard is NODE-owned. A proof admitted
    /// under one registration is a REPLAY after that service is torn down and
    /// re-registered — the guard is not per-registration. A fresh proof still
    /// admits (FIFO barrier: exactly one admit on the second registration).
    #[tokio::test]
    async fn admission_replay_guard_is_node_owned_across_reregistration() {
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct Counter(std::sync::Arc<AtomicUsize>);
        #[async_trait::async_trait]
        impl RpcHandler for Counter {
            async fn call(&self, _ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                self.0.fetch_add(1, Ordering::SeqCst);
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let (server, node_entity, org_b, _dir) = protected_provider("b2").await;
        const CALLER_NODE: u64 = 0x9b;
        let caller_kp = EntityKeypair::generate();
        let caller_origin = caller_kp.entity_id().origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_kp.entity_id().clone());
        let intent = owner_delegated_intent(caller_kp, &org_b, node_entity);

        let base = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        // Sign ONE proof (call_id 1) — the exact bytes are replayed later.
        let header1 = sign_admission_proof(&intent, 1, &base).expect("sign");
        let make = |header: &(String, Vec<u8>), call_id: u64, channel_hash: ChannelHash| {
            let mut req = base.clone();
            req.headers.push(header.clone());
            let mut f = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
                .to_bytes()
                .to_vec();
            encode_rpc_route(&mut f, 0);
            f.extend_from_slice(&req.encode());
            RpcInboundEvent {
                channel_hash,
                origin_hash: caller_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(f),
            }
        };

        // Registration #1: admit the proof.
        let admits1 = std::sync::Arc::new(AtomicUsize::new(0));
        let serve1 = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(Counter(admits1.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve #1");
        let channel_hash = serve1.channel_hash;
        assert!(server.deliver_rpc_inbound_for_test(channel_hash, make(&header1, 1, channel_hash)));
        assert!(
            wait_until_at_least(|| admits1.load(Ordering::SeqCst) as u64, 1).await,
            "the first call admits",
        );
        drop(serve1); // unregister

        // Registration #2 (same service): the SAME proof is a replay; a fresh
        // proof still admits.
        let admits2 = std::sync::Arc::new(AtomicUsize::new(0));
        let serve2 = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(Counter(admits2.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve #2");
        let ch2 = serve2.channel_hash;
        assert!(server.deliver_rpc_inbound_for_test(ch2, make(&header1, 1, ch2))); // replay
        let header2 = sign_admission_proof(&intent, 2, &base).expect("sign fresh");
        assert!(server.deliver_rpc_inbound_for_test(ch2, make(&header2, 2, ch2))); // fresh
        assert!(
            wait_until_at_least(|| admits2.load(Ordering::SeqCst) as u64, 1).await,
            "the fresh call admits on the second registration",
        );
        assert_eq!(
            admits2.load(Ordering::SeqCst),
            1,
            "the replayed proof was DENIED across re-registration (node-owned guard)",
        );
    }

    /// Kyra #47 B2 (cross-service): the node-owned replay guard keys on
    /// `(caller, call_id)` NODE-WIDE, not per service. A `(caller, call_id)`
    /// admitted under protected service A cannot be reused under a DIFFERENT
    /// protected service B — the second presentation (a fresh proof over B's
    /// request, hence a different binding digest) is a `CallIdCollision` and is
    /// DENIED. A fresh `call_id` on B still admits, proving B's path is live and
    /// only the reused id was blocked.
    #[tokio::test]
    async fn admission_replay_guard_collides_across_services() {
        use crate::adapter::net::behavior::org::OrgMembershipCert;
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, OrgDispatcherGrant,
        };
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct Counter(std::sync::Arc<AtomicUsize>);
        #[async_trait::async_trait]
        impl RpcHandler for Counter {
            async fn call(&self, _ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                self.0.fetch_add(1, Ordering::SeqCst);
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let (server, node_entity, org_b, _dir) = protected_provider("b2-xsvc").await;
        const CALLER_NODE: u64 = 0x9c;
        let caller_kp = std::sync::Arc::new(EntityKeypair::generate());
        let caller_origin = caller_kp.entity_id().origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_kp.entity_id().clone());

        // One intent per service for the SAME caller — capability `nrpc:<svc>`.
        let intent_for = |service: &str| -> OrgProofIntent {
            let caller_entity = caller_kp.entity_id().clone();
            let cap = CapabilityAuthorityId::for_tag(&format!("nrpc:{service}"));
            let membership =
                OrgMembershipCert::try_issue(&org_b, caller_entity.clone(), 1, 3600).expect("cert");
            let dispatcher = OrgDispatcherGrant::try_issue(
                &org_b,
                caller_entity,
                DispatcherScope::Exact(cap),
                3600,
            )
            .expect("dispatcher");
            OrgProofIntent {
                caller: caller_kp.clone(),
                membership,
                dispatcher,
                capability_grant: None,
                acting_org: org_b.org_id(),
                provider_owner_org: org_b.org_id(),
                provider: node_entity.clone(),
                capability: cap,
                proof_ttl_secs: 30,
            }
        };
        let req_for = |service: &str| RpcRequestPayload {
            service: service.to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        let make = |base: &RpcRequestPayload,
                    header: &(String, Vec<u8>),
                    call_id: u64,
                    channel_hash: ChannelHash| {
            let mut req = base.clone();
            req.headers.push(header.clone());
            let mut f = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
                .to_bytes()
                .to_vec();
            encode_rpc_route(&mut f, 0);
            f.extend_from_slice(&req.encode());
            RpcInboundEvent {
                channel_hash,
                origin_hash: caller_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(f),
            }
        };

        // Two protected services on the SAME node — both self-index their
        // `nrpc:<svc>` capability so the provider self-check (E1.2) passes.
        let admits_a = std::sync::Arc::new(AtomicUsize::new(0));
        let admits_b = std::sync::Arc::new(AtomicUsize::new(0));
        // Count service B's PROVIDER-POLICY invocations. The policy runs
        // SYNCHRONOUSLY in the admission transaction, AFTER the replay insert and
        // BEFORE fold/handler dispatch — so it is a deterministic signal that
        // does NOT depend on handler (`tokio::spawn`) scheduling order (Kyra #47
        // final): a call denied at the replay insert never reaches the policy.
        let policy_calls_b = std::sync::Arc::new(AtomicUsize::new(0));
        let serve_a = server
            .serve_rpc_protected(
                "a",
                std::sync::Arc::new(Counter(admits_a.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve a");
        let serve_b = server
            .serve_rpc_protected(
                "b",
                std::sync::Arc::new(Counter(admits_b.clone())),
                OrgAdmission::OwnerDelegated,
                {
                    let policy_calls_b = policy_calls_b.clone();
                    std::sync::Arc::new(move |_: &_| {
                        policy_calls_b.fetch_add(1, Ordering::SeqCst);
                        true
                    })
                },
            )
            .expect("serve b");
        let ch_a = serve_a.channel_hash;
        let ch_b = serve_b.channel_hash;

        // Admit (caller, call_id=7) under service A; wait so the replay slot is
        // recorded before B is probed.
        let intent_a = intent_for("a");
        let req_a = req_for("a");
        let header_a7 = sign_admission_proof(&intent_a, 7, &req_a).expect("sign a7");
        assert!(server.deliver_rpc_inbound_for_test(ch_a, make(&req_a, &header_a7, 7, ch_a)));
        assert!(
            wait_until_at_least(|| admits_a.load(Ordering::SeqCst) as u64, 1).await,
            "service A admits (caller, call_id=7)",
        );

        // Reuse call_id 7 under service B (fresh proof over B's request → a
        // DIFFERENT binding digest → `CallIdCollision`), then a FRESH call_id 8
        // under B. Same-channel FIFO: the fresh admit implies the collision was
        // already processed, so `admits_b == 1` proves the reuse was denied.
        let intent_b = intent_for("b");
        let req_b = req_for("b");
        let header_b7 = sign_admission_proof(&intent_b, 7, &req_b).expect("sign b7");
        let header_b8 = sign_admission_proof(&intent_b, 8, &req_b).expect("sign b8");
        assert!(server.deliver_rpc_inbound_for_test(ch_b, make(&req_b, &header_b7, 7, ch_b)));
        assert!(server.deliver_rpc_inbound_for_test(ch_b, make(&req_b, &header_b8, 8, ch_b)));
        assert!(
            wait_until_at_least(|| admits_b.load(Ordering::SeqCst) as u64, 1).await,
            "service B admits the fresh call_id 8",
        );
        // DETERMINISTIC check (not handler-count-race dependent): only the fresh
        // call_id 8 reached B's policy. The reused call_id 7 was denied at the
        // replay insert — BEFORE the policy — so it never incremented this
        // counter. Were the collision incorrectly admitted, the count would be 2.
        assert_eq!(
            policy_calls_b.load(Ordering::SeqCst),
            1,
            "only the fresh call reached service B's policy — the reused call_id 7 was denied at \
             the replay insert (node-wide (caller, call_id) collision)",
        );
        assert_eq!(
            admits_b.load(Ordering::SeqCst),
            1,
            "service B's handler ran exactly once (only the fresh call)",
        );

        drop(serve_a);
        drop(serve_b);
    }

    /// Kyra #47 mixed-version: `strip_public_admission_header` removes ONLY the
    /// org-admission proof header (retaining any other header) and is a true
    /// no-op — `None` — for a request that carries none (the hot-path common
    /// case, where the byte prefilter skips without any decode).
    #[test]
    fn public_admission_strip_removes_only_the_proof_header() {
        let frame = |dispatch: u8, headers: Vec<(String, Vec<u8>)>| -> RpcInboundEvent {
            let req = RpcRequestPayload {
                service: "svc".to_string(),
                deadline_ns: 0,
                flags: 0,
                headers,
                body: Bytes::from_static(b"ping"),
            };
            let mut f = EventMeta::new(dispatch, 0, 0, 1, 0).to_bytes().to_vec();
            encode_rpc_route(&mut f, 0);
            f.extend_from_slice(&req.encode());
            RpcInboundEvent {
                channel_hash: 0,
                origin_hash: 0,
                from_node: 1,
                payload: Bytes::from(f),
            }
        };

        // No proof header → no rewrite (definitive skip via the byte prefilter).
        assert!(
            strip_public_admission_header(&frame(
                DISPATCH_RPC_REQUEST,
                vec![("keep".to_string(), b"v".to_vec())]
            ))
            .is_none(),
            "a request with no proof header is a no-op",
        );

        // A non-REQUEST (CANCEL) frame is left untouched even if the header
        // bytes appear — the REQUEST-only guard short-circuits first.
        assert!(
            strip_public_admission_header(&frame(
                DISPATCH_RPC_CANCEL,
                vec![(ORG_ADMISSION_HEADER.to_string(), b"proofbytes".to_vec())]
            ))
            .is_none(),
            "a non-REQUEST frame is never rewritten",
        );

        // Proof header present → rewritten without it; unrelated headers kept.
        let with_proof = frame(
            DISPATCH_RPC_REQUEST,
            vec![
                ("keep".to_string(), b"v".to_vec()),
                (ORG_ADMISSION_HEADER.to_string(), b"proofbytes".to_vec()),
            ],
        );
        let stripped = strip_public_admission_header(&with_proof)
            .expect("rewrites when the proof header is present");
        let req = RpcRequestPayload::decode(stripped.payload.slice(RPC_FRAME_BODY_OFFSET..))
            .expect("decode rewritten request");
        assert!(
            !req.headers.iter().any(|(n, _)| n == ORG_ADMISSION_HEADER),
            "the proof header was removed",
        );
        assert!(
            req.headers.iter().any(|(n, _)| n == "keep"),
            "an unrelated header was retained",
        );
    }

    /// §8 — the E1.6 strip is applied by the SHARED preflight, so every serve
    /// bridge gets it.
    ///
    /// It used to run at the unary bridge's single fold call site. The three
    /// streaming bridges (`serve_rpc_streaming`, `serve_rpc_client_stream`,
    /// `serve_rpc_duplex`) call this same preflight and then
    /// `fold.lock().apply_inbound(&inbound)` directly, so they never stripped
    /// at all — a caller who hand-stuffed `net-org-admission` into
    /// `CallOptions.request_headers` and issued a streaming call handed the
    /// public handler org-admission credential material verbatim, which E1.6
    /// states must never happen.
    ///
    /// Asserted on `bridge_preflight` rather than through four live bridges
    /// because the preflight is now the ONLY source of a foldable frame:
    /// `BridgePreflight::Proceed` carries it by value, so a bridge physically
    /// cannot fold anything else. Covering this seam covers all four, and the
    /// compiler enforces the rest.
    ///
    /// Red-witness: returning `inbound.clone()` from the preflight instead of
    /// the strip result fails the first assertion.
    #[tokio::test]
    async fn bridge_preflight_strips_a_stray_proof_header_for_every_bridge() {
        let server = build_server().await;
        let cache: RpcOriginNodeCache = Arc::new(BoundedLru::new());
        let metrics = server.rpc_metrics_arc().for_service("svc");

        let req = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![
                ("keep".to_string(), b"v".to_vec()),
                (ORG_ADMISSION_HEADER.to_string(), b"proofbytes".to_vec()),
            ],
            body: Bytes::from_static(b"ping"),
        };
        let mut payload = EventMeta::new(DISPATCH_RPC_REQUEST, 0, 0, 1, 0)
            .to_bytes()
            .to_vec();
        encode_rpc_route(&mut payload, 0);
        payload.extend_from_slice(&req.encode());
        // `from_node == 0` is the loopback/local exemption, so the origin bind
        // and the capability gate both pass — this test is about the strip.
        let inbound = RpcInboundEvent {
            channel_hash: 0,
            origin_hash: 0,
            from_node: 0,
            payload: Bytes::from(payload),
        };

        match bridge_preflight(&server, &cache, &inbound, "svc", "nrpc:svc", &metrics) {
            BridgePreflight::Proceed(frame) => {
                let decoded =
                    RpcRequestPayload::decode(frame.payload.slice(RPC_FRAME_BODY_OFFSET..))
                        .expect("decode the frame the bridge would fold");
                assert!(
                    !decoded
                        .headers
                        .iter()
                        .any(|(n, _)| n == ORG_ADMISSION_HEADER),
                    "the frame handed to EVERY bridge must carry no proof header",
                );
                assert!(
                    decoded.headers.iter().any(|(n, _)| n == "keep"),
                    "an unrelated header must survive",
                );
                assert_eq!(decoded.body.as_ref(), b"ping", "the body is untouched");
            }
            _ => panic!("expected Proceed for a loopback frame on the captured service"),
        }

        // A frame with no proof header still proceeds, unmodified.
        let clean = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![("keep".to_string(), b"v".to_vec())],
            body: Bytes::from_static(b"ping"),
        };
        let mut payload = EventMeta::new(DISPATCH_RPC_REQUEST, 0, 0, 2, 0)
            .to_bytes()
            .to_vec();
        encode_rpc_route(&mut payload, 0);
        payload.extend_from_slice(&clean.encode());
        let inbound = RpcInboundEvent {
            channel_hash: 0,
            origin_hash: 0,
            from_node: 0,
            payload: Bytes::from(payload),
        };
        match bridge_preflight(&server, &cache, &inbound, "svc", "nrpc:svc", &metrics) {
            BridgePreflight::Proceed(frame) => assert_eq!(
                frame.payload, inbound.payload,
                "a frame with no proof header is passed through byte-for-byte",
            ),
            _ => panic!("expected Proceed"),
        }
    }

    /// Kyra #47 B3: a protected `call` finalizes ATOMICALLY and validates the
    /// final wire BEFORE registering the pending oneshot. A caller-supplied
    /// admission header and an over-cap finalized request each fail LOCALLY (no
    /// panic, no send), and NEITHER leaks a pending entry (register happens only
    /// after construction succeeds).
    #[tokio::test]
    async fn protected_call_finalization_is_atomic_bounded_and_leak_free() {
        use crate::adapter::net::behavior::org::OrgKeypair;
        use crate::adapter::net::cortex::MAX_RPC_HEADERS;
        const TARGET: u64 = 0xDEAD_BEEF;

        let server = build_server().await;
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let provider = crate::adapter::net::identity::EntityId::from_bytes([0x99u8; 32]);
        // Pin the target to the proof's bound provider so the binding check
        // passes and the dup-header / over-cap paths below are genuinely reached
        // (Kyra #47 tail — provider binding precedes finalization).
        server.test_pin_peer_entity(TARGET, provider.clone());
        let pending = server.rpc_client_pending();
        assert_eq!(pending.pending_count(), 0);

        // (1) caller-supplied admission header → local error; no pending leak.
        let dup = CallOptions {
            org_proof_intent: Some(owner_delegated_intent(
                EntityKeypair::generate(),
                &org_b,
                provider.clone(),
            )),
            request_headers: vec![("net-org-admission".to_string(), b"forged".to_vec())],
            ..Default::default()
        };
        assert!(
            matches!(
                server
                    .call(TARGET, "svc", Bytes::from_static(b"ping"), dup)
                    .await,
                Err(RpcError::Codec { .. })
            ),
            "a caller-supplied admission header must fail locally",
        );
        assert_eq!(
            pending.pending_count(),
            0,
            "the dup-header failure must not leak a pending entry",
        );

        // (2) MAX_RPC_HEADERS ordinary headers + the proof header = over cap →
        // final-bounds error (no debug panic / release truncation); no leak.
        let over = CallOptions {
            org_proof_intent: Some(owner_delegated_intent(
                EntityKeypair::generate(),
                &org_b,
                provider,
            )),
            request_headers: (0..MAX_RPC_HEADERS)
                .map(|i| (format!("h{i}"), b"v".to_vec()))
                .collect(),
            ..Default::default()
        };
        assert!(
            matches!(
                server
                    .call(TARGET, "svc", Bytes::from_static(b"ping"), over)
                    .await,
                Err(RpcError::Codec { .. })
            ),
            "an over-cap finalized request must fail locally",
        );
        assert_eq!(
            pending.pending_count(),
            0,
            "the over-cap failure must not leak a pending entry",
        );
    }

    /// Kyra #47 tail (caller/API): a proof intent is REFUSED on every streaming
    /// call shape (org admission is unary-only, E1.8 — never silently ignored),
    /// and an intent whose capability does not match the invoked service fails
    /// LOCALLY (before it can reach a provider as a CapabilityMismatch denial).
    #[tokio::test]
    async fn org_proof_intent_rejected_on_streaming_and_capability_mismatch() {
        use crate::adapter::net::behavior::org::OrgKeypair;
        const TARGET: u64 = 0xDEAD_BEEF;
        let server = build_server().await;
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let provider = crate::adapter::net::identity::EntityId::from_bytes([0x99u8; 32]);
        // Pin the target to the proof's bound provider so the unary
        // capability-mismatch path is reached (provider binding is checked
        // first, before the capability match).
        server.test_pin_peer_entity(TARGET, provider.clone());
        let intent_opts = || CallOptions {
            org_proof_intent: Some(owner_delegated_intent(
                EntityKeypair::generate(),
                &org_b,
                provider.clone(),
            )),
            ..Default::default()
        };

        // Streaming shapes refuse a proof intent up front.
        assert!(matches!(
            server
                .call_streaming(TARGET, "svc", Bytes::new(), intent_opts())
                .await,
            Err(RpcError::Codec { .. })
        ));
        assert!(matches!(
            server
                .call_client_stream(TARGET, "svc", intent_opts())
                .await,
            Err(RpcError::Codec { .. })
        ));
        assert!(matches!(
            server.call_duplex(TARGET, "svc", intent_opts()).await,
            Err(RpcError::Codec { .. })
        ));
        // Service-routed streaming rejects the intent at the TOP, before
        // discovery: with NO service advertised, empty discovery would yield
        // `NoRoute` — a `Codec` proves the unary-only guard fired first and
        // routing state was never touched.
        assert!(matches!(
            server
                .call_service_streaming("svc", Bytes::new(), intent_opts())
                .await,
            Err(RpcError::Codec { .. })
        ));

        // The intent's capability is `nrpc:svc`; invoking a DIFFERENT service is
        // a local capability mismatch.
        assert!(matches!(
            server
                .call(TARGET, "other", Bytes::from_static(b"x"), intent_opts())
                .await,
            Err(RpcError::Codec { .. })
        ));
    }

    /// Kyra #47 tail (caller/API): the requested proof TTL must be an honest,
    /// finite lifetime within the SHARED `org_call::MAX_ORG_PROOF_TTL_SECS`
    /// ceiling (30 s) the provider enforces at verify time — the caller fails
    /// LOCALLY rather than silently clamping. `0` is rejected (a proof that
    /// expires within the same whole second is only admissible inside provider
    /// skew tolerance, not a usable credential); the exact ceiling admits; one
    /// past it is rejected, NOT clamped down to the ceiling.
    #[test]
    fn org_proof_ttl_out_of_range_fails_locally() {
        use crate::adapter::net::behavior::org::OrgKeypair;
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let provider = crate::adapter::net::identity::EntityId::from_bytes([0x99u8; 32]);
        let base = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        let intent_with = |ttl: u64| {
            let mut i = owner_delegated_intent(EntityKeypair::generate(), &org_b, provider.clone());
            i.proof_ttl_secs = ttl;
            i
        };
        // 0 → rejected: only "live" inside the provider's skew tolerance.
        assert!(matches!(
            sign_admission_proof(&intent_with(0), 1, &base),
            Err(RpcError::Codec { .. })
        ));
        // Exactly the shared ceiling → admitted.
        assert!(sign_admission_proof(&intent_with(MAX_ORG_PROOF_TTL_SECS), 2, &base).is_ok());
        // One past the ceiling → rejected, NOT clamped to the ceiling.
        assert!(matches!(
            sign_admission_proof(&intent_with(MAX_ORG_PROOF_TTL_SECS + 1), 3, &base),
            Err(RpcError::Codec { .. })
        ));
    }

    /// Kyra #47 tail (caller/API): a protected `call` refuses to publish a proof
    /// to a transport target that is not the EXACT provider the proof binds. An
    /// UNPINNED target (we cannot prove it is P) and a target pinned to a
    /// DIFFERENT entity each fail LOCALLY — no proof leaves the node — and leak
    /// no pending entry (the binding check precedes registration).
    #[tokio::test]
    async fn protected_call_refuses_provider_target_mismatch() {
        use crate::adapter::net::behavior::org::OrgKeypair;
        const TARGET: u64 = 0xDEAD_BEEF;
        let server = build_server().await;
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let provider = crate::adapter::net::identity::EntityId::from_bytes([0x99u8; 32]);
        let other = crate::adapter::net::identity::EntityId::from_bytes([0x11u8; 32]);
        let pending = server.rpc_client_pending();
        let opts = || CallOptions {
            org_proof_intent: Some(owner_delegated_intent(
                EntityKeypair::generate(),
                &org_b,
                provider.clone(),
            )),
            ..Default::default()
        };

        // Unpinned target: cannot prove it is the bound provider → local error.
        assert!(matches!(
            server
                .call(TARGET, "svc", Bytes::from_static(b"x"), opts())
                .await,
            Err(RpcError::Codec { .. })
        ));
        assert_eq!(
            pending.pending_count(),
            0,
            "no pending leak on unpinned target"
        );

        // Target pinned to a DIFFERENT entity → mismatch, local error, no leak.
        server.test_pin_peer_entity(TARGET, other);
        assert!(matches!(
            server
                .call(TARGET, "svc", Bytes::from_static(b"x"), opts())
                .await,
            Err(RpcError::Codec { .. })
        ));
        assert_eq!(
            pending.pending_count(),
            0,
            "no pending leak on provider mismatch"
        );
    }

    /// E1.1: `serve_rpc_protected` refuses up front — a `PublicAuthenticated`
    /// mode is not org-protected, and an org-protected mode with NO installed
    /// node authority could never admit — so both fail cleanly (no dangling
    /// registration) rather than serving a service that denies every call. A
    /// public `serve_rpc` on the same name then still succeeds, proving nothing
    /// was left behind.
    #[tokio::test]
    async fn serve_rpc_protected_refuses_bad_mode_and_missing_authority() {
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        struct H;
        #[async_trait::async_trait]
        impl RpcHandler for H {
            async fn call(&self, _ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }
        let server = build_server().await; // no authority installed
        let policy: OrgProviderPolicy = std::sync::Arc::new(|_| true);

        // PublicAuthenticated is rejected before the authority check.
        assert!(
            matches!(
                server.serve_rpc_protected(
                    "p",
                    std::sync::Arc::new(H),
                    OrgAdmission::PublicAuthenticated,
                    policy.clone(),
                ),
                Err(ServeError::InvalidProtectedRegistration(_))
            ),
            "PublicAuthenticated is not a protected mode",
        );

        // A valid org-protected mode still fails with no installed authority.
        assert!(
            matches!(
                server.serve_rpc_protected(
                    "p",
                    std::sync::Arc::new(H),
                    OrgAdmission::CrossOrgGranted,
                    policy,
                ),
                Err(ServeError::ProtectedAuthorityRequired(_))
            ),
            "protected registration requires an installed authority",
        );

        // Neither refusal left a registration behind — the slot is free.
        assert!(
            server.serve_rpc("p", std::sync::Arc::new(H)).is_ok(),
            "no dangling protected registration blocks the slot",
        );
    }

    /// §1 regression: EVERY org-protected registration mode routes its
    /// responses [`ResponseRouteFallback::DirectOnly`]; only the legacy public
    /// mode keeps the AV-5 roster fallback.
    ///
    /// This is the exact mutation that reintroduces the defect: the unary
    /// response drainer previously passed a hardcoded
    /// `ResponseRouteFallback::RosterOnStaleDirect` for every mode, so a
    /// route-cache eviction (past `RPC_CALLER_CACHE_CAP` concurrent calls) or a
    /// `NoSession` at send time fanned an org-confidential `CrossOrgGranted`
    /// response onto `<service>.replies.<caller_origin>` — a channel the SDK
    /// auto-registers default-permissive and that `authorize_subscribe` lets
    /// ANY peer subscribe to.
    ///
    /// Asserted against the mode enum rather than through a live two-node call
    /// deliberately: the leak triggers only on a cache MISS, and a passing
    /// end-to-end call always populates the cache on the accept path — so an
    /// integration test over the happy path exercises the direct leg and
    /// witnesses nothing, passing identically with the defect present.
    ///
    /// The full property is witnessed in two halves, and this is the first:
    ///
    /// 1. **mode → policy** (here): every protected mode resolves to
    ///    `DirectOnly`.
    /// 2. **policy → behavior**:
    ///    [`direct_only_frame_drops_while_normal_response_rosters_when_peer_gone`]
    ///    proves the divergence on identical input over a gone peer —
    ///    `DirectOnly` drops, `RosterOnStaleDirect` reaches the roster.
    ///
    /// The remaining link — the response drainer passing *this* function's
    /// result rather than a literal — is held by construction rather than by
    /// test: `serve_rpc_unary_impl` derives `response_fallback` once from
    /// `mode` before consuming it, and the drainer has no other
    /// `ResponseRouteFallback` in scope. Re-introducing the defect requires
    /// deliberately replacing that variable with a literal.
    #[test]
    fn protected_registrations_never_roster_fan_responses() {
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        let policy: OrgProviderPolicy = std::sync::Arc::new(|_| true);

        // Legacy public keeps the roster fallback (AV-5): an honest caller that
        // reconnected under a new NodeId is still reachable via its signed
        // roster subscription, and a public response body is not confidential.
        assert_eq!(
            UnaryAdmission::Public.response_route_fallback(),
            ResponseRouteFallback::RosterOnStaleDirect,
            "public services keep the AV-5 roster fallback",
        );

        // Every protected mode is direct-only.
        for (label, mode) in [
            (
                "Protected/OwnerDelegated",
                UnaryAdmission::Protected {
                    admission: OrgAdmission::OwnerDelegated,
                    provider_policy: policy.clone(),
                },
            ),
            (
                "Protected/CrossOrgGranted",
                UnaryAdmission::Protected {
                    admission: OrgAdmission::CrossOrgGranted,
                    provider_policy: policy.clone(),
                },
            ),
            (
                "OwnerScoped",
                UnaryAdmission::OwnerScoped {
                    provider_policy: policy.clone(),
                },
            ),
            (
                "Granted",
                UnaryAdmission::Granted {
                    provider_policy: policy.clone(),
                },
            ),
            (
                "ProtectedRedWitnessDisabled",
                UnaryAdmission::ProtectedRedWitnessDisabled {
                    admission: OrgAdmission::OwnerDelegated,
                    provider_policy: policy.clone(),
                },
            ),
        ] {
            assert_eq!(
                mode.response_route_fallback(),
                ResponseRouteFallback::DirectOnly,
                "{label} must never roster-fan an org-confidential response",
            );
        }
    }

    /// E1 witness 10/11 (owner-delegated), end-to-end through the LIVE gate:
    /// a provider with an installed authority (owner org B) serves a protected
    /// service; a caller ∈ B presents a valid `net-org-admission` proof; the
    /// gate admits and the handler runs with the four-party `Admitted`
    /// attribution in `RpcContext::org_admission` (proof header stripped). This
    /// exercises serve_rpc_protected → admit_and_dispatch_protected →
    /// verify_provider_authority → verify_org_admission → apply_inbound_admitted.
    #[tokio::test]
    async fn protected_owner_delegated_call_admits_end_to_end() {
        use crate::adapter::net::behavior::org::{
            current_timestamp, OrgKeypair, OrgMembershipCert,
        };
        use crate::adapter::net::behavior::org_admission::{Admitted, OrgAdmission};
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_call::{OrgCallProof, ORG_ADMISSION_HEADER};
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, OrgDispatcherGrant,
        };
        use crate::adapter::net::org_admission_gate::org_request_digest;

        type Seen = std::sync::Arc<Mutex<Option<Admitted>>>;
        struct SpyHandler(Seen);
        #[async_trait::async_trait]
        impl RpcHandler for SpyHandler {
            async fn call(&self, ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                *self.0.lock() = Some(ctx.org_admission.clone().expect("admitted call"));
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        // The node is a member of its OWNER org B; adopt + install its authority.
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa2-wire-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        let seen: Seen = std::sync::Arc::new(Mutex::new(None));
        let serve = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(SpyHandler(seen.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve protected");
        let channel_hash = serve.channel_hash;

        // A caller ∈ org B (owner-delegated), pinned to its session node.
        const CALLER_NODE: u64 = 0x91;
        let caller_kp = EntityKeypair::generate();
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let call_id = 7u64;
        // Digest is computed over the request WITHOUT the proof header (the gate
        // strips it before hashing), so sign over the bare request then attach.
        let base = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        let digest = org_request_digest(&base).expect("digest");
        let membership = OrgMembershipCert::try_issue(&org_b, caller_entity.clone(), 1, 3600)
            .expect("caller cert");
        let dispatcher = OrgDispatcherGrant::try_issue(
            &org_b,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher grant");
        let expiry = (current_timestamp() + 20) * 1_000_000_000;
        let proof = OrgCallProof::sign_for_call(
            &caller_kp,
            membership,
            dispatcher,
            None,
            org_b.org_id(),
            org_b.org_id(),
            node_entity.clone(),
            call_id,
            cap,
            expiry,
            digest,
        );
        let proof_bytes = proof.encode().expect("encode proof");

        let mut payload = base.clone();
        payload
            .headers
            .push((ORG_ADMISSION_HEADER.to_string(), proof_bytes));
        let mut frame = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
            .to_bytes()
            .to_vec();
        encode_rpc_route(&mut frame, 0);
        frame.extend_from_slice(&payload.encode());
        let event = RpcInboundEvent {
            channel_hash,
            origin_hash: caller_origin,
            from_node: CALLER_NODE,
            payload: Bytes::from(frame),
        };
        assert!(server.deliver_rpc_inbound_for_test(channel_hash, event));

        assert!(
            wait_until_at_least(|| seen.lock().is_some() as u64, 1).await,
            "the handler must run for an admitted protected call",
        );
        let admitted = seen.lock().clone().expect("admitted");
        assert_eq!(admitted.caller, caller_entity, "caller S");
        assert_eq!(
            admitted.acting_org,
            org_b.org_id(),
            "acting org A == owner B"
        );
        assert_eq!(admitted.provider_org, org_b.org_id(), "provider org B");
        assert_eq!(admitted.provider, node_entity, "exact provider P");
        assert_eq!(admitted.capability, cap, "capability C");
    }

    /// §T1 — a byte-identical REPLAY of an admitted proof frame is denied, and
    /// a wire-TAMPERED proof is denied.
    ///
    /// Neither was covered. Every integration test mints a fresh proof per
    /// `call()`, so no test ever re-sent one frame twice: the mutation
    /// "construct a fresh `AdmissionReplayGuard::with_defaults()` per call"
    /// stayed green across the whole suite. And nothing mutated proof bytes on
    /// the wire, because `call()` refuses a caller-supplied
    /// `net-org-admission` header outright, so there is no way to inject one
    /// through the public API.
    ///
    /// Both are reachable here because `deliver_rpc_inbound_for_test` drives
    /// the REAL bridge with a crafted frame. The frame is built ONCE and the
    /// same `Bytes` delivered twice — a genuine replay, not two equivalent
    /// frames.
    #[tokio::test]
    async fn protected_replayed_and_tampered_proof_frames_are_denied() {
        use crate::adapter::net::behavior::org::{
            current_timestamp, OrgKeypair, OrgMembershipCert,
        };
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_call::{OrgCallProof, ORG_ADMISSION_HEADER};
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, OrgDispatcherGrant,
        };
        use crate::adapter::net::org_admission_gate::org_request_digest;

        let admits = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        struct CountingHandler(std::sync::Arc<std::sync::atomic::AtomicUsize>);
        #[async_trait::async_trait]
        impl RpcHandler for CountingHandler {
            async fn call(&self, _ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::from_static(b"pong"),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa2-replay-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        let serve = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(CountingHandler(admits.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve protected");
        let channel_hash = serve.channel_hash;

        const CALLER_NODE: u64 = 0x91;
        let caller_kp = EntityKeypair::generate();
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let call_id = 7u64;
        let base = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        let digest = org_request_digest(&base).expect("digest");
        let membership = OrgMembershipCert::try_issue(&org_b, caller_entity.clone(), 1, 3600)
            .expect("caller cert");
        let dispatcher = OrgDispatcherGrant::try_issue(
            &org_b,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher grant");
        let expiry = (current_timestamp() + 20) * 1_000_000_000;
        let proof = OrgCallProof::sign_for_call(
            &caller_kp,
            membership,
            dispatcher,
            None,
            org_b.org_id(),
            org_b.org_id(),
            node_entity.clone(),
            call_id,
            cap,
            expiry,
            digest,
        );
        let proof_bytes = proof.encode().expect("encode proof");

        // Build the frame ONCE — the same bytes are delivered twice below.
        let mut payload = base.clone();
        payload
            .headers
            .push((ORG_ADMISSION_HEADER.to_string(), proof_bytes.clone()));
        let mut frame = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
            .to_bytes()
            .to_vec();
        encode_rpc_route(&mut frame, 0);
        frame.extend_from_slice(&payload.encode());
        let frame = Bytes::from(frame);
        let event = |payload: Bytes| RpcInboundEvent {
            channel_hash,
            origin_hash: caller_origin,
            from_node: CALLER_NODE,
            payload,
        };

        // 1. First delivery: admitted.
        assert!(server.deliver_rpc_inbound_for_test(channel_hash, event(frame.clone())));
        assert!(
            wait_until_at_least(
                || admits.load(std::sync::atomic::Ordering::SeqCst) as u64,
                1
            )
            .await,
            "the first delivery must be admitted",
        );

        // 2. REPLAY — the identical bytes again. The guard is keyed on
        //    (caller, call_id) and the binding digest matches, so this is a
        //    Replay rather than a CallIdCollision.
        assert!(server.deliver_rpc_inbound_for_test(channel_hash, event(frame.clone())));
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert_eq!(
            admits.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "a byte-identical replay must NOT reach the handler a second time",
        );

        // 3. TAMPER — flip one byte inside the signed proof header value. The
        //    call-binding signature covers it, so the gate must refuse. A
        //    DIFFERENT call_id is used so the replay guard cannot be what
        //    refuses it: the refusal must come from proof verification.
        let mut tampered_proof = proof_bytes.clone();
        let last = tampered_proof.len() - 1;
        tampered_proof[last] ^= 0xFF;
        assert_ne!(tampered_proof, proof_bytes, "the tamper must change bytes");
        let mut tampered_payload = base.clone();
        tampered_payload
            .headers
            .push((ORG_ADMISSION_HEADER.to_string(), tampered_proof));
        let tampered_call_id = call_id + 1;
        let mut tampered_frame =
            EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, tampered_call_id, 0)
                .to_bytes()
                .to_vec();
        encode_rpc_route(&mut tampered_frame, 0);
        tampered_frame.extend_from_slice(&tampered_payload.encode());
        assert!(
            server.deliver_rpc_inbound_for_test(channel_hash, event(Bytes::from(tampered_frame)))
        );
        tokio::time::sleep(Duration::from_millis(200)).await;
        assert_eq!(
            admits.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "a wire-tampered proof must never reach the handler",
        );
    }

    /// E1 fail-closed, end-to-end: a REQUEST whose proof binds a DIFFERENT
    /// call_id than the frame carries is DENIED (`BindingInvalid`) — the handler
    /// NEVER runs — while a valid follow-up on the same single-consumer bridge
    /// IS admitted. `admits == 1` at the FIFO barrier proves the tampered call
    /// was denied, not merely slow.
    #[tokio::test]
    async fn protected_call_with_tampered_binding_is_denied_end_to_end() {
        use crate::adapter::net::behavior::org::{
            current_timestamp, OrgKeypair, OrgMembershipCert,
        };
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_call::{OrgCallProof, ORG_ADMISSION_HEADER};
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, OrgDispatcherGrant,
        };
        use crate::adapter::net::org_admission_gate::org_request_digest;
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct Counter(std::sync::Arc<AtomicUsize>);
        #[async_trait::async_trait]
        impl RpcHandler for Counter {
            async fn call(&self, ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                assert!(
                    ctx.org_admission.is_some(),
                    "only admitted calls may reach the handler",
                );
                self.0.fetch_add(1, Ordering::SeqCst);
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa2-wire-deny-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        let admits = std::sync::Arc::new(AtomicUsize::new(0));
        let serve = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(Counter(admits.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve protected");
        let channel_hash = serve.channel_hash;

        const CALLER_NODE: u64 = 0x93;
        let caller_kp = EntityKeypair::generate();
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let base = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        let digest = org_request_digest(&base).expect("digest");
        let membership = OrgMembershipCert::try_issue(&org_b, caller_entity.clone(), 1, 3600)
            .expect("caller cert");
        let dispatcher = OrgDispatcherGrant::try_issue(
            &org_b,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher grant");
        let expiry = (current_timestamp() + 20) * 1_000_000_000;

        // Build a frame whose proof binds `signed_call_id`, delivered under
        // `frame_call_id`'s EventMeta. Equal → admits; unequal → BindingInvalid.
        let make_frame = |signed_call_id: u64, frame_call_id: u64| {
            let proof = OrgCallProof::sign_for_call(
                &caller_kp,
                membership.clone(),
                dispatcher.clone(),
                None,
                org_b.org_id(),
                org_b.org_id(),
                node_entity.clone(),
                signed_call_id,
                cap,
                expiry,
                digest,
            );
            let mut payload = base.clone();
            payload.headers.push((
                ORG_ADMISSION_HEADER.to_string(),
                proof.encode().expect("encode"),
            ));
            let mut frame =
                EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, frame_call_id, 0)
                    .to_bytes()
                    .to_vec();
            encode_rpc_route(&mut frame, 0);
            frame.extend_from_slice(&payload.encode());
            RpcInboundEvent {
                channel_hash,
                origin_hash: caller_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(frame),
            }
        };

        // Tampered (signed 7, delivered 8) → denied; valid (9/9) → admitted.
        assert!(server.deliver_rpc_inbound_for_test(channel_hash, make_frame(7, 8)));
        assert!(server.deliver_rpc_inbound_for_test(channel_hash, make_frame(9, 9)));

        assert!(
            wait_until_at_least(|| admits.load(Ordering::SeqCst) as u64, 1).await,
            "the valid call must be admitted",
        );
        assert_eq!(
            admits.load(Ordering::SeqCst),
            1,
            "the tampered-binding call was denied (handler never ran for it)",
        );
    }

    /// E2.1 witness 26: the CALLER-side proof builder — `sign_admission_proof`,
    /// the exact minting the unary `call` performs from an `OrgProofIntent` —
    /// produces a proof the LIVE provider gate ADMITS. Proves caller and
    /// provider derive the same request digest (E1.7) and the
    /// `OrgProofIntent → OrgCallProof` mapping is correct end-to-end.
    #[tokio::test]
    async fn caller_proof_intent_produces_an_admissible_proof() {
        use crate::adapter::net::behavior::org::{OrgKeypair, OrgMembershipCert};
        use crate::adapter::net::behavior::org_admission::{Admitted, OrgAdmission};
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, OrgDispatcherGrant,
        };

        type Seen = std::sync::Arc<Mutex<Option<Admitted>>>;
        struct SpyHandler(Seen);
        #[async_trait::async_trait]
        impl RpcHandler for SpyHandler {
            async fn call(&self, ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                *self.0.lock() = Some(ctx.org_admission.clone().expect("admitted call"));
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa2-caller-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        let seen: Seen = std::sync::Arc::new(Mutex::new(None));
        let serve = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(SpyHandler(seen.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve protected");
        let channel_hash = serve.channel_hash;

        const CALLER_NODE: u64 = 0x95;
        let caller_kp = EntityKeypair::generate();
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let membership = OrgMembershipCert::try_issue(&org_b, caller_entity.clone(), 1, 3600)
            .expect("caller cert");
        let dispatcher = OrgDispatcherGrant::try_issue(
            &org_b,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher grant");
        // The production caller intent — exactly what a caller sets on
        // `CallOptions::org_proof_intent`.
        let intent = OrgProofIntent {
            caller: std::sync::Arc::new(caller_kp),
            membership,
            dispatcher,
            capability_grant: None,
            acting_org: org_b.org_id(),
            provider_owner_org: org_b.org_id(),
            provider: node_entity.clone(),
            capability: cap,
            proof_ttl_secs: 30,
        };

        let call_id = 11u64;
        let mut req = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        // The exact header `call` would mint + append.
        req.headers
            .push(sign_admission_proof(&intent, call_id, &req).expect("sign proof"));

        let mut frame = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
            .to_bytes()
            .to_vec();
        encode_rpc_route(&mut frame, 0);
        frame.extend_from_slice(&req.encode());
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            RpcInboundEvent {
                channel_hash,
                origin_hash: caller_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(frame),
            }
        ));

        assert!(
            wait_until_at_least(|| seen.lock().is_some() as u64, 1).await,
            "the caller-built proof must be admitted by the live gate",
        );
        let admitted = seen.lock().clone().expect("admitted");
        assert_eq!(admitted.caller, caller_entity);
        assert_eq!(admitted.provider, node_entity);
        assert_eq!(admitted.capability, cap);
    }

    /// E1 witness 10 (cross-org), end-to-end: a caller in org A holding a
    /// capability grant B→A (INVOKE, covering this provider) is admitted by a
    /// provider owned by org B — exercising the CrossOrgGranted grant checks
    /// (issuer == owner, grantee == acting org, rights ⊇ INVOKE, capability,
    /// target covers P) through the live gate, with A ≠ B in the attribution.
    #[tokio::test]
    async fn protected_cross_org_call_admits_end_to_end() {
        use crate::adapter::net::behavior::org::{OrgKeypair, OrgMembershipCert};
        use crate::adapter::net::behavior::org_admission::{Admitted, OrgAdmission};
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, GrantRights, GrantTargetScope,
            OrgCapabilityGrant, OrgDispatcherGrant,
        };

        type Seen = std::sync::Arc<Mutex<Option<Admitted>>>;
        struct SpyHandler(Seen);
        #[async_trait::async_trait]
        impl RpcHandler for SpyHandler {
            async fn call(&self, ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                *self.0.lock() = Some(ctx.org_admission.clone().expect("admitted call"));
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]); // provider owner
        let org_a = OrgKeypair::from_bytes([0x77u8; 32]); // caller org
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa2-xorg-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        let seen: Seen = std::sync::Arc::new(Mutex::new(None));
        let serve = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(SpyHandler(seen.clone())),
                OrgAdmission::CrossOrgGranted,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve protected");
        let channel_hash = serve.channel_hash;

        const CALLER_NODE: u64 = 0x97;
        let caller_kp = EntityKeypair::generate();
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let membership = OrgMembershipCert::try_issue(&org_a, caller_entity.clone(), 1, 3600)
            .expect("caller cert");
        let dispatcher = OrgDispatcherGrant::try_issue(
            &org_a,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher grant");
        let (grant, _) = OrgCapabilityGrant::try_issue(
            &org_b,
            org_a.org_id(),
            cap,
            GrantRights::INVOKE,
            GrantTargetScope::ExactNode(node_entity.clone()),
            3600,
        )
        .expect("capability grant");
        let intent = OrgProofIntent {
            caller: std::sync::Arc::new(caller_kp),
            membership,
            dispatcher,
            capability_grant: Some(grant),
            acting_org: org_a.org_id(),
            provider_owner_org: org_b.org_id(),
            provider: node_entity.clone(),
            capability: cap,
            proof_ttl_secs: 30,
        };

        let call_id = 13u64;
        let mut req = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        req.headers
            .push(sign_admission_proof(&intent, call_id, &req).expect("sign proof"));
        let mut frame = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
            .to_bytes()
            .to_vec();
        encode_rpc_route(&mut frame, 0);
        frame.extend_from_slice(&req.encode());
        assert!(server.deliver_rpc_inbound_for_test(
            channel_hash,
            RpcInboundEvent {
                channel_hash,
                origin_hash: caller_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(frame),
            }
        ));

        assert!(
            wait_until_at_least(|| seen.lock().is_some() as u64, 1).await,
            "a valid cross-org call must be admitted",
        );
        let admitted = seen.lock().clone().expect("admitted");
        assert_eq!(admitted.acting_org, org_a.org_id(), "acting org A");
        assert_eq!(admitted.provider_org, org_b.org_id(), "provider org B");
        assert_ne!(
            admitted.acting_org, admitted.provider_org,
            "cross-org: A and B are distinct",
        );
    }

    /// OA-4 slice 2 (Tier 2) — the cross-org `CrossOrgGranted` DENIAL matrix,
    /// table-driven through the REAL provider bridge (`deliver_rpc_inbound_for_test`
    /// → `admit_and_dispatch_protected` → `verify_org_admission` + the real replay
    /// guard). Each adversarial frame is DENIED — the handler stays dark — while
    /// genuine calls admit and a replay of an admitted call is refused. The exact
    /// typed `AdmissionDenied` reason for each row is pinned by the pure
    /// `org_admission.rs` unit matrix (Tier 3); here we prove COMPOSITION: through
    /// real dispatch, an unauthorized proof never reaches the handler.
    ///
    /// Covers the eleven-denial matrix incl. the OA-4 addition `GranteeMismatch`
    /// (missing-local-tag is a corrupted-provider-state row, witnessed separately
    /// in `protected_cross_org_missing_local_capability_denies`): wrong grantee
    /// org, foreign issuer, insufficient rights (DISCOVER-only), missing
    /// capability grant, wrong target, wrong capability, wrong body/digest,
    /// expired proof, copied proof (TOFU member binding), missing header, multiple
    /// headers, and replay.
    ///
    /// Barrier discipline: `deliver_rpc_inbound_for_test` is a single-consumer
    /// FIFO, so after every denial frame we deliver two genuine calls (and re-send
    /// the first); `admits == 2` at the end proves every prior adversarial frame
    /// was processed-and-denied and the replay of the first genuine call was
    /// refused — no denial merely raced ahead of a slow admit.
    #[tokio::test]
    async fn cross_org_admission_denial_matrix() {
        use crate::adapter::net::behavior::org::{
            current_timestamp, OrgKeypair, OrgMembershipCert,
        };
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_call::{OrgCallProof, ORG_ADMISSION_HEADER};
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, GrantRights, GrantTargetScope,
            OrgCapabilityGrant, OrgDispatcherGrant,
        };
        use crate::adapter::net::org_admission_gate::org_request_digest;
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct Counter(std::sync::Arc<AtomicUsize>);
        #[async_trait::async_trait]
        impl RpcHandler for Counter {
            async fn call(&self, ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                assert!(
                    ctx.org_admission.is_some(),
                    "only admitted calls may reach the handler",
                );
                self.0.fetch_add(1, Ordering::SeqCst);
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]); // provider owner
        let org_a = OrgKeypair::from_bytes([0x7au8; 32]); // caller org
        let org_c = OrgKeypair::from_bytes([0x33u8; 32]); // foil org
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa4-xorg-deny-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        let admits = std::sync::Arc::new(AtomicUsize::new(0));
        let serve = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(Counter(admits.clone())),
                OrgAdmission::CrossOrgGranted,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve protected");
        let channel_hash = serve.channel_hash;

        const CALLER_NODE: u64 = 0xA1;
        let caller_kp = EntityKeypair::from_bytes([0x1bu8; 32]);
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let base = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        let digest = org_request_digest(&base).expect("digest");
        let future = (current_timestamp() + 20) * 1_000_000_000;

        // Honest baseline credentials for caller S ∈ org A, and a valid B→A INVOKE
        // grant covering exactly P₂.
        let membership_a = OrgMembershipCert::try_issue(&org_a, caller_entity.clone(), 1, 3600)
            .expect("membership");
        let dispatcher_a = OrgDispatcherGrant::try_issue(
            &org_a,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher");
        let good_grant = OrgCapabilityGrant::try_issue(
            &org_b,
            org_a.org_id(),
            cap,
            GrantRights::INVOKE,
            GrantTargetScope::ExactNode(node_entity.clone()),
            3600,
        )
        .expect("grant")
        .0;

        // A frame from S's pinned session carrying `headers`, `body`, `call_id`.
        let make_event = |headers: Vec<Vec<u8>>, call_id: u64, body: &'static [u8]| {
            let mut payload = base.clone();
            payload.body = Bytes::from_static(body);
            payload.headers = headers
                .into_iter()
                .map(|h| (ORG_ADMISSION_HEADER.to_string(), h))
                .collect();
            let mut frame = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
                .to_bytes()
                .to_vec();
            encode_rpc_route(&mut frame, 0);
            frame.extend_from_slice(&payload.encode());
            RpcInboundEvent {
                channel_hash,
                origin_hash: caller_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(frame),
            }
        };
        // Encode a proof header for caller `kp` over the given credentials. The
        // acting org is always A (bound = dispatcher's org), the provider org B.
        let sign = |kp: &EntityKeypair,
                    membership: OrgMembershipCert,
                    dispatcher: OrgDispatcherGrant,
                    grant: Option<OrgCapabilityGrant>,
                    call_id: u64,
                    expiry: u64,
                    dgst: [u8; 32]|
         -> Vec<u8> {
            OrgCallProof::sign_for_call(
                kp,
                membership,
                dispatcher,
                grant,
                org_a.org_id(),
                org_b.org_id(),
                node_entity.clone(),
                call_id,
                cap,
                expiry,
                dgst,
            )
            .encode()
            .expect("encode proof")
        };
        let good = |call_id: u64| {
            sign(
                &caller_kp,
                membership_a.clone(),
                dispatcher_a.clone(),
                Some(good_grant.clone()),
                call_id,
                future,
                digest,
            )
        };

        // ---- The adversarial rows — every one must be DENIED (handler dark). ----

        // 1. Wrong grantee org: grant issued B→C, but the caller is an A member.
        let wrong_grantee = OrgCapabilityGrant::try_issue(
            &org_b,
            org_c.org_id(),
            cap,
            GrantRights::INVOKE,
            GrantTargetScope::ExactNode(node_entity.clone()),
            3600,
        )
        .expect("grant")
        .0;
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_a.clone(),
                    dispatcher_a.clone(),
                    Some(wrong_grantee),
                    101,
                    future,
                    digest,
                )],
                101,
                b"ping",
            ),
        );

        // 2. Foreign issuer: grant issued by org C, not the provider's owner B.
        let foreign_issuer = OrgCapabilityGrant::try_issue(
            &org_c,
            org_a.org_id(),
            cap,
            GrantRights::INVOKE,
            GrantTargetScope::ExactNode(node_entity.clone()),
            3600,
        )
        .expect("grant")
        .0;
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_a.clone(),
                    dispatcher_a.clone(),
                    Some(foreign_issuer),
                    102,
                    future,
                    digest,
                )],
                102,
                b"ping",
            ),
        );

        // 3. Insufficient rights: a DISCOVER-only grant carries no INVOKE.
        let discover_only = OrgCapabilityGrant::try_issue(
            &org_b,
            org_a.org_id(),
            cap,
            GrantRights::DISCOVER,
            GrantTargetScope::ExactNode(node_entity.clone()),
            3600,
        )
        .expect("grant")
        .0;
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_a.clone(),
                    dispatcher_a.clone(),
                    Some(discover_only),
                    103,
                    future,
                    digest,
                )],
                103,
                b"ping",
            ),
        );

        // 4. Missing capability grant: a CrossOrgGranted call with no grant.
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_a.clone(),
                    dispatcher_a.clone(),
                    None,
                    104,
                    future,
                    digest,
                )],
                104,
                b"ping",
            ),
        );

        // 5. Wrong target: the grant names a different provider entity.
        let other_entity = EntityKeypair::from_bytes([0xeeu8; 32]).entity_id().clone();
        let wrong_target = OrgCapabilityGrant::try_issue(
            &org_b,
            org_a.org_id(),
            cap,
            GrantRights::INVOKE,
            GrantTargetScope::ExactNode(other_entity),
            3600,
        )
        .expect("grant")
        .0;
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_a.clone(),
                    dispatcher_a.clone(),
                    Some(wrong_target),
                    105,
                    future,
                    digest,
                )],
                105,
                b"ping",
            ),
        );

        // 6. Wrong capability: the grant authorizes a DIFFERENT capability.
        let wrong_cap = OrgCapabilityGrant::try_issue(
            &org_b,
            org_a.org_id(),
            CapabilityAuthorityId::for_tag("nrpc:other"),
            GrantRights::INVOKE,
            GrantTargetScope::ExactNode(node_entity.clone()),
            3600,
        )
        .expect("grant")
        .0;
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_a.clone(),
                    dispatcher_a.clone(),
                    Some(wrong_cap),
                    106,
                    future,
                    digest,
                )],
                106,
                b"ping",
            ),
        );

        // 7. Wrong body: a proof signed over the "ping" digest, delivered on a
        //    "pong" body → the request digest binding fails.
        server
            .deliver_rpc_inbound_for_test(channel_hash, make_event(vec![good(107)], 107, b"pong"));

        // 8. Expired proof: an expiry 100 s in the past.
        let past = current_timestamp().saturating_sub(100) * 1_000_000_000;
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_a.clone(),
                    dispatcher_a.clone(),
                    Some(good_grant.clone()),
                    108,
                    past,
                    digest,
                )],
                108,
                b"ping",
            ),
        );

        // 9. Copied proof: a valid proof for a DIFFERENT caller X, delivered on
        //    S's authenticated session → TOFU member binding fails.
        let x_kp = EntityKeypair::from_bytes([0x2cu8; 32]);
        let x_entity = x_kp.entity_id().clone();
        let membership_x =
            OrgMembershipCert::try_issue(&org_a, x_entity.clone(), 1, 3600).expect("x membership");
        let dispatcher_x =
            OrgDispatcherGrant::try_issue(&org_a, x_entity, DispatcherScope::Exact(cap), 3600)
                .expect("x dispatcher");
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &x_kp,
                    membership_x,
                    dispatcher_x,
                    Some(good_grant.clone()),
                    109,
                    future,
                    digest,
                )],
                109,
                b"ping",
            ),
        );

        // 10. Missing header: no admission header at all.
        server.deliver_rpc_inbound_for_test(channel_hash, make_event(vec![], 110, b"ping"));

        // 11. Multiple headers: two admission headers on one request.
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(vec![good(111), good(111)], 111, b"ping"),
        );

        // ---- Genuine calls + replay: the FIFO barrier. ----
        let v1 = good(200);
        server
            .deliver_rpc_inbound_for_test(channel_hash, make_event(vec![v1.clone()], 200, b"ping"));
        // Replay: the identical admitted frame again → refused (no second admit).
        server.deliver_rpc_inbound_for_test(channel_hash, make_event(vec![v1], 200, b"ping"));
        // A second genuine call closes the barrier.
        server
            .deliver_rpc_inbound_for_test(channel_hash, make_event(vec![good(201)], 201, b"ping"));

        assert!(
            wait_until_at_least(|| admits.load(Ordering::SeqCst) as u64, 2).await,
            "the two genuine cross-org calls must be admitted",
        );
        assert_eq!(
            admits.load(Ordering::SeqCst),
            2,
            "exactly the two genuine calls admitted — every adversarial frame was denied \
             (handler dark) and the replay of the first genuine call was refused",
        );
    }

    /// OA-4 slice 3 (Tier 2) — the OwnerDelegated DENIAL matrix, table-driven
    /// through the real provider bridge (mirrors the cross-org harness for the
    /// same-org mode). Each adversarial frame is DENIED (handler dark); the exact
    /// typed reason is pinned by the pure `org_admission.rs` unit matrix (Tier 3).
    /// Rows: membership-only (dispatcher grant scoped to another capability),
    /// copied proof (TOFU member binding), wrong callee, wrong capability, wrong
    /// body/digest, expired proof, an UNEXPECTED capability grant (OwnerDelegated
    /// forbids one), grantee mismatch (acting org ≠ the provider's owner), missing
    /// header, multiple headers. A FIFO barrier of two genuine calls (the first
    /// re-sent) gives `admits == 2` — every denial and the replay were refused.
    #[tokio::test]
    async fn owner_delegated_admission_denial_matrix() {
        use crate::adapter::net::behavior::org::{
            current_timestamp, OrgKeypair, OrgMembershipCert,
        };
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_call::{OrgCallProof, ORG_ADMISSION_HEADER};
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, GrantRights, GrantTargetScope,
            OrgCapabilityGrant, OrgDispatcherGrant,
        };
        use crate::adapter::net::org_admission_gate::org_request_digest;
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct Counter(std::sync::Arc<AtomicUsize>);
        #[async_trait::async_trait]
        impl RpcHandler for Counter {
            async fn call(&self, ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                assert!(
                    ctx.org_admission.is_some(),
                    "only admitted calls may reach the handler",
                );
                self.0.fetch_add(1, Ordering::SeqCst);
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]); // provider owner == caller org
        let org_a = OrgKeypair::from_bytes([0x7au8; 32]); // a FOREIGN org, for grantee mismatch
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa4-owner-deny-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        let admits = std::sync::Arc::new(AtomicUsize::new(0));
        let serve = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(Counter(admits.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve protected");
        let channel_hash = serve.channel_hash;

        const CALLER_NODE: u64 = 0xB1;
        let caller_kp = EntityKeypair::from_bytes([0x3bu8; 32]);
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let base = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        let digest = org_request_digest(&base).expect("digest");
        let future = (current_timestamp() + 20) * 1_000_000_000;

        // Honest OwnerDelegated baseline: caller S is a member of the provider's
        // OWN owner org B, with a dispatcher grant covering nrpc:svc and no
        // capability grant.
        let membership_b = OrgMembershipCert::try_issue(&org_b, caller_entity.clone(), 1, 3600)
            .expect("membership");
        let dispatcher_b = OrgDispatcherGrant::try_issue(
            &org_b,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher");

        let make_event = |headers: Vec<Vec<u8>>, call_id: u64, body: &'static [u8]| {
            let mut payload = base.clone();
            payload.body = Bytes::from_static(body);
            payload.headers = headers
                .into_iter()
                .map(|h| (ORG_ADMISSION_HEADER.to_string(), h))
                .collect();
            let mut frame = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
                .to_bytes()
                .to_vec();
            encode_rpc_route(&mut frame, 0);
            frame.extend_from_slice(&payload.encode());
            RpcInboundEvent {
                channel_hash,
                origin_hash: caller_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(frame),
            }
        };
        // sign_for_call with explicit fields — full proof surgery.
        #[allow(clippy::too_many_arguments)]
        let sign = |kp: &EntityKeypair,
                    membership: OrgMembershipCert,
                    dispatcher: OrgDispatcherGrant,
                    grant: Option<OrgCapabilityGrant>,
                    acting_org: crate::adapter::net::behavior::org::OrgId,
                    callee: crate::adapter::net::identity::EntityId,
                    capability: CapabilityAuthorityId,
                    call_id: u64,
                    expiry: u64,
                    dgst: [u8; 32]|
         -> Vec<u8> {
            OrgCallProof::sign_for_call(
                kp,
                membership,
                dispatcher,
                grant,
                acting_org,
                org_b.org_id(),
                callee,
                call_id,
                capability,
                expiry,
                dgst,
            )
            .encode()
            .expect("encode proof")
        };
        let good = |call_id: u64| {
            sign(
                &caller_kp,
                membership_b.clone(),
                dispatcher_b.clone(),
                None,
                org_b.org_id(),
                node_entity.clone(),
                cap,
                call_id,
                future,
                digest,
            )
        };

        // 1. Membership-only: the dispatcher grant covers a DIFFERENT capability,
        //    so it does not empower this call → DispatcherGrantScope.
        let dispatcher_other = OrgDispatcherGrant::try_issue(
            &org_b,
            caller_entity.clone(),
            DispatcherScope::Exact(CapabilityAuthorityId::for_tag("nrpc:other")),
            3600,
        )
        .expect("dispatcher");
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_b.clone(),
                    dispatcher_other,
                    None,
                    org_b.org_id(),
                    node_entity.clone(),
                    cap,
                    401,
                    future,
                    digest,
                )],
                401,
                b"ping",
            ),
        );

        // 2. Copied proof: a valid proof for a DIFFERENT caller X on S's session.
        let x_kp = EntityKeypair::from_bytes([0x3cu8; 32]);
        let x_entity = x_kp.entity_id().clone();
        let membership_x =
            OrgMembershipCert::try_issue(&org_b, x_entity.clone(), 1, 3600).expect("x membership");
        let dispatcher_x =
            OrgDispatcherGrant::try_issue(&org_b, x_entity, DispatcherScope::Exact(cap), 3600)
                .expect("x dispatcher");
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &x_kp,
                    membership_x,
                    dispatcher_x,
                    None,
                    org_b.org_id(),
                    node_entity.clone(),
                    cap,
                    402,
                    future,
                    digest,
                )],
                402,
                b"ping",
            ),
        );

        // 3. Wrong callee: the binding names a different provider entity.
        let other_entity = EntityKeypair::from_bytes([0xefu8; 32]).entity_id().clone();
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_b.clone(),
                    dispatcher_b.clone(),
                    None,
                    org_b.org_id(),
                    other_entity,
                    cap,
                    403,
                    future,
                    digest,
                )],
                403,
                b"ping",
            ),
        );

        // 4. Wrong capability: the binding is minted for a different capability.
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_b.clone(),
                    dispatcher_b.clone(),
                    None,
                    org_b.org_id(),
                    node_entity.clone(),
                    CapabilityAuthorityId::for_tag("nrpc:other"),
                    404,
                    future,
                    digest,
                )],
                404,
                b"ping",
            ),
        );

        // 5. Wrong body: signed over the "ping" digest, delivered on "pong".
        server
            .deliver_rpc_inbound_for_test(channel_hash, make_event(vec![good(405)], 405, b"pong"));

        // 6. Expired proof.
        let past = current_timestamp().saturating_sub(100) * 1_000_000_000;
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_b.clone(),
                    dispatcher_b.clone(),
                    None,
                    org_b.org_id(),
                    node_entity.clone(),
                    cap,
                    406,
                    past,
                    digest,
                )],
                406,
                b"ping",
            ),
        );

        // 7. Unexpected capability grant: OwnerDelegated forbids carrying one.
        let stray_grant = OrgCapabilityGrant::try_issue(
            &org_b,
            org_b.org_id(),
            cap,
            GrantRights::INVOKE,
            GrantTargetScope::ExactNode(node_entity.clone()),
            3600,
        )
        .expect("grant")
        .0;
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_b.clone(),
                    dispatcher_b.clone(),
                    Some(stray_grant),
                    org_b.org_id(),
                    node_entity.clone(),
                    cap,
                    407,
                    future,
                    digest,
                )],
                407,
                b"ping",
            ),
        );

        // 8. Grantee mismatch: the caller acts for a FOREIGN org A, not the
        //    provider's owner B → OwnerDelegated denies.
        let membership_a = OrgMembershipCert::try_issue(&org_a, caller_entity.clone(), 1, 3600)
            .expect("a membership");
        let dispatcher_a = OrgDispatcherGrant::try_issue(
            &org_a,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("a dispatcher");
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(
                vec![sign(
                    &caller_kp,
                    membership_a,
                    dispatcher_a,
                    None,
                    org_a.org_id(),
                    node_entity.clone(),
                    cap,
                    408,
                    future,
                    digest,
                )],
                408,
                b"ping",
            ),
        );

        // 9. Missing header. 10. Multiple headers.
        server.deliver_rpc_inbound_for_test(channel_hash, make_event(vec![], 409, b"ping"));
        server.deliver_rpc_inbound_for_test(
            channel_hash,
            make_event(vec![good(410), good(410)], 410, b"ping"),
        );

        // Genuine + replay barrier.
        let v1 = good(500);
        server
            .deliver_rpc_inbound_for_test(channel_hash, make_event(vec![v1.clone()], 500, b"ping"));
        server.deliver_rpc_inbound_for_test(channel_hash, make_event(vec![v1], 500, b"ping"));
        server
            .deliver_rpc_inbound_for_test(channel_hash, make_event(vec![good(501)], 501, b"ping"));

        assert!(
            wait_until_at_least(|| admits.load(Ordering::SeqCst) as u64, 2).await,
            "the two genuine owner-delegated calls must be admitted",
        );
        assert_eq!(
            admits.load(Ordering::SeqCst),
            2,
            "exactly the two genuine calls admitted — every adversarial frame was denied \
             (handler dark) and the replay of the first genuine call was refused",
        );
    }

    /// OA-4 slice 5 (review-7 RED) — `OrgAdmission` is load-bearing, independent
    /// of any legacy `may_execute` verdict. On a provider whose target-wide
    /// allow-list aggregation makes `may_execute(P, C, S)` FALSE while
    /// `has_local_capability(P, C)` is TRUE:
    ///   * positive control — a VALID org proof for C is admitted through the
    ///     protected path (the legacy gate cannot block it);
    ///   * negative control — an unauthorized (no-proof) request is denied and the
    ///     handler stays dark;
    ///   * RED — re-registering C with the `#[cfg(test)]`-only disabled mode (which
    ///     bypasses ONLY `verify_org_admission`, after every provider/transport
    ///     precheck) makes the SAME unauthorized request run the handler.
    ///
    /// The RED succeeding proves the org-admission engine is the load-bearing
    /// authority: removing it alone — nothing else — admits an unauthorized call.
    /// The disabled registration does not outlive this test.
    #[tokio::test]
    async fn seam_red_org_admission_is_load_bearing() {
        use crate::adapter::net::behavior::fold::capability::{
            CapabilityFold, CapabilityMembership,
        };
        use crate::adapter::net::behavior::fold::capability_bridge::{
            has_local_capability, may_execute,
        };
        use crate::adapter::net::behavior::fold::{
            EnvelopeMeta, FoldKind, NodeState, SignedAnnouncement,
        };
        use crate::adapter::net::behavior::org::{
            current_timestamp, OrgKeypair, OrgMembershipCert,
        };
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_call::{OrgCallProof, ORG_ADMISSION_HEADER};
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, GrantRights, GrantTargetScope,
            OrgCapabilityGrant, OrgDispatcherGrant,
        };
        use crate::adapter::net::org_admission_gate::org_request_digest;
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct Counter(std::sync::Arc<AtomicUsize>);
        #[async_trait::async_trait]
        impl RpcHandler for Counter {
            async fn call(&self, _ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                self.0.fetch_add(1, Ordering::SeqCst);
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]); // provider owner
        let org_a = OrgKeypair::from_bytes([0x7au8; 32]); // caller org
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa4-seamred-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        const CALLER_NODE: u64 = 0xC1;
        let caller_kp = EntityKeypair::from_bytes([0x4bu8; 32]);
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let base = RpcRequestPayload {
            service: "svc".to_string(),
            deadline_ns: 0,
            flags: 0,
            headers: vec![],
            body: Bytes::from_static(b"ping"),
        };
        let digest = org_request_digest(&base).expect("digest");
        let future = (current_timestamp() + 20) * 1_000_000_000;

        // A valid CROSS-ORG proof for C: caller S ∈ org A holds a B→A INVOKE grant
        // covering exactly this provider.
        let membership = OrgMembershipCert::try_issue(&org_a, caller_entity.clone(), 1, 3600)
            .expect("membership");
        let dispatcher = OrgDispatcherGrant::try_issue(
            &org_a,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher");
        let grant = OrgCapabilityGrant::try_issue(
            &org_b,
            org_a.org_id(),
            cap,
            GrantRights::INVOKE,
            GrantTargetScope::ExactNode(node_entity.clone()),
            3600,
        )
        .expect("grant")
        .0;
        let valid_proof = |call_id: u64| {
            OrgCallProof::sign_for_call(
                &caller_kp,
                membership.clone(),
                dispatcher.clone(),
                Some(grant.clone()),
                org_a.org_id(),
                org_b.org_id(),
                node_entity.clone(),
                call_id,
                cap,
                future,
                digest,
            )
            .encode()
            .expect("encode proof")
        };
        let make_event = |ch: u64, headers: Vec<Vec<u8>>, call_id: u64| {
            let mut payload = base.clone();
            payload.headers = headers
                .into_iter()
                .map(|h| (ORG_ADMISSION_HEADER.to_string(), h))
                .collect();
            let mut frame = EventMeta::new(DISPATCH_RPC_REQUEST, 0, caller_origin, call_id, 0)
                .to_bytes()
                .to_vec();
            encode_rpc_route(&mut frame, 0);
            frame.extend_from_slice(&payload.encode());
            RpcInboundEvent {
                channel_hash: ch,
                origin_hash: caller_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(frame),
            }
        };
        // An unrelated PUBLIC service D — a real service governed by `may_execute`
        // (Slice-6 exit-map accounting). Its ServeHandle is kept alive so its
        // registration persists across C's teardown/re-registration.
        let _serve_d = server
            .serve_rpc(
                "d",
                std::sync::Arc::new(Counter(std::sync::Arc::new(AtomicUsize::new(0)))),
            )
            .expect("serve public D");

        // ---- Phase A: admission ENFORCED. ----
        let admits = std::sync::Arc::new(AtomicUsize::new(0));
        let serve_enforced = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(Counter(admits.clone())),
                OrgAdmission::CrossOrgGranted,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve enforced");
        let ch = serve_enforced.channel_hash;

        // C's OWN entry is unrestricted: with only the class-0 self entries (C and
        // the public D, both empty allow-lists) the legacy gate PERMITS S.
        assert!(
            may_execute(
                server.capability_fold(),
                server.node_id(),
                "nrpc:svc",
                CALLER_NODE
            ),
            "before the unrelated restricted D entry, C's own class-0 entry permits S \
             (empty allow-lists)",
        );

        // Add a SEPARATE restrictive native-class (0xD00D) entry for the same
        // provider, carrying ONLY `nrpc:d` with a non-S allow-list. A distinct
        // class key keeps it OUT of C's class-0 self entry (so C stays unrestricted)
        // and lets it survive C's re-registration.
        let d_kp = EntityKeypair::generate();
        let d_entry = SignedAnnouncement::sign(
            &d_kp,
            CapabilityFold::KIND_ID,
            0xD00D,
            server.node_id(),
            1,
            EnvelopeMeta::default(),
            CapabilityMembership {
                class_hash: 0xD00D,
                tags: vec!["nrpc:d".to_string()],
                hardware: None,
                state: NodeState::Idle,
                region: None,
                price_quote: None,
                reflex_addr: None,
                allowed_nodes: vec![0xDEAD],
                allowed_subnets: vec![],
                allowed_groups: vec![],
                metadata: std::collections::BTreeMap::new(),
                owner: None,
            },
        )
        .expect("sign restrictive D");
        server
            .capability_fold()
            .apply(d_entry)
            .expect("apply restrictive D entry");

        // Now the review-7 condition holds via UNRELATED-D target-wide aggregation:
        // C is present locally and its OWN entry is unrestricted, yet may_execute(C,
        // S) is false purely because D's separate restrictive entry contaminates the
        // aggregation — and D's own gate denies S.
        assert!(
            has_local_capability(server.capability_fold(), server.node_id(), "nrpc:svc"),
            "the provider holds C locally",
        );
        assert!(
            !may_execute(
                server.capability_fold(),
                server.node_id(),
                "nrpc:svc",
                CALLER_NODE
            ),
            "may_execute(P, C, S) is now false ONLY via the unrelated D entry's \
             target-wide aggregation — C's own entry is still unrestricted",
        );
        assert!(
            !may_execute(
                server.capability_fold(),
                server.node_id(),
                "nrpc:d",
                CALLER_NODE
            ),
            "the unrelated D is itself governed by may_execute (S excluded)",
        );

        // Positive control: a valid proof is admitted despite may_execute == false.
        server.deliver_rpc_inbound_for_test(ch, make_event(ch, vec![valid_proof(700)], 700));
        // Negative control: an unauthorized (no-proof) request is denied.
        server.deliver_rpc_inbound_for_test(ch, make_event(ch, vec![], 701));
        // A second valid call closes the FIFO barrier.
        server.deliver_rpc_inbound_for_test(ch, make_event(ch, vec![valid_proof(702)], 702));
        assert!(
            wait_until_at_least(|| admits.load(Ordering::SeqCst) as u64, 2).await,
            "both valid proofs are admitted through the protected path",
        );
        assert_eq!(
            admits.load(Ordering::SeqCst),
            2,
            "the two valid proofs admitted (legacy gate cannot block C); the no-proof \
             request was denied under enforced admission",
        );

        // ---- Phase B: RED — admission DISABLED for an equivalent C. ----
        drop(serve_enforced);
        let serve_disabled = server
            .serve_rpc_protected_red_witness_disabled(
                "svc",
                std::sync::Arc::new(Counter(admits.clone())),
                OrgAdmission::CrossOrgGranted,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve red-witness-disabled");
        let ch2 = serve_disabled.channel_hash;
        // The native D entry survived the re-registration (distinct class key), so
        // the review-7 condition still holds — no re-injection needed.
        assert!(
            has_local_capability(server.capability_fold(), server.node_id(), "nrpc:svc"),
            "C is present locally after the re-registration",
        );
        assert!(
            !may_execute(
                server.capability_fold(),
                server.node_id(),
                "nrpc:svc",
                CALLER_NODE
            ),
            "may_execute(P, C, S) stays false via the surviving unrelated D entry",
        );

        // The SAME unauthorized (no-proof) request now RUNS the handler — proving
        // that removing ONLY verify_org_admission is what admitted it.
        server.deliver_rpc_inbound_for_test(ch2, make_event(ch2, vec![], 703));
        assert!(
            wait_until_at_least(|| admits.load(Ordering::SeqCst) as u64, 3).await,
            "RED: with org admission disabled, the unauthorized protected call ran the handler",
        );
        assert_eq!(
            admits.load(Ordering::SeqCst),
            3,
            "disabling ONLY verify_org_admission let the unauthorized protected call execute — \
             OrgAdmission is load-bearing, independent of the legacy may_execute verdict",
        );

        drop(serve_disabled);
    }

    /// Kyra #47 B1: the gate binds the AUTHENTICATED session entity's origin to
    /// the wire-claimed origin. A pinned peer with a VALID proof for itself, but
    /// stamping a DIFFERENT origin (packet == payload == victim) into the frame,
    /// is DENIED — split authenticated/claimed identity cannot reach the handler
    /// (nor aim a response at the victim). A correctly-stamped follow-up admits,
    /// so `admits == 1` at the FIFO barrier proves the mismatched call was denied.
    #[tokio::test]
    async fn protected_gate_binds_authenticated_identity_to_claimed_origin() {
        use crate::adapter::net::behavior::org::{OrgKeypair, OrgMembershipCert};
        use crate::adapter::net::behavior::org_admission::OrgAdmission;
        use crate::adapter::net::behavior::org_authority::NodeAuthority;
        use crate::adapter::net::behavior::org_grant::{
            CapabilityAuthorityId, DispatcherScope, OrgDispatcherGrant,
        };
        use std::sync::atomic::{AtomicUsize, Ordering};

        struct Counter(std::sync::Arc<AtomicUsize>);
        #[async_trait::async_trait]
        impl RpcHandler for Counter {
            async fn call(&self, _ctx: RpcContext) -> Result<RpcResponsePayload, RpcHandlerError> {
                self.0.fetch_add(1, Ordering::SeqCst);
                Ok(RpcResponsePayload {
                    status: RpcStatus::Ok,
                    headers: vec![],
                    body: Bytes::new(),
                })
            }
        }

        let server = build_server().await;
        let node_entity = server.entity_id().clone();
        let org_b = OrgKeypair::from_bytes([0x42u8; 32]);
        let node_cert =
            OrgMembershipCert::try_issue(&org_b, node_entity.clone(), 1, 3600).expect("node cert");
        let dir = std::env::temp_dir().join(format!("net-oa2-b1-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let authority =
            NodeAuthority::adopt(&dir, node_cert, &node_entity, 0, None).expect("adopt authority");
        server
            .install_node_authority(std::sync::Arc::new(authority))
            .expect("install authority");

        let admits = std::sync::Arc::new(AtomicUsize::new(0));
        let serve = server
            .serve_rpc_protected(
                "svc",
                std::sync::Arc::new(Counter(admits.clone())),
                OrgAdmission::OwnerDelegated,
                std::sync::Arc::new(|_| true),
            )
            .expect("serve protected");
        let channel_hash = serve.channel_hash;

        const CALLER_NODE: u64 = 0x99;
        let caller_kp = EntityKeypair::generate();
        let caller_entity = caller_kp.entity_id().clone();
        let caller_origin = caller_entity.origin_hash();
        let victim_origin = caller_origin ^ 0xFFFF_FFFF; // a DIFFERENT origin
        server.test_pin_peer_entity(CALLER_NODE, caller_entity.clone());

        let cap = CapabilityAuthorityId::for_tag("nrpc:svc");
        let membership = OrgMembershipCert::try_issue(&org_b, caller_entity.clone(), 1, 3600)
            .expect("caller cert");
        let dispatcher = OrgDispatcherGrant::try_issue(
            &org_b,
            caller_entity.clone(),
            DispatcherScope::Exact(cap),
            3600,
        )
        .expect("dispatcher grant");
        let intent = OrgProofIntent {
            caller: std::sync::Arc::new(caller_kp),
            membership,
            dispatcher,
            capability_grant: None,
            acting_org: org_b.org_id(),
            provider_owner_org: org_b.org_id(),
            provider: node_entity.clone(),
            capability: cap,
            proof_ttl_secs: 30,
        };
        // A valid self-proof for `intent` at `call_id`, stamped with `frame_origin`.
        let frame = |call_id: u64, frame_origin: u64| {
            let mut req = RpcRequestPayload {
                service: "svc".to_string(),
                deadline_ns: 0,
                flags: 0,
                headers: vec![],
                body: Bytes::from_static(b"ping"),
            };
            req.headers
                .push(sign_admission_proof(&intent, call_id, &req).expect("sign"));
            let mut f = EventMeta::new(DISPATCH_RPC_REQUEST, 0, frame_origin, call_id, 0)
                .to_bytes()
                .to_vec();
            encode_rpc_route(&mut f, 0);
            f.extend_from_slice(&req.encode());
            RpcInboundEvent {
                channel_hash,
                origin_hash: frame_origin,
                from_node: CALLER_NODE,
                payload: Bytes::from(f),
            }
        };

        // Split identity (valid self-proof, VICTIM origin stamped) → denied.
        assert!(server.deliver_rpc_inbound_for_test(channel_hash, frame(1, victim_origin)));
        // Honest (matched origin) → admitted; the FIFO barrier for the deny.
        assert!(server.deliver_rpc_inbound_for_test(channel_hash, frame(2, caller_origin)));
        assert!(
            wait_until_at_least(|| admits.load(Ordering::SeqCst) as u64, 1).await,
            "the origin-matched call is admitted",
        );
        assert_eq!(
            admits.load(Ordering::SeqCst),
            1,
            "the origin-mismatched call was denied — the handler stayed dark",
        );
    }

    /// Like [`build_server`], but installs a channel-config registry that
    /// token-gates `reply` on a root the node cannot chain to. The local
    /// node holds no matching token, so any *roster* fan-out on `reply`
    /// is denied publisher-side (`publish` returns
    /// `Connection("channel: publish denied by channel ACL")`) — a clean,
    /// live-session-free, deterministic observable for "did the roster
    /// path run?". A DirectOnly frame that correctly drops never consults
    /// the roster, so it stays `Ok`; a frame that (incorrectly)
    /// roster-fell-back surfaces the ACL `Err`.
    async fn build_server_with_token_gated_reply(reply: &ChannelName) -> Arc<MeshNode> {
        use crate::adapter::net::channel::{ChannelConfig, ChannelConfigRegistry};
        let addr: SocketAddr = "127.0.0.1:0".parse().unwrap();
        let cfg = MeshNodeConfig::new(addr, [0x42u8; 32])
            .with_heartbeat_interval(Duration::from_millis(200))
            .with_session_timeout(Duration::from_secs(10))
            .with_handshake(3, Duration::from_secs(2));
        let mut node = MeshNode::new(EntityKeypair::generate(), cfg)
            .await
            .expect("MeshNode::new");
        let registry = ChannelConfigRegistry::new();
        // A root the local node has no chain to → `can_publish` fails
        // closed (no chain presented), so the roster path errors.
        let foreign_root = EntityKeypair::generate().entity_id().clone();
        registry.insert(
            ChannelConfig::new(ChannelId::new(reply.clone())).with_token_roots(vec![foreign_root]),
        );
        node.set_channel_configs(Arc::new(registry));
        Arc::new(node)
    }

    /// R2-6: the atomic pre-send outcome. A never-connected peer must
    /// report [`PeerPublishOutcome::NoSession`] from the production seam
    /// `try_publish_to_peer` — the single session-existence gate that
    /// replaced AV-5's `has_peer_session`-then-`publish` TOCTOU. Nothing
    /// is built or transmitted, so a caller may safely fall back.
    ///
    /// Red-witness: making the `None` arm of `try_publish_to_peer` return
    /// `Sent` (or `SendFailed`) instead of `NoSession` fails the match.
    #[tokio::test]
    async fn try_publish_to_peer_reports_pre_send_no_session() {
        let server = build_server().await;
        let reply = ChannelName::new("svc.replies.0000000000000002").unwrap();
        let cid = ChannelId::new(reply);
        let reply_hash = cid.hash();
        let reply_sid = MeshNode::publish_stream_id(&cid);
        const NEVER_CONNECTED: u64 = 0xDEAD_BEEF_0000_0002;
        assert!(!server.has_peer_session(NEVER_CONNECTED));
        let outcome = server
            .try_publish_to_peer(
                NEVER_CONNECTED,
                reply_hash,
                reply_sid,
                /* reliable */ true,
                std::slice::from_ref(&Bytes::from_static(b"resp")),
            )
            .await;
        assert!(
            matches!(outcome, PeerPublishOutcome::NoSession),
            "a never-connected peer must report the pre-send NoSession outcome",
        );
    }

    /// R2-7: the routing policy — proved by DIVERGENCE on identical input.
    /// The reply channel is token-gated so a roster fan-out errors; the
    /// target peer session is gone. Over the SAME gone peer:
    ///
    /// - `DirectOnly` DROPS (never consults the roster) → `Ok`;
    /// - `RosterOnStaleDirect` reaches the (ACL-denied) roster → `Err`.
    ///
    /// The Ok/Err split — same call, same gone peer, only the policy
    /// differs — is the exactly-once routing decision Kyra's addendum
    /// asked for, not merely "Ok against an empty roster". A denial can
    /// never reflect onto the claimed origin's roster channel (NC2).
    ///
    /// Red-witness: deleting the DirectOnly `return Ok(())` drop (letting
    /// it fall through to the roster) makes the DirectOnly call surface
    /// the ACL `Err`, failing the first assertion.
    #[tokio::test]
    async fn direct_only_frame_drops_while_normal_response_rosters_when_peer_gone() {
        let reply = ChannelName::new("svc.replies.0000000000000003").unwrap();
        let server = build_server_with_token_gated_reply(&reply).await;
        let cid = ChannelId::new(reply.clone());
        let reply_hash = cid.hash();
        let reply_sid = MeshNode::publish_stream_id(&cid);
        const GONE_NODE: u64 = 0xDEAD_BEEF_0000_0003;
        assert!(!server.has_peer_session(GONE_NODE));

        let direct = publish_response_to_caller(
            &server,
            /* caller_origin */ 0x3,
            Some(GONE_NODE),
            &reply,
            reply_hash,
            reply_sid,
            Bytes::from_static(b"deny"),
            ResponseRouteFallback::DirectOnly,
        )
        .await;
        assert!(
            direct.is_ok(),
            "a direct-only frame to a gone peer must DROP (never roster-fallback): {direct:?}",
        );

        let roster = publish_response_to_caller(
            &server,
            /* caller_origin */ 0x3,
            Some(GONE_NODE),
            &reply,
            reply_hash,
            reply_sid,
            Bytes::from_static(b"resp"),
            ResponseRouteFallback::RosterOnStaleDirect,
        )
        .await;
        assert!(
            roster.is_err(),
            "a normal response to a gone peer must REACH the (ACL-denied) roster, \
             proving the divergence is the routing policy not an empty roster: {roster:?}",
        );
    }

    /// AV-5 regression (retained): a normal RESPONSE whose resolved route
    /// hint points at a node with no peer session must still fall back to
    /// the subscriber roster rather than erroring out — on a genuinely
    /// open (empty) roster that fan-out is a clean `Ok`, so the response
    /// is never lost. The stronger reachability proof lives in
    /// [`direct_only_frame_drops_while_normal_response_rosters_when_peer_gone`].
    #[tokio::test]
    async fn stale_route_hint_falls_back_to_the_roster() {
        let server = build_server().await;
        let reply = ChannelName::new("svc.replies.0000000000000001").unwrap();
        let cid = ChannelId::new(reply.clone());
        let reply_hash = cid.hash();
        let reply_sid = MeshNode::publish_stream_id(&cid);
        // A NodeId that was never connected: the atomic `try_publish_to_peer`
        // reports NoSession, so nothing is sent and the roster path is taken.
        const STALE_NODE: u64 = 0xDEAD_BEEF_0000_0001;
        assert!(!server.has_peer_session(STALE_NODE));
        let result = publish_response_to_caller(
            &server,
            /* caller_origin */ 0x1,
            Some(STALE_NODE),
            &reply,
            reply_hash,
            reply_sid,
            Bytes::from_static(b"resp"),
            ResponseRouteFallback::RosterOnStaleDirect,
        )
        .await;
        assert!(
            result.is_ok(),
            "a stale route hint must fall back to the roster, not error out: {result:?}",
        );
    }
}