rvoip-sip 0.3.8

SIP umbrella for RVoIP: api/* (UnifiedCoordinator, StreamPeer, CallbackPeer, Endpoint), server/* (B2BUA helpers), adapter/* (rvoip-core::ConnectionAdapter impl)
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
//! Simplified Dialog Adapter for rvoip-sip
//!
//! Thin translation layer between dialog-core and state machine.
//! Focuses only on essential dialog operations and events.
//!
//! ## API Design
//!
//! This adapter provides a clean interface for dialog operations:
//!
//! ### Primary Methods
//! - `send_invite_with_details()` - Creates dialog and sends INVITE in one atomic operation
//! - `send_response()` - Sends SIP responses for incoming calls
//!
//! ### Removed Methods
//! The following methods were removed to avoid confusion:
//! - `create_dialog()` - Did not actually create a dialog in dialog-core
//! - `send_invite()` - Did not actually send an INVITE
//!
//! All dialog creation is now done through `send_invite_with_details()` which
//! properly creates the dialog in dialog-core and sends the INVITE.

use crate::adapters::outbound_request_tracker::{
    OutboundInDialogRequestTracker, TrackedInDialogOptions,
};
use crate::api::types::DialogIdentity;
use crate::cleanup_diag::{self, CleanupStage};
use crate::errors::{Result, SessionError};
use crate::retained_tasks::RetainedTasks;
use crate::session_lifecycle::{
    ManagedResourceReleaseError, ManagedSessionResource, OwnedOperation, OwnedOperationCompletion,
    ResourceDescriptor, ResourceSpec, SessionOperationKind,
};
use crate::session_registry::{SessionRegistry, SessionRegistryError, SessionRegistryHandle};
use crate::session_store::{SessionState, SessionStore};
use crate::sip_data_message::{
    build_sip_data_request, SipDataMessage, SipDataMessageDispatchLanes,
};
use crate::state_table::{
    types::{DialogId, SessionId},
    EventType,
};
use dashmap::DashMap;
use rvoip_infra_common::events::coordinator::GlobalEventCoordinator;
use rvoip_sip_core::{Method, Response, StatusCode, Uri};
use rvoip_sip_dialog::{
    api::unified::{
        ByeRequestOptions, CancelRequestOptions, InfoRequestOptions, MessageRequestOptions,
        NotifyRequestOptions, OptionsRequestOptions, ReferRequestOptions, RegisterRequestOptions,
        SubscribeRequestOptions, UnifiedDialogApi, UpdateRequestOptions,
    },
    transaction::{
        dialog::DialogRequestTemplate, transport::multiplexed::exact_next_hop_uri_for_request,
        ClientTransactionCompletionHandle, ClientTransactionOutcome, TransactionKey,
    },
    DialogId as RvoipDialogId, DialogState, InitialInviteOwner, InitialInviteWireOutcome,
};
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
use std::sync::{Arc, Mutex as StdMutex, Weak};
use std::time::{Duration, Instant};

const INITIAL_INVITE_OWNED_OPERATION_TIMEOUT: Duration = Duration::from_secs(30);
const INITIAL_INVITE_RESOURCE_RELEASE_TIMEOUT: Duration = Duration::from_secs(12);
const INITIAL_INVITE_PROTOCOL_DRAIN_TIMEOUT: Duration = Duration::from_secs(10);
const DATA_MESSAGE_FINAL_RESPONSE_TIMEOUT: Duration = Duration::from_secs(5);
const REGISTRATION_REFRESH_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);

const OWNED_INVITE_INSTALLED: u8 = 0;
const OWNED_INVITE_SENT: u8 = 1;
const OWNED_INVITE_WIRE_UNKNOWN: u8 = 2;
const OWNED_INVITE_ZERO_WIRE: u8 = 3;

fn spawn_api_event_observation(
    coordinator: Arc<GlobalEventCoordinator>,
    api_event: crate::api::events::Event,
) -> tokio::task::JoinHandle<()> {
    let wrapped = crate::adapters::SessionApiCrossCrateEvent::new(
        crate::adapters::sanitize_session_api_observation(&api_event),
    );
    tokio::spawn(async move {
        if let Err(error) = coordinator.publish_observational(wrapped).await {
            tracing::warn!(%error, "Failed to publish app-level dialog adapter event");
        }
    })
}

/// One immutable snapshot for every transaction-oriented standalone request.
///
/// MESSAGE, OPTIONS, and SUBSCRIBE intentionally remain outside the call
/// state machine. Keeping their request identity in this private enum lets the
/// coordinator share one authentication/retry implementation without
/// manufacturing compatibility sessions.
#[derive(Clone)]
pub(crate) enum StandaloneRequestOptions {
    Message(MessageRequestOptions),
    Options(OptionsRequestOptions),
    Subscribe {
        target: String,
        options: SubscribeRequestOptions,
    },
}

impl StandaloneRequestOptions {
    pub(crate) fn method(&self) -> rvoip_sip_core::Method {
        match self {
            Self::Message(_) => rvoip_sip_core::Method::Message,
            Self::Options(_) => rvoip_sip_core::Method::Options,
            Self::Subscribe { .. } => rvoip_sip_core::Method::Subscribe,
        }
    }

    pub(crate) fn request_uri(&self) -> &str {
        match self {
            Self::Message(options) => &options.to_uri,
            Self::Options(options) => &options.to_uri,
            Self::Subscribe { target, .. } => target,
        }
    }

    pub(crate) fn body(&self) -> Option<&[u8]> {
        match self {
            Self::Message(options) if !options.body.is_empty() => Some(options.body.as_ref()),
            _ => None,
        }
    }

    pub(crate) fn with_request_identity(
        mut self,
        cseq: u32,
        call_id: Option<String>,
        from_tag: Option<String>,
    ) -> Self {
        match &mut self {
            Self::Message(options) => {
                options.cseq = Some(cseq);
                options.call_id = call_id;
                options.from_tag = from_tag;
            }
            Self::Options(options) => {
                options.cseq = Some(cseq);
                options.call_id = call_id;
                options.from_tag = from_tag;
            }
            Self::Subscribe { options, .. } => {
                options.cseq = Some(cseq);
                options.call_id = call_id;
                options.from_tag = from_tag;
            }
        }
        self
    }
}

fn exact_response_method_class(method: &rvoip_sip_core::Method) -> &'static str {
    use rvoip_sip_core::Method;

    match method {
        Method::Invite => "INVITE",
        Method::Ack => "ACK",
        Method::Bye => "BYE",
        Method::Cancel => "CANCEL",
        Method::Register => "REGISTER",
        Method::Options => "OPTIONS",
        Method::Subscribe => "SUBSCRIBE",
        Method::Notify => "NOTIFY",
        Method::Update => "UPDATE",
        Method::Refer => "REFER",
        Method::Info => "INFO",
        Method::Message => "MESSAGE",
        Method::Prack => "PRACK",
        Method::Publish => "PUBLISH",
        Method::Extension(_) => "extension",
    }
}

fn exact_response_transaction_diagnostics(
    transaction_id: &TransactionKey,
) -> (&'static str, &'static str) {
    let direction = if transaction_id.is_server() {
        "server"
    } else {
        "client"
    };
    (
        exact_response_method_class(transaction_id.method()),
        direction,
    )
}

struct RegistrationRefreshTask {
    handle: SessionRegistryHandle,
    generation: u64,
    cancel: tokio::sync::oneshot::Sender<()>,
}

struct RegistrationRefreshCompletion {
    admission: Arc<StdMutex<()>>,
    tasks: Arc<DashMap<SessionId, RegistrationRefreshTask>>,
    handle: SessionRegistryHandle,
    generation: u64,
}

impl Drop for RegistrationRefreshCompletion {
    fn drop(&mut self) {
        let _admission = self
            .admission
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        self.tasks
            .remove_if(self.handle.session_id(), |_, current| {
                current.handle == self.handle && current.generation == self.generation
            });
    }
}

#[cfg(test)]
struct RegistrationRefreshDispatchPause {
    entered: std::sync::atomic::AtomicBool,
    entered_notify: tokio::sync::Notify,
    release: tokio::sync::Notify,
}

#[cfg(test)]
impl RegistrationRefreshDispatchPause {
    fn new() -> Self {
        Self {
            entered: std::sync::atomic::AtomicBool::new(false),
            entered_notify: tokio::sync::Notify::new(),
            release: tokio::sync::Notify::new(),
        }
    }

    async fn pause(&self) {
        self.entered.store(true, Ordering::Release);
        self.entered_notify.notify_waiters();
        self.release.notified().await;
    }

    async fn wait_entered(&self) {
        while !self.entered.load(Ordering::Acquire) {
            self.entered_notify.notified().await;
        }
    }

    fn release(&self) {
        self.release.notify_one();
    }
}

#[derive(Clone)]
struct DataMessageAuthChallenge {
    status: u16,
    value: String,
}

#[derive(Clone)]
struct OutboundByeTransaction {
    handle: SessionRegistryHandle,
    generation: u64,
    transaction_id: TransactionKey,
    /// Completion captured atomically with transaction creation. This exact
    /// authority remains valid after the manager retires the key-indexed
    /// transaction entry.
    completion: ClientTransactionCompletionHandle,
    /// Request-URI captured from the dialog remote target immediately before
    /// this generation is built. Local teardown owns the dialog from that
    /// point, so target-refresh requests are no longer admitted; retaining the
    /// value also keeps Digest retry independent of compact transaction
    /// tombstones, which intentionally do not retain non-INVITE request wire.
    request_uri: String,
}

/// Cancellation owner for the gap between BYE dispatch and exact response
/// confirmation. Terminal cleanup may preserve a completed receipt only while
/// at least one owner exists; dropping the last owner exact-removes any newer
/// generation so cancelled builder/adapter futures cannot retain it forever.
pub(crate) struct OutgoingByeWaitOwner {
    handle: SessionRegistryHandle,
    wait_intents: Arc<DashMap<SessionRegistryHandle, OutgoingByeWaitIntentState>>,
    transactions: Arc<DashMap<SessionRegistryHandle, OutboundByeTransaction>>,
    generation_watch: Arc<DashMap<SessionRegistryHandle, tokio::sync::watch::Sender<u64>>>,
}

#[derive(Clone)]
struct OutgoingByeWaitIntentState {
    handle: SessionRegistryHandle,
    owners: usize,
    min_after_generation: u64,
}

impl Drop for OutgoingByeWaitOwner {
    fn drop(&mut self) {
        use dashmap::mapref::entry::Entry;

        if let Entry::Occupied(mut entry) = self.wait_intents.entry(self.handle.clone()) {
            if entry.get().handle != self.handle {
                return;
            }
            if entry.get().owners > 1 {
                entry.get_mut().owners -= 1;
                return;
            }

            // Keep the per-session intent entry occupied through reclamation.
            // A new owner therefore cannot publish a later generation between
            // the last-owner decision and remove_if (the same-session ABA).
            let min_after_generation = entry.get().min_after_generation;
            let removed = self.transactions.remove_if(&self.handle, |_, current| {
                current.handle == self.handle && current.generation > min_after_generation
            });
            if removed.is_some() || !self.transactions.contains_key(&self.handle) {
                self.generation_watch.remove(&self.handle);
            }
            entry.remove();
        }
    }
}

enum OutgoingByeGenerationWake {
    UseExactOutcome(
        rvoip_sip_dialog::transaction::TransactionResult<Option<ClientTransactionOutcome>>,
    ),
    FollowNewerGeneration,
    RetryCurrentGeneration,
    CleanupInterrupted,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum OutgoingByeFinalDisposition {
    Confirmed,
    AuthenticationChallenge,
    PeerAlreadyTerminated,
    Rejected,
}

fn classify_outgoing_bye_final_response(status_code: u16) -> OutgoingByeFinalDisposition {
    match status_code {
        200..=299 => OutgoingByeFinalDisposition::Confirmed,
        401 | 407 => OutgoingByeFinalDisposition::AuthenticationChallenge,
        // RFC 3261 §15.1.1: a 481 response to BYE means the peer no
        // longer has the dialog, and the UAC MUST still consider the session
        // and dialog terminated. This is the ordinary result when two BYEs
        // cross and the peer completes its locally initiated teardown first.
        481 => OutgoingByeFinalDisposition::PeerAlreadyTerminated,
        _ => OutgoingByeFinalDisposition::Rejected,
    }
}

fn resolve_outgoing_bye_generation_wake(
    current_outcome: rvoip_sip_dialog::transaction::TransactionResult<
        Option<ClientTransactionOutcome>,
    >,
    newer_generation_exists: bool,
    generation_watch_closed: bool,
    retained_transaction_exists: bool,
) -> OutgoingByeGenerationWake {
    match current_outcome {
        current @ Ok(Some(_)) | current @ Err(_) => {
            OutgoingByeGenerationWake::UseExactOutcome(current)
        }
        Ok(None) if newer_generation_exists => OutgoingByeGenerationWake::FollowNewerGeneration,
        Ok(None) if generation_watch_closed && !retained_transaction_exists => {
            OutgoingByeGenerationWake::CleanupInterrupted
        }
        Ok(None) => OutgoingByeGenerationWake::RetryCurrentGeneration,
    }
}

/// Return whether exact cleanup must interrupt an incomplete local-BYE
/// confirmation. A terminal completion is the handoff receipt for the
/// retained hangup owner: response-driven cleanup can run before the sending
/// state-machine action unwinds, so removing that receipt here would make the
/// later waiter sleep until Timer F despite an already-recorded wire result.
fn outgoing_bye_cleanup_should_interrupt_waiter(
    current_outcome: rvoip_sip_dialog::transaction::TransactionResult<
        Option<ClientTransactionOutcome>,
    >,
    wait_intent_registered: bool,
) -> bool {
    matches!(current_outcome, Ok(None)) || !wait_intent_registered
}

fn data_message_auth_realm(selected: &crate::auth::ClientAuthHeader) -> String {
    if let Some(challenge) = selected.digest_challenge.as_ref() {
        return challenge.realm.clone();
    }

    match &selected.scheme {
        crate::auth::SipAuthScheme::Digest => "digest",
        crate::auth::SipAuthScheme::Bearer => "bearer",
        crate::auth::SipAuthScheme::Basic => "basic",
        crate::auth::SipAuthScheme::Aka => "aka",
        crate::auth::SipAuthScheme::Other(_) => "other",
    }
    .to_string()
}

/// Publish one retained-auth mutation while the caller owns this exact
/// session's state-machine lane.
///
/// The lane—not a snapshot revision—is the serialization authority for Digest
/// nonce counts and retained protection spaces. The generation-qualified
/// handle still rejects replacement lifetimes; callers must not invoke this
/// helper from a MESSAGE-lane-only or otherwise unowned context.
fn update_retained_auth_lane_owned_exact<R>(
    store: &SessionStore,
    handle: &SessionRegistryHandle,
    unavailable: &'static str,
    update: impl FnOnce(&mut crate::session_store::SessionState) -> Result<R>,
) -> Result<R> {
    store
        .update_session_exact_with(handle, None, update)
        .map_err(|_| SessionError::InvalidTransition(unavailable.to_string()))?
}

/// Capture a raw public session identifier once, wait on that exact cell's
/// signaling lane, and revalidate the same generation after the wait.
///
/// Executor actions must never call this helper: they already own the lane and
/// use the lane-owned dispatch variants below.
async fn lock_and_load_exact_current_session(
    store: &SessionStore,
    session_id: &SessionId,
) -> Option<(
    SessionRegistryHandle,
    tokio::sync::OwnedMutexGuard<()>,
    SessionState,
)> {
    let (handle, lane) = store.state_machine_lane(session_id)?;
    let guard = lane.lock_owned().await;
    let snapshot = store.get_session_snapshot_exact(&handle).ok()?;
    Some((handle, guard, snapshot.state().clone()))
}

fn resolve_dialog_for_handle_exact(
    store: &SessionStore,
    handle: &SessionRegistryHandle,
) -> Option<RvoipDialogId> {
    store
        .registry()
        .get_dialog_handle_exact(handle)
        .map(Into::into)
}

/// Resolve the canonical dialog while the caller owns this session's exact
/// state-machine lane. The state-local identity and registry mapping must name
/// the same dialog before any in-dialog wire operation is allowed.
fn resolve_dialog_for_lane_owned_session(
    store: &SessionStore,
    session: &SessionState,
) -> Result<RvoipDialogId> {
    let handle = session.lifecycle_handle.as_ref().ok_or_else(|| {
        SessionError::InvalidTransition(
            "SIP request exact session has no lifecycle authority".to_string(),
        )
    })?;
    if handle.session_id() != &session.session_id {
        return Err(SessionError::InvalidTransition(
            "SIP request lifecycle owner does not match its session".to_string(),
        ));
    }
    let dialog_id = resolve_dialog_for_handle_exact(store, handle).ok_or_else(|| {
        SessionError::InvalidTransition(
            "SIP request exact session has no current dialog".to_string(),
        )
    })?;
    let exact_dialog_id: crate::types::DialogId = dialog_id.clone().into();
    if session.dialog_id.as_ref() != Some(&exact_dialog_id) {
        return Err(SessionError::InvalidTransition(
            "SIP request exact dialog no longer owns its session".to_string(),
        ));
    }
    Ok(dialog_id)
}

/// Resolve one legacy Dialog-ID convenience call through the canonical exact
/// registry owner, then acquire and revalidate that owner's state-machine
/// lane. Every missing or stale owner is an error: compatibility entry points
/// must never report wire success when no exact dialog can be reached.
async fn lock_and_load_exact_legacy_dialog_session(
    store: &SessionStore,
    dialog_id: &RvoipDialogId,
) -> Result<(
    SessionRegistryHandle,
    tokio::sync::OwnedMutexGuard<()>,
    SessionState,
)> {
    let exact_dialog_id: crate::types::DialogId = dialog_id.clone().into();
    let handle = store
        .registry()
        .get_handle_by_dialog_exact(&exact_dialog_id)
        .ok_or_else(|| {
            SessionError::SessionNotFound(format!("No exact session owns dialog {}", dialog_id))
        })?;
    let lane = store.state_machine_lane_exact(&handle).ok_or_else(|| {
        SessionError::SessionNotFound(format!(
            "Exact session for dialog {} is no longer available",
            dialog_id
        ))
    })?;
    let guard = lane.lock_owned().await;
    let snapshot = store.get_session_snapshot_exact(&handle).map_err(|_| {
        SessionError::SessionNotFound(format!(
            "Exact session for dialog {} is no longer current",
            dialog_id
        ))
    })?;
    if store.registry().get_dialog_handle_exact(&handle) != Some(exact_dialog_id) {
        return Err(SessionError::InvalidTransition(format!(
            "Dialog {} no longer owns its exact session",
            dialog_id
        )));
    }
    Ok((handle, guard, snapshot.state().clone()))
}

/// Resolve and acquire the state-machine lane owned by one canonical exact
/// dialog mapping. The registry supplies the generation-qualified owner;
/// compatibility maps are deliberately not consulted. Revalidation after the
/// await prevents cleanup or raw-ID reuse from redirecting a queued attempt.
async fn lock_and_load_exact_data_message_session(
    store: &SessionStore,
    dialog_id: &RvoipDialogId,
) -> Result<(
    SessionRegistryHandle,
    tokio::sync::OwnedMutexGuard<()>,
    SessionState,
)> {
    let exact_dialog_id: crate::types::DialogId = dialog_id.clone().into();
    let handle = store
        .registry()
        .get_handle_by_dialog_exact(&exact_dialog_id)
        .ok_or_else(|| {
            SessionError::InvalidTransition(
                "SIP MESSAGE exact dialog has no owning session".to_string(),
            )
        })?;
    let lane = store.state_machine_lane_exact(&handle).ok_or_else(|| {
        SessionError::InvalidTransition(
            "SIP MESSAGE exact session is no longer available".to_string(),
        )
    })?;

    let guard = lane.lock_owned().await;
    let snapshot = store.get_session_snapshot_exact(&handle).map_err(|_| {
        SessionError::InvalidTransition(
            "SIP MESSAGE exact session is no longer available".to_string(),
        )
    })?;
    if store.registry().get_dialog_handle_exact(&handle).as_ref() != Some(&exact_dialog_id) {
        return Err(SessionError::InvalidTransition(
            "SIP MESSAGE exact dialog no longer owns its session".to_string(),
        ));
    }
    Ok((handle, guard, snapshot.state().clone()))
}

/// Select how the canonical in-dialog MESSAGE driver obtains session-state
/// authority.
///
/// Public/external callers capture an exact generation and let the driver
/// acquire that generation's lane for every wire attempt. State-machine
/// actions already own the lane, so they lend their working state directly
/// and must never try to reacquire it.
enum DataMessageStateLane<'a> {
    AcquireExact {
        expected_handle: Option<SessionRegistryHandle>,
    },
    AlreadyOwned(&'a mut SessionState),
}

enum DataMessageAttemptState<'a> {
    AcquiredExact {
        handle: SessionRegistryHandle,
        _guard: tokio::sync::OwnedMutexGuard<()>,
        session: Box<SessionState>,
    },
    AlreadyOwned {
        handle: SessionRegistryHandle,
        session: &'a mut SessionState,
    },
}

fn legacy_text_data_message(body: String) -> SipDataMessage {
    SipDataMessage {
        content_type: "text/plain".to_string(),
        bytes: bytes::Bytes::from(body),
        extra_headers: Vec::new(),
    }
}

#[derive(Clone, Copy)]
enum RetainedDialogAuthMode<'a> {
    Request,
    DataMessage {
        fresh_challenge: Option<&'a DataMessageAuthChallenge>,
    },
}

impl<'a> RetainedDialogAuthMode<'a> {
    fn fresh_challenge(self) -> Option<&'a DataMessageAuthChallenge> {
        match self {
            Self::Request => None,
            Self::DataMessage { fresh_challenge } => fresh_challenge,
        }
    }

    fn requires_active_dialog(self) -> bool {
        matches!(self, Self::DataMessage { .. })
    }

    fn dialog_ownership_error(self) -> &'static str {
        match self {
            Self::Request => "SIP request exact dialog no longer owns its session",
            Self::DataMessage { .. } => "SIP MESSAGE exact dialog no longer owns its session",
        }
    }

    fn missing_credentials_error(self) -> &'static str {
        match self {
            Self::Request => "SIP dialog retained a challenge without route credentials",
            Self::DataMessage { .. } => {
                "SIP MESSAGE dialog retained a challenge without route credentials"
            }
        }
    }

    fn challenge_mismatch_error(self) -> &'static str {
        match self {
            Self::Request => {
                "SIP request challenge no longer matches the exact dialog protection space"
            }
            Self::DataMessage { .. } => {
                "SIP MESSAGE challenge no longer matches the exact dialog protection space"
            }
        }
    }

    fn wire_validation_error(self) -> &'static str {
        match self {
            Self::Request => "SIP request authorization failed wire-safety validation",
            Self::DataMessage { .. } => "SIP MESSAGE authorization failed wire-safety validation",
        }
    }
}

struct RetainedDialogAuthRoute<'a> {
    next_hop: &'a str,
    transport: &'a crate::auth::SipTransportSecurityContext,
}

/// Re-author one exact dialog's retained origin/proxy protection spaces.
///
/// This is deliberately a pure working-state mutation: it performs no store,
/// lane, dialog, transaction, or transport I/O. Callers retain their current
/// ownership and lock ordering while sharing one standards-sensitive Digest
/// implementation. Credentials and nonce counts are copied first and are
/// published to `session` together only after every selected header passes
/// protection-space and wire-safety validation.
fn mutate_retained_dialog_auth(
    session: &mut SessionState,
    dialog_id: &RvoipDialogId,
    mode: RetainedDialogAuthMode<'_>,
    method: &str,
    request_uri: &str,
    route: RetainedDialogAuthRoute<'_>,
    body: Option<&[u8]>,
) -> Result<Vec<rvoip_sip_core::types::TypedHeader>> {
    use crate::session_store::state::{InviteAuthorizationCredential, InviteCredentialKind};
    let RetainedDialogAuthRoute {
        next_hop,
        transport,
    } = route;

    if session
        .dialog_id
        .as_ref()
        .is_none_or(|current| current.as_uuid() != &dialog_id.0)
    {
        return Err(SessionError::InvalidTransition(
            mode.dialog_ownership_error().to_string(),
        ));
    }
    if mode.requires_active_dialog()
        && (!session.dialog_established
            || session.call_state == crate::types::CallState::Terminating
            || session.call_state.is_final())
    {
        return Err(SessionError::InvalidTransition(
            "SIP MESSAGE exact dialog is no longer active".to_string(),
        ));
    }

    let fresh_challenge = mode.fresh_challenge();
    if session.invite_authorization_credentials.is_empty() && fresh_challenge.is_none() {
        return Ok(Vec::new());
    }

    let auth = session
        .auth
        .clone()
        .or_else(|| session.credentials.clone().map(Into::into))
        .ok_or_else(|| SessionError::AuthError(mode.missing_credentials_error().to_string()))?;
    let origin_target = session
        .remote_uri
        .clone()
        .unwrap_or_else(|| request_uri.to_string());
    let mut credentials = session.invite_authorization_credentials.clone();
    let mut digest_nc = session.digest_nc.clone();

    if let Some(fresh) = fresh_challenge {
        let kind = if fresh.status == 407 {
            InviteCredentialKind::Proxy
        } else {
            InviteCredentialKind::Origin
        };
        let preview = auth
            .authorization_for_challenge_with_transport_context(
                &fresh.value,
                method,
                request_uri,
                1,
                body,
                transport,
            )
            .map_err(|error| {
                crate::errors::redacted_outbound_auth_error(
                    crate::errors::OutboundAuthOperation::Request,
                    error,
                )
            })?;
        let realm = data_message_auth_realm(&preview);
        let nonce = preview
            .digest_challenge
            .as_ref()
            .map(|challenge| challenge.nonce.clone());
        let existing = credentials
            .iter()
            .position(|credential| credential.kind == kind && credential.realm == realm);
        if existing.is_none() && credentials.iter().any(|credential| credential.kind == kind) {
            return Err(SessionError::AuthError(
                "SIP MESSAGE challenge changed the exact dialog protection space".to_string(),
            ));
        }
        let (protection_target, stale_refreshes) = if let Some(index) = existing {
            let credential = &credentials[index];
            if !preview.stale || credential.nonce == nonce || credential.stale_refreshes >= 1 {
                return Err(SessionError::AuthError(
                    "SIP MESSAGE repeated a non-refreshing authentication challenge".to_string(),
                ));
            }
            (
                credential.protection_target.clone(),
                credential.stale_refreshes.saturating_add(1),
            )
        } else {
            if credentials.len() >= 8 {
                return Err(SessionError::AuthError(
                    "SIP MESSAGE authentication protection-space limit was reached".to_string(),
                ));
            }
            (
                if kind == InviteCredentialKind::Origin {
                    origin_target.clone()
                } else {
                    next_hop.to_string()
                },
                0,
            )
        };
        let credential = InviteAuthorizationCredential {
            kind,
            protection_target,
            challenge_raw: fresh.value.clone(),
            realm,
            nonce,
            stale_refreshes,
            value: String::new(),
        };
        if let Some(index) = existing {
            credentials[index] = credential;
        } else {
            credentials.push(credential);
        }
    }

    let mut headers = Vec::with_capacity(credentials.len());
    for credential in &mut credentials {
        let applies_to_exact_target = match credential.kind {
            InviteCredentialKind::Origin => credential.protection_target == origin_target,
            InviteCredentialKind::Proxy => credential.protection_target == next_hop,
        };
        if !applies_to_exact_target {
            continue;
        }
        let preview = auth
            .authorization_for_challenge_with_transport_context(
                &credential.challenge_raw,
                method,
                request_uri,
                1,
                body,
                transport,
            )
            .map_err(|error| {
                crate::errors::redacted_outbound_auth_error(
                    crate::errors::OutboundAuthOperation::Request,
                    error,
                )
            })?;
        if let Some(challenge) = preview.digest_challenge.as_ref() {
            if challenge.realm != credential.realm
                || credential.nonce.as_deref() != Some(challenge.nonce.as_str())
            {
                return Err(SessionError::AuthError(
                    mode.challenge_mismatch_error().to_string(),
                ));
            }
        }
        let nonce_count = if let Some(challenge) = preview.digest_challenge.as_ref() {
            let key = (challenge.realm.clone(), challenge.nonce.clone());
            *digest_nc
                .entry(key)
                .and_modify(|count| *count = count.saturating_add(1))
                .or_insert(1)
        } else {
            1
        };
        let selected = if preview.digest_challenge.is_some() && nonce_count != 1 {
            auth.authorization_for_challenge_with_transport_context(
                &credential.challenge_raw,
                method,
                request_uri,
                nonce_count,
                body,
                transport,
            )
            .map_err(|error| {
                crate::errors::redacted_outbound_auth_error(
                    crate::errors::OutboundAuthOperation::Request,
                    error,
                )
            })?
        } else {
            preview
        };
        credential.value = selected.value.clone();
        let name = match credential.kind {
            InviteCredentialKind::Origin => rvoip_sip_core::types::HeaderName::Authorization,
            InviteCredentialKind::Proxy => rvoip_sip_core::types::HeaderName::ProxyAuthorization,
        };
        headers.push(
            rvoip_sip_core::validation::validated_authorization_header(name, selected.value)
                .map_err(|_| SessionError::AuthError(mode.wire_validation_error().to_string()))?,
        );
    }

    session.invite_authorization_credentials = credentials;
    session.digest_nc = digest_nc;
    Ok(headers)
}

/// Apply retained MESSAGE authentication while the caller owns the exact
/// state-machine lane. The unauthenticated path validates against the local
/// lane-owned snapshot without publishing; credential or fresh-challenge
/// bookkeeping is committed through the narrow exact-cell updater.
#[allow(clippy::too_many_arguments)]
fn authorize_data_message_lane_owned_exact(
    store: &SessionStore,
    handle: &SessionRegistryHandle,
    session: &mut SessionState,
    dialog_id: &RvoipDialogId,
    request: &mut rvoip_sip_core::Request,
    next_hop: &str,
    fresh_challenge: Option<&DataMessageAuthChallenge>,
    transport: &crate::auth::SipTransportSecurityContext,
) -> Result<()> {
    let request_uri = request.uri.to_string();
    let body = Some(request.body.as_ref());
    let authorize = |target: &mut SessionState| {
        mutate_retained_dialog_auth(
            target,
            dialog_id,
            RetainedDialogAuthMode::DataMessage { fresh_challenge },
            "MESSAGE",
            &request_uri,
            RetainedDialogAuthRoute {
                next_hop,
                transport,
            },
            body,
        )
    };
    let headers =
        if !session.invite_authorization_credentials.is_empty() || fresh_challenge.is_some() {
            update_retained_auth_lane_owned_exact(
                store,
                handle,
                "SIP MESSAGE exact session changed during authentication",
                authorize,
            )?
        } else {
            authorize(session)?
        };
    request.headers.extend(headers);
    Ok(())
}

/// Publish the exact lower-layer dialog identity before the initial INVITE is
/// allowed onto the wire.
///
/// A loopback peer can answer synchronously during dispatch.  The response
/// handler must therefore never be able to clone a session revision whose
/// exact registry mapping is installed but whose state-local `dialog_id` is
/// still empty.  Publishing here closes that gap; the ordinary state-machine
/// action later observes and republishes the same identity.
fn publish_initial_invite_dialog_exact(
    store: &SessionStore,
    handle: &SessionRegistryHandle,
    dialog_id: &RvoipDialogId,
) -> Result<()> {
    let session_dialog_id: crate::types::DialogId = dialog_id.clone().into();
    let registry_dialog_id = store.registry().get_dialog_handle_exact(handle);
    match store.update_session_exact_with(handle, None, |session| -> Result<()> {
        match (session.dialog_id.as_ref(), registry_dialog_id.as_ref()) {
            (Some(current), _) if current == &session_dialog_id => return Ok(()),
            // Redirect cleanup retires the old registry owner inside the same
            // executor transition before this replacement INVITE is
            // dispatched. The store still contains the transition's
            // pre-commit dialog snapshot, so replace it only when the exact
            // registry already proves the new owner.
            (Some(_), Some(registry)) if registry == &session_dialog_id => {}
            (Some(_), _) => {
                return Err(SessionError::InvalidTransition(
                    "initial INVITE exact dialog changed before wire dispatch".to_string(),
                ));
            }
            (None, _) => {}
        }
        session.dialog_id = Some(session_dialog_id);
        Ok(())
    }) {
        Ok(result) => result,
        Err(_) => Err(SessionError::InternalError(
            "initial INVITE exact dialog publication failed (class=lifecycle)".to_string(),
        )),
    }
}

/// Resolve the dialog owned by the current exact session lifetime.
///
/// INVITE retries are responses to an already-installed initial transaction,
/// so the registry mapping is authoritative and must already exist. Capturing
/// the generation-qualified handle before the synchronous exact lookup makes
/// raw-ID reuse unable to redirect a retry to another call.
fn resolve_exact_invite_retry_dialog(
    store: &SessionStore,
    session_id: &SessionId,
) -> Result<RvoipDialogId> {
    let handle = store
        .lifecycle_handle(session_id)
        .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?;
    resolve_dialog_for_handle_exact(store, &handle)
        .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))
}

#[derive(Clone)]
struct OutboundInitialInviteBinding {
    handle: SessionRegistryHandle,
    owner: InitialInviteOwner,
    resource: Weak<OutboundInitialInviteResource>,
}

#[derive(Clone)]
struct OutboundInviteTransaction {
    handle: SessionRegistryHandle,
    dialog_id: RvoipDialogId,
    transaction_id: TransactionKey,
}

impl OutboundInviteTransaction {
    fn matches(&self, handle: &SessionRegistryHandle, dialog_id: &RvoipDialogId) -> bool {
        self.handle == *handle && self.dialog_id == *dialog_id
    }
}

impl OutboundInitialInviteBinding {
    fn matches(&self, handle: &SessionRegistryHandle, owner: &InitialInviteOwner) -> bool {
        self.handle == *handle && self.owner == *owner
    }
}

/// Exact lower-layer ownership retained by the session lifecycle authority.
///
/// The remaining raw-ID transaction and resource trackers carry an exact
/// handle beside every value, fencing every mutation and rollback. The weak
/// self-reference lets explicit CANCEL/BYE paths mark protocol teardown
/// without creating a resource/map reference cycle.
struct OutboundInitialInviteResource {
    dialog_api: Arc<UnifiedDialogApi>,
    store: Arc<SessionStore>,
    registry: Arc<SessionRegistry>,
    handle: SessionRegistryHandle,
    owner: InitialInviteOwner,
    bindings: Arc<DashMap<SessionId, OutboundInitialInviteBinding>>,
    outgoing_invite_tx: Arc<DashMap<SessionId, OutboundInviteTransaction>>,
    phase: AtomicU8,
    protocol_teardown_owned_by_upper: AtomicBool,
    state_dialog_published: AtomicBool,
    registry_map_installed: AtomicBool,
    transaction_map_installed: AtomicBool,
}

/// Deterministic SIP Call-ID used by every outbound dialog construction path.
/// Media routing may derive its lookup key before dialog-core returns, so this
/// function is the single source of truth shared with the adapter layer.
pub(crate) fn deterministic_outbound_call_id(session_id: &SessionId) -> String {
    format!("{}@rvoip-sip", session_id.0)
}

/// Registrar metadata returned on a successful REGISTER 2xx response.
#[derive(Debug, Clone, Default)]
pub(crate) struct RegistrationResponseMetadata {
    pub(crate) service_route: Option<Vec<String>>,
    pub(crate) pub_gruu: Option<String>,
    pub(crate) temp_gruu: Option<String>,
    /// Exact flow-bearing route used by the successful REGISTER attempt.
    pub(crate) transport_route: Option<rvoip_sip_transport::TransportRoute>,
}

/// Outcome for a single REGISTER wire attempt.
///
/// This deliberately does not encode state-machine lifecycle decisions. The
/// dialog adapter sends one request, parses one response, and returns the SIP
/// result; the state-machine action decides which internal event to enqueue.
#[derive(Debug, Clone)]
pub(crate) enum RegisterAttemptOutcome {
    Registered {
        accepted_expires: u32,
        metadata: RegistrationResponseMetadata,
    },
    Unregistered,
    AuthChallenge {
        status_code: u16,
        challenge: String,
    },
    IntervalTooBrief {
        min_expires: u32,
    },
    Failure {
        status_code: u16,
        reason: String,
    },
}

/// Dialog-owned REGISTER mechanics returned to the state-machine lane after
/// one wire attempt.
///
/// This is not a second stored projection. It is an input/output value for a
/// single dialog operation: the action captures it from its lane-owned
/// `SessionState`, dialog code advances Call-ID/CSeq, Digest nonce-count, and
/// the response transport context, and the action applies it back to that same
/// working state before the executor's canonical commit.
#[derive(Clone)]
pub(crate) struct RegisterAttemptContext {
    registration_call_id: Option<String>,
    registration_cseq: u32,
    auth_challenge_raw: Option<String>,
    auth_challenge: Option<crate::auth::DigestChallenge>,
    pending_auth_transport: Option<crate::auth::SipTransportSecurityContext>,
    pending_auth_status: Option<u16>,
    digest_nc: std::collections::HashMap<(String, String), u32>,
}

impl RegisterAttemptContext {
    pub(crate) fn capture(session: &SessionState) -> Self {
        Self {
            registration_call_id: session.registration_call_id.clone(),
            registration_cseq: session.registration_cseq,
            auth_challenge_raw: session.auth_challenge_raw.clone(),
            auth_challenge: session.auth_challenge.clone(),
            pending_auth_transport: session.pending_auth_transport.clone(),
            pending_auth_status: session.pending_auth.as_ref().map(|(status, _)| *status),
            digest_nc: session.digest_nc.clone(),
        }
    }

    pub(crate) fn apply(self, session: &mut SessionState) {
        session.registration_call_id = self.registration_call_id;
        session.registration_cseq = self.registration_cseq;
        session.pending_auth_transport = self.pending_auth_transport;
        session.digest_nc = self.digest_nc;
    }
}

/// Result of one REGISTER wire attempt, including the dialog-owned mechanics
/// that the caller must fold into its lane-owned working state.
pub(crate) struct RegisterAttemptResult {
    pub(crate) outcome: RegisterAttemptOutcome,
    pub(crate) context: RegisterAttemptContext,
    /// Exact request snapshot written for this attempt. The state-machine
    /// retains it across 401/407 and 423 so every retry preserves application
    /// headers, routing, registration identity, and refresh intent.
    pub(crate) request_options: RegisterRequestOptions,
}

/// Non-state side effects admitted only after the executor commits the
/// registration outcome. Observer callbacks and refresh timers therefore
/// cannot observe the pre-outcome session snapshot.
#[derive(Debug, Clone)]
pub(crate) enum RegistrationPostCommitEffect {
    Registered {
        registrar_uri: String,
        from_uri: String,
        contact_uri: String,
        accepted_expires: u32,
        next_refresh_at: Option<Instant>,
        transport_route: Option<rvoip_sip_transport::TransportRoute>,
    },
    Unregistered {
        registrar_uri: String,
    },
    RegistrationFailed {
        registrar_uri: String,
        status_code: u16,
        failure_summary: String,
    },
    UnregistrationFailed {
        registrar_uri: String,
        reason: String,
    },
}

struct RegistrationSuccessStateInput<'a> {
    registrar_uri: &'a str,
    from_uri: &'a str,
    contact_uri: &'a str,
    accepted_expires: u32,
    now: Instant,
    next_refresh_at: Option<Instant>,
    metadata: RegistrationResponseMetadata,
}

fn record_registration_success_state(
    session: &mut SessionState,
    input: RegistrationSuccessStateInput<'_>,
) -> RegistrationPostCommitEffect {
    let RegistrationSuccessStateInput {
        registrar_uri,
        from_uri,
        contact_uri,
        accepted_expires,
        now,
        next_refresh_at,
        metadata,
    } = input;
    session.is_registered = true;
    session.registration_expires = Some(accepted_expires);
    session.registration_accepted_expires = Some(accepted_expires);
    session.registration_registered_at = Some(now);
    session.registration_next_refresh_at = next_refresh_at;
    session.registration_last_failure = None;
    session.registration_retry_count = 0;
    session.registration_service_route = metadata.service_route;
    session.registration_pub_gruu = metadata.pub_gruu;
    session.registration_temp_gruu = metadata.temp_gruu;

    RegistrationPostCommitEffect::Registered {
        registrar_uri: registrar_uri.to_string(),
        from_uri: from_uri.to_string(),
        contact_uri: contact_uri.to_string(),
        accepted_expires,
        next_refresh_at,
        transport_route: metadata.transport_route,
    }
}

fn record_unregistration_success_state(
    session: &mut SessionState,
    registrar_uri: &str,
) -> RegistrationPostCommitEffect {
    session.is_registered = false;
    session.registration_accepted_expires = None;
    session.registration_registered_at = None;
    session.registration_next_refresh_at = None;
    session.registration_last_failure = None;
    session.registration_retry_count = 0;
    session.registration_service_route = None;
    session.registration_pub_gruu = None;
    session.registration_temp_gruu = None;

    RegistrationPostCommitEffect::Unregistered {
        registrar_uri: registrar_uri.to_string(),
    }
}

fn record_registration_failure_state(
    session: &mut SessionState,
    registrar_uri: &str,
    status_code: u16,
    reason: String,
) -> RegistrationPostCommitEffect {
    let failure_summary = if session.registration_retry_count > 0 {
        format!(
            "{} after {} retry attempt(s)",
            reason, session.registration_retry_count
        )
    } else {
        reason
    };
    session.is_registered = false;
    session.registration_accepted_expires = None;
    session.registration_registered_at = None;
    session.registration_next_refresh_at = None;
    session.registration_last_failure = Some(failure_summary.clone());
    session.registration_service_route = None;
    session.registration_pub_gruu = None;
    session.registration_temp_gruu = None;

    RegistrationPostCommitEffect::RegistrationFailed {
        registrar_uri: registrar_uri.to_string(),
        status_code,
        failure_summary,
    }
}

fn record_unregistration_failure_state(
    session: &mut SessionState,
    registrar_uri: &str,
    reason: String,
) -> RegistrationPostCommitEffect {
    session.is_registered = false;
    session.registration_accepted_expires = None;
    session.registration_registered_at = None;
    session.registration_next_refresh_at = None;
    session.registration_last_failure = Some(reason.clone());
    session.registration_retry_count = 0;
    session.registration_service_route = None;
    session.registration_pub_gruu = None;
    session.registration_temp_gruu = None;

    RegistrationPostCommitEffect::UnregistrationFailed {
        registrar_uri: registrar_uri.to_string(),
        reason,
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum InviteDispatchFailure {
    Initial,
    InitialWithExtraHeaders,
    InitialWithOptions,
    AuthRetry,
    SessionTimerRetry,
    ReinviteWithOptions,
}

impl InviteDispatchFailure {
    fn diagnostic(self) -> &'static str {
        match self {
            Self::Initial => "Failed to make call (class=invite-dispatch)",
            Self::InitialWithExtraHeaders => {
                "Failed to make call with extra headers (class=invite-dispatch)"
            }
            Self::InitialWithOptions => {
                "Failed to send INVITE with options (class=dialog-dispatch)"
            }
            Self::AuthRetry => "resend_invite_with_auth failed (class=invite-auth-retry)",
            Self::SessionTimerRetry => {
                "resend_invite_with_session_timer_override failed (class=invite-timer-retry)"
            }
            Self::ReinviteWithOptions => {
                "Failed to send re-INVITE with options (class=invite-dispatch)"
            }
        }
    }
}

fn redacted_invite_dispatch_error<E>(failure: InviteDispatchFailure, _source: E) -> SessionError {
    // Dialog-layer failures can retain a parser or validation source
    // containing caller-owned URI/header/auth material. Preserve only the
    // operation and fixed failure class at this public wrapper.
    SessionError::DialogError(failure.diagnostic().to_string())
}

fn redacted_dialog_operation_error<E>(operation: &'static str, _source: E) -> SessionError {
    SessionError::DialogError(format!("{operation} failed (class=dialog-dispatch)"))
}

fn register_auth_scheme_class(scheme: &crate::auth::SipAuthScheme) -> &'static str {
    match scheme {
        crate::auth::SipAuthScheme::Digest => "digest",
        crate::auth::SipAuthScheme::Bearer => "bearer",
        crate::auth::SipAuthScheme::Basic => "basic",
        crate::auth::SipAuthScheme::Aka => "aka",
        crate::auth::SipAuthScheme::Other(_) => "other",
    }
}

impl OutboundInitialInviteResource {
    fn new(
        adapter: &DialogAdapter,
        handle: SessionRegistryHandle,
        owner: InitialInviteOwner,
    ) -> Arc<Self> {
        Arc::new(Self {
            dialog_api: Arc::clone(&adapter.dialog_api),
            store: Arc::clone(&adapter.store),
            registry: Arc::clone(adapter.store.registry()),
            handle,
            owner,
            bindings: Arc::clone(&adapter.outbound_initial_invites),
            outgoing_invite_tx: Arc::clone(&adapter.outgoing_invite_tx),
            phase: AtomicU8::new(OWNED_INVITE_INSTALLED),
            protocol_teardown_owned_by_upper: AtomicBool::new(false),
            state_dialog_published: AtomicBool::new(false),
            registry_map_installed: AtomicBool::new(false),
            transaction_map_installed: AtomicBool::new(false),
        })
    }

    fn install_adapter_bindings(self: &Arc<Self>) -> std::result::Result<(), &'static str> {
        use dashmap::mapref::entry::Entry;

        let session_id = self.handle.session_id().clone();
        match self.bindings.entry(session_id.clone()) {
            Entry::Vacant(entry) => {
                entry.insert(OutboundInitialInviteBinding {
                    handle: self.handle.clone(),
                    owner: self.owner.clone(),
                    resource: Arc::downgrade(self),
                });
            }
            Entry::Occupied(_) => return Err("exact outbound INVITE binding already exists"),
        }

        self.registry
            .install_dialog_identity_handle(
                &self.handle,
                self.owner.dialog_id().clone().into(),
                self.owner.call_id().to_string(),
            )
            .map_err(|_| "exact session registry dialog mapping failed")?;
        self.registry_map_installed.store(true, Ordering::Release);
        Ok(())
    }

    fn record_state_dialog_published(&self) {
        self.state_dialog_published.store(true, Ordering::Release);
    }

    fn record_wire_outcome(&self, outcome: InitialInviteWireOutcome) {
        let phase = match outcome {
            InitialInviteWireOutcome::ZeroWire => OWNED_INVITE_ZERO_WIRE,
            InitialInviteWireOutcome::Sent => OWNED_INVITE_SENT,
            InitialInviteWireOutcome::Unknown => OWNED_INVITE_WIRE_UNKNOWN,
        };
        self.phase.store(phase, Ordering::Release);
    }

    fn install_transaction(&self, transaction_id: TransactionKey) -> bool {
        use dashmap::mapref::entry::Entry;

        let session_id = self.handle.session_id().clone();
        if !self
            .bindings
            .get(&session_id)
            .is_some_and(|binding| binding.matches(&self.handle, &self.owner))
        {
            return false;
        }
        match self.outgoing_invite_tx.entry(session_id) {
            Entry::Vacant(entry) => {
                entry.insert(OutboundInviteTransaction {
                    handle: self.handle.clone(),
                    dialog_id: self.owner.dialog_id().clone(),
                    transaction_id,
                });
                self.transaction_map_installed
                    .store(true, Ordering::Release);
                true
            }
            Entry::Occupied(_) => false,
        }
    }

    fn mark_protocol_teardown_owned_by_upper(&self) {
        self.protocol_teardown_owned_by_upper
            .store(true, Ordering::Release);
    }

    // The arguments are an immutable teardown snapshot. Keeping them flat
    // makes the retained cleanup task independent of the owning guard.
    #[allow(clippy::too_many_arguments)]
    async fn release_exact(
        dialog_api: Arc<UnifiedDialogApi>,
        store: Arc<SessionStore>,
        registry: Arc<SessionRegistry>,
        handle: SessionRegistryHandle,
        owner: InitialInviteOwner,
        bindings: Arc<DashMap<SessionId, OutboundInitialInviteBinding>>,
        outgoing_invite_tx: Arc<DashMap<SessionId, OutboundInviteTransaction>>,
        phase: u8,
        protocol_teardown_owned_by_upper: bool,
        state_dialog_published: bool,
        registry_map_installed: bool,
        transaction_map_installed: bool,
    ) -> std::result::Result<(), ManagedResourceReleaseError> {
        let retained = dialog_api.initial_invite_owner_is_retained(&owner);
        if retained {
            match phase {
                OWNED_INVITE_INSTALLED => {
                    let _ = dialog_api.compensate_initial_invite(&owner).await;
                }
                OWNED_INVITE_SENT => {
                    let active = dialog_api
                        .list_active_dialogs()
                        .await
                        .iter()
                        .any(|dialog_id| dialog_id == owner.dialog_id());
                    // A peer-originated BYE can retire the dialog before this
                    // exact resource release runs. Missing from the manager's
                    // active-dialog index is then a confirmed terminal
                    // condition, not an uncertain sent INVITE that needs a
                    // synthetic BYE/CANCEL supervisor. If the dialog races
                    // away between the index read and state read, recheck the
                    // authoritative index; a state-read failure on a still-
                    // live dialog remains fail-closed.
                    let terminal = if !active {
                        true
                    } else {
                        match dialog_api.get_dialog_state(owner.dialog_id()).await {
                            Ok(DialogState::Terminated) => true,
                            Ok(_) => false,
                            Err(_) => !dialog_api
                                .list_active_dialogs()
                                .await
                                .iter()
                                .any(|dialog_id| dialog_id == owner.dialog_id()),
                        }
                    };
                    if protocol_teardown_owned_by_upper || terminal {
                        let _ = dialog_api.finish_initial_invite_teardown(&owner).await;
                    } else {
                        let _ = dialog_api.supervise_initial_invite_teardown(&owner);
                    }
                }
                OWNED_INVITE_WIRE_UNKNOWN => {
                    let _ = dialog_api.supervise_initial_invite_teardown(&owner);
                }
                OWNED_INVITE_ZERO_WIRE => {
                    let _ = dialog_api.compensate_initial_invite(&owner).await;
                }
                _ => return Err(ManagedResourceReleaseError::new("invite-phase-invalid")),
            }
        }

        if dialog_api.initial_invite_owner_is_retained(&owner) {
            let deadline = tokio::time::Instant::now() + INITIAL_INVITE_PROTOCOL_DRAIN_TIMEOUT;
            loop {
                if !dialog_api.initial_invite_owner_is_retained(&owner) {
                    break;
                }
                if tokio::time::Instant::now() >= deadline {
                    return Err(ManagedResourceReleaseError::new(
                        "invite-protocol-teardown-pending",
                    ));
                }
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        }

        let session_id = handle.session_id().clone();
        let binding_matches = bindings
            .get(&session_id)
            .is_some_and(|binding| binding.matches(&handle, &owner));
        if !binding_matches {
            return Ok(());
        }

        if state_dialog_published
            && store
                .clear_dialog_session_retained_exact(&handle, &owner.dialog_id().clone().into())
                .is_err()
        {
            return Err(ManagedResourceReleaseError::new(
                "invite-session-dialog-release-failed",
            ));
        }

        if registry_map_installed {
            match registry.clear_dialog_handle_retained(&handle, owner.dialog_id().clone().into()) {
                Ok(_)
                | Err(SessionRegistryError::SlotMissing)
                | Err(SessionRegistryError::RevisionMismatch) => {}
                Err(_) => {
                    return Err(ManagedResourceReleaseError::new(
                        "invite-registry-release-failed",
                    ));
                }
            }
        }

        if bindings
            .remove_if(&session_id, |_, binding| binding.matches(&handle, &owner))
            .is_none()
        {
            return Ok(());
        }

        if transaction_map_installed {
            outgoing_invite_tx.remove_if(&session_id, |_, transaction| {
                transaction.matches(&handle, owner.dialog_id())
            });
        }
        Ok(())
    }
}

impl ManagedSessionResource for OutboundInitialInviteResource {
    fn descriptor(&self) -> ResourceDescriptor {
        ResourceDescriptor::new("sip-initial-invite", self.owner.dialog_id().to_string())
    }

    fn cancel(&self) {
        // The authority's owned operation/dispatch supervisors remain retained
        // across caller cancellation. Phase-specific protocol work belongs in
        // the async release path where its outcome can be observed.
    }

    fn release(
        &self,
    ) -> std::pin::Pin<
        Box<
            dyn std::future::Future<Output = std::result::Result<(), ManagedResourceReleaseError>>
                + Send
                + 'static,
        >,
    > {
        let dialog_api = Arc::clone(&self.dialog_api);
        let store = Arc::clone(&self.store);
        let registry = Arc::clone(&self.registry);
        let handle = self.handle.clone();
        let owner = self.owner.clone();
        let bindings = Arc::clone(&self.bindings);
        let outgoing_invite_tx = Arc::clone(&self.outgoing_invite_tx);
        let phase = self.phase.load(Ordering::Acquire);
        let protocol_teardown_owned_by_upper = self
            .protocol_teardown_owned_by_upper
            .load(Ordering::Acquire);
        let state_dialog_published = self.state_dialog_published.load(Ordering::Acquire);
        let registry_map_installed = self.registry_map_installed.load(Ordering::Acquire);
        let transaction_map_installed = self.transaction_map_installed.load(Ordering::Acquire);
        Box::pin(Self::release_exact(
            dialog_api,
            store,
            registry,
            handle,
            owner,
            bindings,
            outgoing_invite_tx,
            phase,
            protocol_teardown_owned_by_upper,
            state_dialog_published,
            registry_map_installed,
            transaction_map_installed,
        ))
    }
}

async fn rollback_owned_invite<T>(
    operation: OwnedOperation,
    value: T,
) -> OwnedOperationCompletion<T> {
    operation
        .rollback(value)
        .await
        .unwrap_or_else(|_| panic!("initial INVITE exact rollback failed"))
}

async fn commit_owned_invite<T>(
    operation: OwnedOperation,
    value: T,
) -> OwnedOperationCompletion<T> {
    match operation.commit() {
        Ok(committed) => committed.complete(value),
        Err(failure) => rollback_owned_invite(failure.into_operation(), value).await,
    }
}

/// Minimal dialog adapter - just translates between dialog-core and state machine
pub struct DialogAdapter {
    /// Dialog-core unified API
    pub(crate) dialog_api: Arc<UnifiedDialogApi>,

    /// Session store for updating IDs
    pub(crate) store: Arc<SessionStore>,

    /// Generation-qualified outgoing INVITE transaction ownership retained for
    /// automatic ACK correlation and exact response cleanup.
    outgoing_invite_tx: Arc<DashMap<SessionId, OutboundInviteTransaction>>,

    /// Latest in-dialog BYE transaction for each exact live session. The
    /// generation lets a 401/407-driven retry supersede the challenged
    /// transaction without a late initial dispatch overwriting it.
    outgoing_bye_tx: Arc<DashMap<SessionRegistryHandle, OutboundByeTransaction>>,
    /// Exact per-session generation notification. Authentication retries wake
    /// the owning BYE waiter directly instead of requiring 10 ms polling.
    outgoing_bye_generation_watch:
        Arc<DashMap<SessionRegistryHandle, tokio::sync::watch::Sender<u64>>>,
    /// Number of cancellation owners spanning dispatch through confirmation.
    /// A terminal receipt is preserved across response-driven cleanup only
    /// while this exact session has at least one such owner.
    outgoing_bye_wait_intents: Arc<DashMap<SessionRegistryHandle, OutgoingByeWaitIntentState>>,
    next_outgoing_bye_generation: Arc<AtomicU64>,
    /// Timer F / configured non-INVITE transaction horizon used by the
    /// retained local-BYE cleanup owner.
    non_invite_transaction_timeout: Duration,

    /// Exact in-dialog request ownership for methods whose builder futures
    /// return after first transport write while authentication/final response
    /// arrives asynchronously.
    pub(crate) outbound_request_tracker: OutboundInDialogRequestTracker,

    /// Exact owner for each staged outbound initial INVITE.
    outbound_initial_invites: Arc<DashMap<SessionId, OutboundInitialInviteBinding>>,

    /// FIFO serialization for reliable-ordered SIP DataMessages. A lane is
    /// scoped to an exact dialog ID and removed by exact dialog cleanup.
    data_message_dispatch_lanes: Arc<SipDataMessageDispatchLanes>,

    /// SIP_API_DESIGN_2 §7.4 — application-supplied headers stamped on
    /// every outbound message the state machine emits automatically
    /// (auto-BYE on session-timer expiry, auto-CANCEL on
    /// dialog-terminated-during-INVITE, auto-NOTIFY on REFER
    /// completion). Populated at construction from
    /// [`crate::Config::auto_emit_extra_headers`]; empty by default.
    pub(crate) auto_emit_extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,

    /// Global event coordinator for publishing events
    pub(crate) global_coordinator: Arc<GlobalEventCoordinator>,

    /// State machine reference for triggering events (needed for REGISTER
    /// response handling). Wired post-construction via
    /// [`DialogAdapter::init_state_machine`] because the `StateMachine`
    /// transitively depends on this adapter — classic circular init. The
    /// `OnceLock` makes the initialization soundly observable by any task
    /// without requiring `&mut self`.
    pub(crate) state_machine: Arc<std::sync::OnceLock<Arc<crate::state_machine::StateMachine>>>,

    /// RFC 3261 §8.1.2 outbound proxy URI, validated at construction. When
    /// `Some`, `send_invite_with_extra_headers` prepends a `Route:
    /// <proxy-uri;lr>` header so dialog-initiating requests traverse the
    /// configured proxy. `None` → no Route pre-loading. Populated from
    /// [`crate::Config::outbound_proxy_uri`] during coordinator setup.
    pub(crate) outbound_proxy_uri: Option<rvoip_sip_core::types::uri::Uri>,

    /// RFC 5626 §4 outbound registration params (`+sip.instance` URN +
    /// `reg-id`) applied to REGISTER Contact headers, together with the
    /// `;ob` URI flag. `None` → pre-5626 behaviour. Populated at
    /// construction from
    /// [`crate::Config::sip_outbound_enabled`]+[`crate::Config::sip_instance`].
    pub(crate) outbound_contact_params:
        Option<rvoip_sip_core::types::outbound::OutboundContactParams>,

    /// Symmetric registered-flow keep-alive identity. Unlike RFC 5626 mode,
    /// this starts after REGISTER success even if the registrar does not echo
    /// outbound Contact parameters.
    pub(crate) symmetric_flow_params:
        Option<rvoip_sip_core::types::outbound::OutboundContactParams>,

    /// Automatic registration refresh settings and task registry.
    registration_auto_refresh: bool,
    registration_refresh_jitter_percent: u8,
    registration_refresh_admission: Arc<StdMutex<()>>,
    registration_refresh_tasks: Arc<DashMap<SessionId, RegistrationRefreshTask>>,
    registration_refresh_retained: Arc<RetainedTasks>,
    next_registration_refresh_generation: Arc<AtomicU64>,
    #[cfg(test)]
    registration_refresh_dispatch_pause:
        Arc<StdMutex<Option<Arc<RegistrationRefreshDispatchPause>>>>,

    /// Perf diagnostics for dialog mapping cleanup balance.
    cleanup_attempt_total: Arc<AtomicU64>,
    cleanup_mapped_total: Arc<AtomicU64>,
    cleanup_missing_total: Arc<AtomicU64>,
    cleanup_outgoing_invite_removed_total: Arc<AtomicU64>,

    /// SIP_API_DESIGN_2 §12.4 — pluggable trace-output redactor. When
    /// `Some`, the trace path consults this hook before emitting each
    /// header to the trace sink so PII / carrier tokens can be
    /// scrubbed without affecting the wire form. Populated at
    /// construction from
    /// [`crate::Config::trace_redaction`]; `None` resolves to the
    /// production-safe default policy before construction. See
    /// [`crate::TraceRedactor`] for the policy contract.
    pub(crate) trace_redactor: Option<Arc<dyn crate::api::trace_redactor::TraceRedactor>>,
}

impl DialogAdapter {
    /// Create a new dialog adapter.
    ///
    /// `outbound_proxy_uri` is the RFC 3261 §8.1.2 outbound proxy, if any.
    /// Pass `None` for no pre-loaded Route. When `Some`, the URI MUST parse
    /// as a valid SIP URI — typically `sip:sbc.example.com;lr`.
    ///
    /// `outbound_contact_params` is the RFC 5626 §4 instance + reg-id pair
    /// attached to REGISTER Contact headers when outbound registration is
    /// enabled. Pass `None` for pre-5626 REGISTER Contact shape.
    // Preserve the established public constructor while the builder API is
    // introduced separately.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        dialog_api: Arc<UnifiedDialogApi>,
        store: Arc<SessionStore>,
        global_coordinator: Arc<GlobalEventCoordinator>,
        outbound_proxy_uri: Option<rvoip_sip_core::types::uri::Uri>,
        outbound_contact_params: Option<rvoip_sip_core::types::outbound::OutboundContactParams>,
        symmetric_flow_params: Option<rvoip_sip_core::types::outbound::OutboundContactParams>,
        registration_auto_refresh: bool,
        registration_refresh_jitter_percent: u8,
        auto_emit_extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
        trace_redactor: Option<Arc<dyn crate::api::trace_redactor::TraceRedactor>>,
    ) -> Self {
        let non_invite_transaction_timeout = dialog_api
            .dialog_manager()
            .core()
            .transaction_manager()
            .timer_settings()
            .transaction_timeout;
        Self {
            dialog_api,
            store,
            outgoing_invite_tx: Arc::new(DashMap::new()),
            outgoing_bye_tx: Arc::new(DashMap::new()),
            outgoing_bye_generation_watch: Arc::new(DashMap::new()),
            outgoing_bye_wait_intents: Arc::new(DashMap::new()),
            next_outgoing_bye_generation: Arc::new(AtomicU64::new(1)),
            non_invite_transaction_timeout,
            outbound_request_tracker: OutboundInDialogRequestTracker::new(
                non_invite_transaction_timeout,
            ),
            outbound_initial_invites: Arc::new(DashMap::new()),
            data_message_dispatch_lanes: Arc::new(SipDataMessageDispatchLanes::default()),
            auto_emit_extra_headers,
            global_coordinator,
            state_machine: Arc::new(std::sync::OnceLock::new()),
            outbound_proxy_uri,
            outbound_contact_params,
            symmetric_flow_params,
            registration_auto_refresh,
            registration_refresh_jitter_percent,
            registration_refresh_admission: Arc::new(StdMutex::new(())),
            registration_refresh_tasks: Arc::new(DashMap::new()),
            registration_refresh_retained: RetainedTasks::new(),
            next_registration_refresh_generation: Arc::new(AtomicU64::new(1)),
            #[cfg(test)]
            registration_refresh_dispatch_pause: Arc::new(StdMutex::new(None)),
            cleanup_attempt_total: Arc::new(AtomicU64::new(0)),
            cleanup_mapped_total: Arc::new(AtomicU64::new(0)),
            cleanup_missing_total: Arc::new(AtomicU64::new(0)),
            cleanup_outgoing_invite_removed_total: Arc::new(AtomicU64::new(0)),
            trace_redactor,
        }
    }

    /// Wire the state machine after construction. Idempotent — subsequent
    /// calls are silently ignored (returns `Err` if already set, which
    /// callers may choose to ignore or treat as a programming error).
    pub fn init_state_machine(
        &self,
        state_machine: Arc<crate::state_machine::StateMachine>,
    ) -> std::result::Result<(), Arc<crate::state_machine::StateMachine>> {
        self.state_machine.set(state_machine)
    }

    /// Route a retained adapter compatibility facade through the same atomic
    /// staged-options executor used by crate-owned builders. The adapter never
    /// invokes a BYE or CANCEL wire method directly from a raw public ID.
    async fn dispatch_state_machine_options_exact(
        &self,
        handle: &SessionRegistryHandle,
        event: EventType,
        slot: crate::state_machine::executor::PendingOptionsSlot,
    ) -> Result<()> {
        let state_machine = self.state_machine.get().cloned().ok_or_else(|| {
            SessionError::InvalidTransition(
                "SIP signaling state-machine authority is not installed".to_string(),
            )
        })?;
        self.store
            .get_session_snapshot_exact(handle)
            .map_err(|_| SessionError::SessionNotFound(handle.session_id().to_string()))?;
        let claim = Arc::new(crate::state_machine::executor::StageDispatchClaim::new(
            slot.clone(),
        ));
        state_machine
            .process_event_with_staged_options_exact(handle, event, slot, claim, None)
            .await
            .map(|_| ())
            .map_err(|error| SessionError::InternalError(error.to_string()))
    }

    /// Admit a sanitized application observation without placing observer
    /// completion or backpressure on the signaling caller.
    pub(crate) fn publish_api_event(&self, api_event: crate::api::events::Event) {
        if self
            .state_machine
            .get()
            .is_some_and(|state_machine| state_machine.publish_api_event(api_event.clone()))
        {
            return;
        }
        let _observation =
            spawn_api_event_observation(Arc::clone(&self.global_coordinator), api_event);
    }

    /// Publish a committed application event through the installed private
    /// exact-control path. Isolated adapters without that publisher emit only
    /// a sanitized public observation and never place authority on the bus.
    pub(crate) fn publish_api_event_exact(
        &self,
        lifecycle_handle: &SessionRegistryHandle,
        api_event: crate::api::events::Event,
    ) {
        if self.state_machine.get().is_some_and(|state_machine| {
            state_machine.publish_api_event_exact(lifecycle_handle, api_event.clone())
        }) {
            return;
        }
        let _observation =
            spawn_api_event_observation(Arc::clone(&self.global_coordinator), api_event);
    }

    pub(crate) fn outbound_transport_context_for_uri(
        &self,
        request_uri: &str,
    ) -> crate::auth::SipTransportSecurityContext {
        let Ok(uri) = Uri::from_str(request_uri) else {
            return crate::auth::SipTransportSecurityContext::from_request_uri_transport_hint(
                request_uri,
            );
        };
        let transaction_manager = self
            .dialog_api
            .dialog_manager()
            .core()
            .transaction_manager();
        let transport = transaction_manager.get_best_transport_for_uri(&uri);
        let mut context =
            crate::auth::SipTransportSecurityContext::from_transport_name(transport.to_string());
        if let Some(info) = transaction_manager.get_transport_info(transport) {
            context.local_addr = info.local_addr.map(|addr| addr.to_string());
        }
        context
    }

    pub(crate) fn outbound_transport_context_for_response(
        &self,
        response: &Response,
        fallback_request_uri: &str,
    ) -> crate::auth::SipTransportSecurityContext {
        self.dialog_api
            .outbound_transport_context_for_response(response)
            .map(|context| {
                crate::auth::SipTransportSecurityContext::from_transport_context(&context)
            })
            .unwrap_or_else(|| self.outbound_transport_context_for_uri(fallback_request_uri))
    }

    pub(crate) fn abort_registration_refresh_exact(&self, handle: &SessionRegistryHandle) {
        let session_id = handle.session_id();
        let guard = cleanup_diag::stage_guard(CleanupStage::TimerTaskShutdown, &session_id.0);
        let _admission = self
            .registration_refresh_admission
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        if let Some((_, task)) = self
            .registration_refresh_tasks
            .remove_if(session_id, |_, current| current.handle == *handle)
        {
            let _ = task.cancel.send(());
        }
        guard.finish_success();
    }

    /// Feature-gated retained-object counts for perf leak investigations.
    #[cfg(any(test, feature = "perf-tests"))]
    pub(crate) fn perf_diagnostic_counts(&self) -> serde_json::Value {
        serde_json::json!({
            "outgoing_invite_tx": self.outgoing_invite_tx.len(),
            "outgoing_bye_tx": self.outgoing_bye_tx.len(),
            "outgoing_bye_generation_watch": self.outgoing_bye_generation_watch.len(),
            "outgoing_bye_wait_intents": self.outgoing_bye_wait_intents.len(),
            "outbound_initial_invites": self.outbound_initial_invites.len(),
            "outbound_request_tracker": {
                "live_requests": self.outbound_request_tracker.live_request_count(),
                "deferred_events": self.outbound_request_tracker.deferred_event_count(),
            },
            "registration_refresh_tasks": self.registration_refresh_tasks.len(),
            "registration_refresh_retained_tasks": self.registration_refresh_retained.count(),
            "lifecycle": {
                "cleanup_attempt_total": self.cleanup_attempt_total.load(Ordering::Relaxed),
                "cleanup_mapped_total": self.cleanup_mapped_total.load(Ordering::Relaxed),
                "cleanup_missing_total": self.cleanup_missing_total.load(Ordering::Relaxed),
                "cleanup_outgoing_invite_removed_total": self.cleanup_outgoing_invite_removed_total.load(Ordering::Relaxed),
            },
        })
    }

    pub(crate) async fn abort_all_registration_refreshes_and_wait(&self) -> Result<()> {
        let cleanup_guard = cleanup_diag::stage_guard(CleanupStage::TimerTaskShutdown, "all");
        {
            // This short synchronous gate makes close, replacement and task
            // publication one ordered admission history. Network work never
            // runs while the gate is held.
            let _admission = self
                .registration_refresh_admission
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            self.registration_refresh_retained.close();
            let session_ids: Vec<_> = self
                .registration_refresh_tasks
                .iter()
                .map(|entry| entry.key().clone())
                .collect();
            for session_id in session_ids {
                if let Some((_, task)) = self.registration_refresh_tasks.remove(&session_id) {
                    let _ = task.cancel.send(());
                }
            }
        }
        cleanup_guard.finish_success();
        if tokio::time::timeout(
            REGISTRATION_REFRESH_DRAIN_TIMEOUT,
            self.registration_refresh_retained.wait_idle(),
        )
        .await
        .is_err()
        {
            return Err(SessionError::InternalError(format!(
                "registration refresh drain timed out with {} retained tasks",
                self.registration_refresh_retained.count()
            )));
        }
        if self.registration_refresh_retained.panicked() {
            return Err(SessionError::InternalError(
                "registration refresh task panicked during drain".to_string(),
            ));
        }
        Ok(())
    }

    fn compute_registration_refresh_at(&self, now: Instant, accepted_expires: u32) -> Instant {
        let base_secs = ((accepted_expires as f64) * 0.85).floor().max(1.0) as u64;
        let jitter_cap_secs =
            (base_secs * u64::from(self.registration_refresh_jitter_percent)) / 100;
        let jitter_secs = if jitter_cap_secs == 0 {
            0
        } else {
            use rand::Rng;
            rand::thread_rng().gen_range(0..=jitter_cap_secs)
        };
        now + Duration::from_secs(base_secs.saturating_sub(jitter_secs).max(1))
    }

    fn schedule_registration_refresh(
        &self,
        handle: SessionRegistryHandle,
        next_refresh_at: Option<Instant>,
    ) {
        let session_id = handle.session_id().clone();
        let state_machine = self.state_machine.get().cloned();
        let _admission = self
            .registration_refresh_admission
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());

        // Post-commit effects run outside the exact state-machine lane. A
        // delayed generation-A effect must not cancel or publish over a
        // generation-B timer that now owns the same raw SessionId.
        if self.store.lifecycle_handle(&session_id).as_ref() != Some(&handle) {
            tracing::debug!(
                session_id = %session_id,
                "ignored stale automatic registration refresh schedule"
            );
            return;
        }

        // Every map removal compares the complete task identity observed
        // under the admission gate. A current generation may reclaim a stale
        // predecessor, but an old callback can never remove its successor.
        let previous_identity = self
            .registration_refresh_tasks
            .get(&session_id)
            .map(|current| (current.handle.clone(), current.generation));
        if let Some((previous_handle, previous_generation)) = previous_identity {
            if let Some((_, previous)) =
                self.registration_refresh_tasks
                    .remove_if(&session_id, |_, current| {
                        current.handle == previous_handle
                            && current.generation == previous_generation
                    })
            {
                let _ = previous.cancel.send(());
            }
        }
        if !self.registration_auto_refresh {
            return;
        }
        let Some(next_refresh_at) = next_refresh_at else {
            return;
        };
        let Some(state_machine) = state_machine else {
            return;
        };
        if self.store.lifecycle_handle(&session_id).as_ref() != Some(&handle) {
            return;
        }

        let generation = self
            .next_registration_refresh_generation
            .fetch_add(1, Ordering::Relaxed);
        let (cancel, mut cancelled) = tokio::sync::oneshot::channel();
        let session_id_for_task = session_id.clone();
        let handle_for_task = handle.clone();
        let completion_handle = handle.clone();
        let completion_admission = Arc::clone(&self.registration_refresh_admission);
        let completion_tasks = Arc::clone(&self.registration_refresh_tasks);
        #[cfg(test)]
        let dispatch_pause = Arc::clone(&self.registration_refresh_dispatch_pause);
        let spawned = self.registration_refresh_retained.spawn(async move {
            // Construct inside the spawned future. If admission rejects and
            // drops the unpolled future while the caller owns the gate, there
            // is no completion destructor trying to reacquire that gate.
            let _completion = RegistrationRefreshCompletion {
                admission: completion_admission,
                tasks: completion_tasks,
                handle: completion_handle,
                generation,
            };
            let stage_claim = Arc::new(
                crate::state_machine::executor::StageDispatchClaim::new_deferred(
                    Method::Register,
                    crate::state_machine::executor::PendingOptionsSlotKind::Register,
                ),
            );
            let refresh_claim = Arc::clone(&stage_claim);
            let refresh = async move {
                tokio::time::sleep_until(tokio::time::Instant::from_std(next_refresh_at)).await;

                #[cfg(test)]
                let pause = {
                    dispatch_pause
                        .lock()
                        .unwrap_or_else(|poisoned| poisoned.into_inner())
                        .clone()
                };
                #[cfg(test)]
                if let Some(pause) = pause {
                    pause.pause().await;
                }

                match state_machine
                    .process_registration_refresh_exact(
                        &handle_for_task,
                        crate::state_table::types::EventType::RefreshRegistration,
                        None,
                        Vec::new(),
                        refresh_claim,
                    )
                    .await
                {
                    Ok(result) if result.transition.is_some() => {}
                    Ok(_) => {
                        tracing::warn!(
                            session_id = %session_id_for_task,
                            generation,
                            "automatic registration refresh has no state-table transition; no REGISTER dispatched"
                        );
                    }
                    Err(e) => {
                        tracing::debug!(
                            session_id = %session_id_for_task,
                            generation,
                            error = %e,
                            "exact automatic registration refresh was cancelled or stale"
                        );
                    }
                }
            };
            tokio::pin!(refresh);
            tokio::select! {
                biased;
                _ = &mut cancelled => {
                    if stage_claim.cancel_before_claim() {
                        return;
                    }
                    refresh.await;
                },
                _ = &mut refresh => {}
            }
        });
        if spawned {
            let replaced = self.registration_refresh_tasks.insert(
                session_id,
                RegistrationRefreshTask {
                    handle,
                    generation,
                    cancel,
                },
            );
            debug_assert!(replaced.is_none());
        }
    }

    pub(crate) fn accepted_registration_expires(
        response: &Response,
        requested_contact_uri: &str,
        fallback_expires: u32,
    ) -> u32 {
        use rvoip_sip_core::types::headers::HeaderAccess;
        use rvoip_sip_core::types::{header::HeaderName, TypedHeader};

        let requested = requested_contact_uri.trim().trim_matches(['<', '>']);

        let mut first_contact_expires = None;
        for contact in response.headers.iter().filter_map(|header| match header {
            TypedHeader::Contact(contact) => Some(contact),
            _ => None,
        }) {
            for address in contact.addresses() {
                let expires = address
                    .get_param("expires")
                    .flatten()
                    .and_then(|value| value.parse::<u32>().ok());
                if first_contact_expires.is_none() {
                    first_contact_expires = expires;
                }
                if address.uri.to_string() == requested {
                    if let Some(expires) = expires {
                        return expires;
                    }
                }
            }
        }

        first_contact_expires
            .or_else(|| {
                response
                    .raw_header_value(&HeaderName::Expires)
                    .and_then(|value| value.trim().parse::<u32>().ok())
            })
            .unwrap_or(fallback_expires)
    }

    pub(crate) fn response_registration_metadata(
        response: &Response,
    ) -> RegistrationResponseMetadata {
        use rvoip_sip_core::types::outbound::read_gruu_contact_params;
        use rvoip_sip_core::types::TypedHeader;

        let service_route = {
            let routes: Vec<String> = response
                .headers
                .iter()
                .filter_map(|header| match header {
                    TypedHeader::ServiceRoute(route) => Some(route.uris()),
                    _ => None,
                })
                .flatten()
                .map(|uri| uri.to_string())
                .collect();
            if routes.is_empty() {
                None
            } else {
                Some(routes)
            }
        };

        let mut pub_gruu = None;
        let mut temp_gruu = None;
        for contact in response.headers.iter().filter_map(|header| match header {
            TypedHeader::Contact(contact) => Some(contact),
            _ => None,
        }) {
            for address in contact.addresses() {
                let params = read_gruu_contact_params(address);
                if pub_gruu.is_none() {
                    pub_gruu = params.pub_gruu;
                }
                if temp_gruu.is_none() {
                    temp_gruu = params.temp_gruu;
                }
            }
        }

        RegistrationResponseMetadata {
            service_route,
            pub_gruu,
            temp_gruu,
            transport_route: None,
        }
    }

    pub(crate) fn register_attempt_outcome_from_response(
        response: &Response,
        contact_uri: &str,
        expires: u32,
    ) -> RegisterAttemptOutcome {
        match response.status_code() {
            200..=299 => {
                if expires == 0 {
                    RegisterAttemptOutcome::Unregistered
                } else {
                    RegisterAttemptOutcome::Registered {
                        accepted_expires: Self::accepted_registration_expires(
                            response,
                            contact_uri,
                            expires,
                        ),
                        metadata: Self::response_registration_metadata(response),
                    }
                }
            }
            401 | 407 => {
                use rvoip_sip_core::types::headers::HeaderAccess;
                let header_name = if response.status_code() == 407 {
                    rvoip_sip_core::types::header::HeaderName::ProxyAuthenticate
                } else {
                    rvoip_sip_core::types::header::HeaderName::WwwAuthenticate
                };
                if let Some(challenge) = response.raw_header_value(&header_name) {
                    RegisterAttemptOutcome::AuthChallenge {
                        status_code: response.status_code(),
                        challenge,
                    }
                } else {
                    RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: "REGISTER challenge response did not include challenge header"
                            .to_string(),
                    }
                }
            }
            423 => {
                use rvoip_sip_core::types::headers::HeaderAccess;
                match response
                    .raw_header_value(&rvoip_sip_core::types::header::HeaderName::MinExpires)
                    .and_then(|s| s.trim().parse::<u32>().ok())
                {
                    Some(min_expires) if min_expires > 0 && min_expires <= 7200 => {
                        RegisterAttemptOutcome::IntervalTooBrief { min_expires }
                    }
                    Some(min_expires) => RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: format!(
                            "423 Interval Too Brief included invalid Min-Expires={}",
                            min_expires
                        ),
                    },
                    None => RegisterAttemptOutcome::Failure {
                        status_code: response.status_code(),
                        reason: "423 Interval Too Brief without Min-Expires header".to_string(),
                    },
                }
            }
            _ => RegisterAttemptOutcome::Failure {
                status_code: response.status_code(),
                reason: response.reason_phrase().to_string(),
            },
        }
    }

    pub(crate) fn register_response_transport_context(
        &self,
        response: &Response,
    ) -> Option<crate::auth::SipTransportSecurityContext> {
        self.dialog_api
            .outbound_transport_context_for_response(response)
            .map(|context| {
                crate::auth::SipTransportSecurityContext::from_transport_context(&context)
            })
    }

    /// Apply a successful REGISTER outcome to the executor's lane-owned
    /// working state and return the non-state work that must run after commit.
    pub(crate) fn record_registration_success(
        &self,
        session: &mut SessionState,
        registrar_uri: &str,
        from_uri: &str,
        contact_uri: &str,
        accepted_expires: u32,
        metadata: RegistrationResponseMetadata,
    ) -> RegistrationPostCommitEffect {
        let now = Instant::now();
        let next_refresh_at = if self.registration_auto_refresh && accepted_expires > 0 {
            Some(self.compute_registration_refresh_at(now, accepted_expires))
        } else {
            None
        };

        record_registration_success_state(
            session,
            RegistrationSuccessStateInput {
                registrar_uri,
                from_uri,
                contact_uri,
                accepted_expires,
                now,
                next_refresh_at,
                metadata,
            },
        )
    }

    pub(crate) fn record_unregistration_success(
        &self,
        session: &mut SessionState,
        registrar_uri: &str,
    ) -> RegistrationPostCommitEffect {
        record_unregistration_success_state(session, registrar_uri)
    }

    pub(crate) fn record_registration_failure(
        &self,
        session: &mut SessionState,
        registrar_uri: &str,
        status_code: u16,
        reason: impl Into<String>,
    ) -> RegistrationPostCommitEffect {
        record_registration_failure_state(session, registrar_uri, status_code, reason.into())
    }

    pub(crate) fn record_unregistration_failure(
        &self,
        session: &mut SessionState,
        registrar_uri: &str,
        reason: impl Into<String>,
    ) -> RegistrationPostCommitEffect {
        record_unregistration_failure_state(session, registrar_uri, reason.into())
    }

    /// Run observer/timer/flow effects after the canonical state commit.
    pub(crate) fn complete_registration_post_commit(
        &self,
        handle: &SessionRegistryHandle,
        effect: RegistrationPostCommitEffect,
    ) {
        let session_id = handle.session_id();
        match effect {
            RegistrationPostCommitEffect::Registered {
                registrar_uri,
                from_uri,
                contact_uri,
                accepted_expires,
                next_refresh_at,
                transport_route,
            } => {
                tracing::info!(
                    "✅ Registration successful - session {} marked as registered",
                    session_id.0
                );
                self.publish_api_event(crate::api::events::Event::RegistrationSuccess {
                    registrar: registrar_uri,
                    expires: accepted_expires,
                    contact: contact_uri,
                });
                self.schedule_registration_refresh(handle.clone(), next_refresh_at);
                self.start_symmetric_registration_keepalive(&from_uri, transport_route);
            }
            RegistrationPostCommitEffect::Unregistered { registrar_uri } => {
                self.abort_registration_refresh_exact(handle);
                tracing::info!(
                    "✅ Unregistration successful - session {} marked as unregistered",
                    session_id.0
                );
                self.publish_api_event(crate::api::events::Event::UnregistrationSuccess {
                    registrar: registrar_uri,
                });
            }
            RegistrationPostCommitEffect::RegistrationFailed {
                registrar_uri,
                status_code,
                failure_summary,
            } => {
                self.abort_registration_refresh_exact(handle);
                self.publish_api_event(crate::api::events::Event::RegistrationFailed {
                    registrar: registrar_uri,
                    status_code,
                    reason: failure_summary,
                });
            }
            RegistrationPostCommitEffect::UnregistrationFailed {
                registrar_uri,
                reason,
            } => {
                self.abort_registration_refresh_exact(handle);
                self.publish_api_event(crate::api::events::Event::UnregistrationFailed {
                    registrar: registrar_uri,
                    reason,
                });
            }
        }
    }

    // ===== Direct Dialog Operations =====
    // NOTE: Removed confusing create_dialog() and send_invite() methods
    // Use send_invite_with_details() to create a dialog and send INVITE in one operation

    /// Send a response
    pub async fn send_response_by_dialog(
        &self,
        _dialog_id: DialogId,
        _status_code: u16,
        _reason: &str,
    ) -> Result<()> {
        Err(SessionError::InvalidTransition(
            "dialog-scoped response dispatch has no exact inbound transaction authority"
                .to_string(),
        ))
    }

    /// Compatibility facade for a dialog-addressed BYE. The exact registry
    /// owner is captured once, then the request is staged and dispatched by
    /// the YAML executor before this method joins the transaction result.
    pub async fn send_bye(&self, dialog_id: crate::types::DialogId) -> Result<()> {
        let rvoip_dialog_id: RvoipDialogId = dialog_id.into();
        let exact_dialog_id: crate::types::DialogId = rvoip_dialog_id.clone().into();
        let handle = self
            .store
            .registry()
            .get_handle_by_dialog_exact(&exact_dialog_id)
            .ok_or_else(|| {
                SessionError::SessionNotFound(format!(
                    "No exact session owns dialog {}",
                    rvoip_dialog_id
                ))
            })?;
        let _wait_owner = self.begin_outgoing_bye_wait_exact(&handle)?;
        self.dispatch_state_machine_options_exact(
            &handle,
            EventType::SendOutboundBye,
            crate::state_machine::executor::PendingOptionsSlot::Bye(Arc::new(
                ByeRequestOptions::default(),
            )),
        )
        .await?;
        self.wait_for_outgoing_bye_final_response_exact(&handle)
            .await
    }

    /// Send re-INVITE with new SDP
    pub async fn send_reinvite(
        &self,
        dialog_id: crate::types::DialogId,
        sdp: String,
    ) -> Result<()> {
        let rvoip_dialog_id: RvoipDialogId = dialog_id.into();
        let (_handle, _exact_lane, session) =
            lock_and_load_exact_legacy_dialog_session(self.store.as_ref(), &rvoip_dialog_id)
                .await?;

        let session_id = session.session_id.clone();
        self.send_reinvite_with_options_lane_owned(
            &session,
            rvoip_sip_dialog::api::unified::ReInviteRequestOptions {
                sdp: Some(sdp),
                ..Default::default()
            },
        )
        .await?;

        tracing::info!("Sent re-INVITE for session {}", session_id.0);

        Ok(())
    }

    /// Send REFER for transfers
    pub async fn send_refer(
        &self,
        dialog_id: crate::types::DialogId,
        target: &str,
        attended: bool,
    ) -> Result<()> {
        // Convert our DialogId to RvoipDialogId
        let rvoip_dialog_id: RvoipDialogId = dialog_id.into();
        let (_handle, _exact_lane, session) =
            lock_and_load_exact_legacy_dialog_session(self.store.as_ref(), &rvoip_dialog_id)
                .await?;

        let session_id = session.session_id.clone();
        // Attended-transfer Replaces belongs in `ReferRequestOptions.replaces`
        // (an RFC 3891 header param on Refer-To), not as a REFER body. The
        // legacy boolean never had an on-wire effect.
        let _ = attended;
        self.send_refer_with_options_lane_owned(
            &session,
            ReferRequestOptions {
                refer_to: target.to_string(),
                ..Default::default()
            },
        )
        .await?;

        tracing::info!(
            session = %session_id.0,
            target_present = !target.is_empty(),
            target_bytes = target.len(),
            "Sent REFER"
        );

        Ok(())
    }

    /// Get remote URI for a dialog
    pub async fn get_remote_uri(&self, dialog_id: crate::types::DialogId) -> Result<String> {
        let rvoip_dialog_id: RvoipDialogId = dialog_id.into();
        self.dialog_api
            .get_dialog_info(&rvoip_dialog_id)
            .await
            .map(|dialog| dialog.remote_uri.to_string())
            .map_err(|_| {
                SessionError::DialogError(
                    "Failed to resolve remote URI for exact dialog (class=dialog)".to_string(),
                )
            })
    }

    /// RFC 3261 §22.2 — resend an INVITE with `Authorization` (or
    /// `Proxy-Authorization`) header on the same dialog after the server
    /// challenged with 401/407. The `SendINVITEWithAuth` state-machine action
    /// owns auth header computation; this is a thin passthrough to dialog-core.
    ///
    /// Both REGISTER and INVITE 401/407 challenges flow through the state
    /// machine via `DialogToSessionEvent::AuthRequired` → `EventType::AuthRequired`;
    /// the previous inline REGISTER-auth shortcut (`handle_401_challenge`) was
    /// retired when INVITE auth landed. See `default.yaml`'s `Initiating` /
    /// `Registering` + `AuthRequired` transitions.
    pub async fn resend_invite_with_auth(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::InviteAuthRetryOptions,
        apply_global_proxy: bool,
    ) -> Result<()> {
        let dialog_id = resolve_exact_invite_retry_dialog(self.store.as_ref(), session_id)?;

        // Legacy/internal paths may not have a persisted per-call override.
        // In that case retain the configured global proxy structurally; never
        // synthesize it as a transient application Route header.
        if apply_global_proxy && opts.outbound_proxy_uri.is_none() {
            opts.outbound_proxy_uri = self.outbound_proxy_uri.clone();
        }
        self.dialog_api
            .send_invite_with_auth_options(&dialog_id, opts)
            .await
            .map_err(|error| {
                redacted_invite_dispatch_error(InviteDispatchFailure::AuthRetry, error)
            })?;
        Ok(())
    }

    /// RFC 4028 §6 — resend an INVITE with a bumped `Session-Expires` /
    /// `Min-SE` after a 422 Session Interval Too Small. The UAS's Min-SE
    /// floor is supplied by the caller (parsed from the 422 response by
    /// dialog-core). The timer headers bypass
    /// [`DialogManagerConfig`](rvoip_sip_dialog::config::DialogManagerConfig)'s
    /// global values and use these overrides verbatim.
    pub async fn resend_invite_with_session_timer_override(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::InviteAuthRetryOptions,
        apply_global_proxy: bool,
        session_secs: u32,
        min_se: u32,
    ) -> Result<()> {
        let dialog_id = resolve_exact_invite_retry_dialog(self.store.as_ref(), session_id)?;

        if apply_global_proxy && opts.outbound_proxy_uri.is_none() {
            opts.outbound_proxy_uri = self.outbound_proxy_uri.clone();
        }
        self.dialog_api
            .send_invite_with_session_timer_options(&dialog_id, opts, session_secs, min_se)
            .await
            .map_err(|error| {
                redacted_invite_dispatch_error(InviteDispatchFailure::SessionTimerRetry, error)
            })?;
        Ok(())
    }

    /// Read the dialog installed by a completed initial-INVITE dispatch while
    /// the executor retains this exact session lane. The owned operation has
    /// already published the same identity into SessionStore before wire; the
    /// executor's working copy may still contain `None` and adopts it at its
    /// canonical event commit.
    pub(crate) fn initial_invite_dialog_lane_owned(
        &self,
        session: &SessionState,
    ) -> Result<crate::types::DialogId> {
        let handle = session.lifecycle_handle.as_ref().ok_or_else(|| {
            SessionError::InvalidTransition(
                "initial INVITE exact session has no lifecycle authority".to_string(),
            )
        })?;
        if handle.session_id() != &session.session_id {
            return Err(SessionError::InvalidTransition(
                "initial INVITE lifecycle owner does not match its session".to_string(),
            ));
        }
        let dialog_id = self
            .store
            .registry()
            .get_dialog_handle_exact(handle)
            .ok_or_else(|| {
                SessionError::InternalError(
                    "initial INVITE committed without an exact dialog mapping".to_string(),
                )
            })?;
        if session
            .dialog_id
            .as_ref()
            .is_some_and(|current| current != &dialog_id)
        {
            return Err(SessionError::InvalidTransition(
                "initial INVITE exact dialog changed before executor commit".to_string(),
            ));
        }
        Ok(dialog_id)
    }

    /// Does the remote peer support RFC 3262 100rel? Used to gate
    /// `send_early_media` — we only emit a reliable 183 when the caller
    /// advertised `Supported: 100rel` (or `Require: 100rel`) on the INVITE.
    /// Returns `SessionNotFound` if the session has no dialog yet.
    pub async fn peer_supports_100rel(&self, session_id: &SessionId) -> Result<bool> {
        let handle = self
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?;
        let dialog_id = resolve_dialog_for_handle_exact(self.store.as_ref(), &handle)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.0.clone()))?;

        let dialog = self
            .dialog_api
            .get_dialog_info(&dialog_id)
            .await
            .map_err(|e| {
                SessionError::DialogError(format!(
                    "peer_supports_100rel: failed to read dialog {}: {}",
                    dialog_id, e
                ))
            })?;

        if resolve_dialog_for_handle_exact(self.store.as_ref(), &handle).as_ref()
            != Some(&dialog_id)
        {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        }

        Ok(dialog.peer_supports_100rel)
    }

    // ===== Outbound Actions (from state machine) =====

    /// Record that the accepted upper-layer transition owns BYE teardown.
    ///
    /// Call this immediately before awaiting BYE dispatch. A loopback
    /// peer can return a final response during that await and drive exact
    /// session release before the send future unwinds. Marking afterward loses
    /// the retained initial-INVITE owner and can make shutdown supervise a
    /// teardown that the upper layer already sent. CANCEL remains owned by the
    /// dialog lifecycle because its transaction layer can distinguish a
    /// proven zero-wire failure from a write-started ambiguous failure.
    pub(crate) fn mark_initial_invite_protocol_teardown_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) {
        let session_id = handle.session_id();
        let Some(binding) = self.outbound_initial_invites.get(session_id) else {
            return;
        };
        if binding.handle != *handle {
            return;
        }
        if let Some(resource) = binding.resource.upgrade() {
            resource.mark_protocol_teardown_owned_by_upper();
        }
    }

    async fn send_initial_invite_staged(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::InviteRequestOptions,
        failure: InviteDispatchFailure,
    ) -> Result<()> {
        tracing::trace!(
            session_id = %session_id,
            operation = failure.diagnostic(),
            "staged initial INVITE entering planner"
        );
        let handle = self.store.lifecycle_handle(session_id).ok_or_else(|| {
            SessionError::SessionNotFound(format!(
                "Session {} has no current lifecycle handle",
                session_id.0
            ))
        })?;
        let plan = self
            .dialog_api
            .plan_initial_invite(Some(session_id.0.clone()), opts)
            .await
            .map_err(|error| redacted_invite_dispatch_error(failure, error))?;
        tracing::trace!(
            session_id = %session_id,
            operation = failure.diagnostic(),
            "staged initial INVITE plan ready"
        );
        let resource =
            OutboundInitialInviteResource::new(self, handle.clone(), plan.owner().clone());
        let dialog_api = Arc::clone(&self.dialog_api);
        let store = Arc::clone(&self.store);
        let authority = Arc::clone(self.store.authority());
        let operation_resource = Arc::clone(&resource);

        let waiter = authority
            .spawn_owned_exact(
                handle.key(),
                SessionOperationKind::Signaling,
                INITIAL_INVITE_OWNED_OPERATION_TIMEOUT,
                move |mut operation| async move {
                    tracing::trace!("staged initial INVITE owned operation started");
                    let spec = ResourceSpec::new(
                        operation_resource.descriptor(),
                        Vec::new(),
                        INITIAL_INVITE_RESOURCE_RELEASE_TIMEOUT,
                    )
                    .unwrap_or_else(|_| panic!("initial INVITE resource spec is invalid"));
                    let attempt = match operation.reserve_resource(spec) {
                        Ok(attempt) => attempt,
                        Err(_) => {
                            return rollback_owned_invite(
                                operation,
                                Err(SessionError::InternalError(
                                    "initial INVITE resource reservation failed (class=lifecycle)"
                                        .to_string(),
                                )),
                            )
                            .await;
                        }
                    };
                    let installation_sink = attempt
                        .dispatch()
                        .unwrap_or_else(|_| panic!("initial INVITE dispatch permit failed"))
                        .into_installation_sink();
                    // `install_initial_invite_with_sink` may reject a plan
                    // before invoking its sink (for example, when an exact
                    // session mapping is still occupied). Keep the sink in a
                    // shared single-use slot so that path can prove the
                    // reservation unused instead of dropping it as an
                    // unresolvable lifecycle orphan.
                    let installation_sink = Arc::new(std::sync::Mutex::new(Some(
                        installation_sink,
                    )));
                    let callback_installation_sink = Arc::clone(&installation_sink);
                    let sink_resource = Arc::clone(&operation_resource);
                    let installed = match dialog_api.install_initial_invite_with_sink(
                        plan,
                        move |_installed| {
                            let installation_sink = callback_installation_sink
                                .lock()
                                .unwrap_or_else(|poisoned| poisoned.into_inner())
                                .take()
                                .ok_or_else(|| rvoip_sip_dialog::ApiError::Dialog {
                                    message: "Initial INVITE lifecycle sink was already resolved"
                                        .to_string(),
                                })?;
                            installation_sink
                                .capture_at_install(
                                    Arc::clone(&sink_resource)
                                        as Arc<dyn ManagedSessionResource>,
                                )
                                .map_err(|_| rvoip_sip_dialog::ApiError::Dialog {
                                    message: "Initial INVITE lifecycle capture failed".to_string(),
                                })?;
                            sink_resource.install_adapter_bindings().map_err(|_| {
                                rvoip_sip_dialog::ApiError::Dialog {
                                    message: "Initial INVITE adapter binding failed".to_string(),
                                }
                            })
                        },
                    ) {
                        Ok(installed) => {
                            tracing::trace!("staged initial INVITE installed");
                            installed
                        }
                        Err(error) => {
                            tracing::trace!("staged initial INVITE installation rejected");
                            let unused_sink = installation_sink
                                .lock()
                                .unwrap_or_else(|poisoned| poisoned.into_inner())
                                .take();
                            if let Some(unused_sink) = unused_sink {
                                if unused_sink.confirm_unused().is_err() {
                                    return rollback_owned_invite(
                                        operation,
                                        Err(SessionError::InternalError(
                                            "initial INVITE unused reservation confirmation failed (class=lifecycle)"
                                                .to_string(),
                                        )),
                                    )
                                    .await;
                                }
                            }
                            return rollback_owned_invite(
                                operation,
                                Err(redacted_invite_dispatch_error(failure, error)),
                            )
                            .await;
                        }
                    };

                    // Installation publishes the exact registry mapping.
                    // Mirror that identity into SessionState before
                    // dispatch: a synchronous 200 OK may otherwise publish an
                    // Active snapshot cloned from the pre-install revision and
                    // make an immediate BYE fail its ownership check.
                    if let Err(error) = publish_initial_invite_dialog_exact(
                        store.as_ref(),
                        &operation_resource.handle,
                        operation_resource.owner.dialog_id(),
                    ) {
                        drop(installed);
                        return rollback_owned_invite(operation, Err(error)).await;
                    }
                    operation_resource.record_state_dialog_published();

                    tracing::trace!("staged initial INVITE dispatch starting");
                    let completion = dialog_api.dispatch_initial_invite(installed).wait().await;
                    tracing::trace!("staged initial INVITE dispatch completed");
                    let wire_outcome = completion.wire_outcome();
                    operation_resource.record_wire_outcome(wire_outcome);
                    match completion.into_result() {
                        Ok((owner, transaction_id)) => {
                            if owner != operation_resource.owner {
                                panic!("initial INVITE dispatch returned a different exact owner");
                            }
                            if !operation_resource.install_transaction(transaction_id) {
                                return commit_owned_invite(
                                    operation,
                                    Err(SessionError::InternalError(
                                        "initial INVITE transaction binding failed (class=lifecycle)"
                                            .to_string(),
                                    )),
                                )
                                .await;
                            }
                            commit_owned_invite(operation, Ok(())).await
                        }
                        Err(error) => {
                            let value = Err(redacted_invite_dispatch_error(failure, error));
                            match wire_outcome {
                                InitialInviteWireOutcome::ZeroWire => {
                                    rollback_owned_invite(operation, value).await
                                }
                                InitialInviteWireOutcome::Sent
                                | InitialInviteWireOutcome::Unknown => {
                                    commit_owned_invite(operation, value).await
                                }
                            }
                        }
                    }
                },
            )
            .map_err(|_| {
                SessionError::InternalError(
                    "initial INVITE owned operation admission failed (class=lifecycle)".to_string(),
                )
            })?;

        let result = waiter.await.map_err(|_| {
            SessionError::InternalError(
                "initial INVITE owned operation failed (class=lifecycle)".to_string(),
            )
        })?;
        if result.is_ok() {
            tracing::debug!(
                session_id = %session_id,
                dialog_id = %resource.owner.dialog_id(),
                "staged initial INVITE committed with exact lifecycle ownership"
            );
        }
        result
    }

    /// Send INVITE for UAC - this is the primary method for initiating calls
    ///
    /// This method:
    /// 1. Creates a dialog in dialog-core
    /// 2. Sends the INVITE request
    /// 3. Stores the session-to-dialog mapping
    ///
    /// # Arguments
    /// * `session_id` - The session ID from the state machine
    /// * `from` - The From URI (e.g., "sip:alice@example.com")
    /// * `to` - The To URI (e.g., "sip:bob@example.com")
    /// * `sdp` - Optional SDP offer
    pub async fn send_invite_with_details(
        &self,
        session_id: &SessionId,
        from: &str,
        to: &str,
        sdp: Option<String>,
    ) -> Result<()> {
        let call_id = deterministic_outbound_call_id(session_id);
        self.send_initial_invite_staged(
            session_id,
            rvoip_sip_dialog::api::unified::InviteRequestOptions {
                from_uri: from.to_string(),
                to_uri: to.to_string(),
                sdp,
                call_id: Some(call_id),
                ..Default::default()
            },
            InviteDispatchFailure::Initial,
        )
        .await
    }

    /// Like [`send_invite_with_details`](Self::send_invite_with_details) but appends caller-supplied extra
    /// headers to the outgoing INVITE. Routes through dialog-core's
    /// `make_call_with_extra_headers_for_session` so the extras (typically
    /// `P-Asserted-Identity` per RFC 3325) ride on the very first wire
    /// transmission rather than being added in a follow-up.
    ///
    /// Used by the `SendINVITE` action when `SessionState.pai_uri` is set;
    /// the action handler builds the typed PAI header from the URI and
    /// passes it through here.
    pub async fn send_invite_with_extra_headers(
        &self,
        session_id: &SessionId,
        from: &str,
        to: &str,
        sdp: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        self.send_invite_with_extra_headers_inner(
            session_id,
            from,
            to,
            sdp,
            extra_headers,
            true, // apply global outbound-proxy Route
        )
        .await
    }

    /// SIP_API_DESIGN_2 §6.1 — variant used by builder dispatch when
    /// the builder has set its own per-call `with_outbound_proxy(uri)`
    /// structural override in `Action::SendINVITEWithOptions`. Skips the global
    /// `Config.outbound_proxy_uri` so the wire doesn't end up with two
    /// stacked proxy Routes when the caller meant to override the
    /// default.
    pub async fn send_invite_with_extra_headers_no_global_proxy(
        &self,
        session_id: &SessionId,
        from: &str,
        to: &str,
        sdp: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        self.send_invite_with_extra_headers_inner(session_id, from, to, sdp, extra_headers, false)
            .await
    }

    async fn send_invite_with_extra_headers_inner(
        &self,
        session_id: &SessionId,
        from: &str,
        to: &str,
        sdp: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
        apply_global_proxy: bool,
    ) -> Result<()> {
        let call_id = deterministic_outbound_call_id(session_id);

        // The proxy is a structural first hop, not an application Route
        // header. This guarantees it precedes REGISTER Service-Route entries
        // and lets dialog-core reject caller-controlled Route injection.
        let outbound_proxy_uri = if apply_global_proxy {
            self.outbound_proxy_uri.clone()
        } else {
            None
        };
        if apply_global_proxy && self.outbound_proxy_uri.is_some() {
            tracing::debug!(
                "E4 outbound proxy: staged structural first-hop route for INVITE session {}",
                session_id.0
            );
        }

        let opts = rvoip_sip_dialog::api::unified::InviteRequestOptions {
            from_uri: from.to_string(),
            to_uri: to.to_string(),
            sdp,
            call_id: Some(call_id),
            from_display: None,
            contact_uri: None,
            precomputed_authorization: None,
            outbound_proxy_uri,
            supported_100rel: false,
            extra_headers,
        };
        self.send_initial_invite_staged(
            session_id,
            opts,
            InviteDispatchFailure::InitialWithExtraHeaders,
        )
        .await
    }

    /// SIP_API_DESIGN_2 Phase B — structured initial-INVITE dispatch. The
    /// rvoip-sip counterpart of dialog-core `send_invite_with_options`: carries
    /// the `From` display name and `Contact` as typed fields instead of
    /// smuggling them through `extra_headers`. `apply_global_proxy` follows the
    /// same rule as [`Self::send_invite_with_extra_headers`] — skip the global
    /// `Config.outbound_proxy_uri` when the builder set a structural per-call
    /// override in `opts.outbound_proxy_uri`.
    pub async fn send_invite_with_options(
        &self,
        session_id: &SessionId,
        mut opts: rvoip_sip_dialog::api::unified::InviteRequestOptions,
        apply_global_proxy: bool,
    ) -> Result<()> {
        let call_id = deterministic_outbound_call_id(session_id);

        if apply_global_proxy && opts.outbound_proxy_uri.is_none() {
            opts.outbound_proxy_uri = self.outbound_proxy_uri.clone();
            if opts.outbound_proxy_uri.is_some() {
                tracing::debug!(
                    "E4 outbound proxy: staged structural first-hop route for INVITE session {}",
                    session_id.0
                );
            }
        }
        opts.call_id = Some(call_id);
        self.send_initial_invite_staged(session_id, opts, InviteDispatchFailure::InitialWithOptions)
            .await
    }

    /// Send 200 OK response
    pub async fn send_200_ok(&self, session_id: &SessionId, sdp: Option<String>) -> Result<()> {
        self.send_response(session_id, 200, sdp).await
    }

    /// Send response with SDP
    pub async fn send_response_with_sdp(
        &self,
        session_id: &SessionId,
        code: u16,
        _reason: &str,
        sdp: &str,
    ) -> Result<()> {
        self.send_response(session_id, code, Some(sdp.to_string()))
            .await
    }

    /// Send response without SDP
    pub async fn send_response_session(
        &self,
        session_id: &SessionId,
        code: u16,
        _reason: &str,
    ) -> Result<()> {
        self.send_response(session_id, code, None).await
    }

    /// Send error response
    pub async fn send_error_response(
        &self,
        session_id: &SessionId,
        code: StatusCode,
        _reason: &str,
    ) -> Result<()> {
        self.send_response(session_id, code.as_u16(), None).await
    }

    /// Retained compatibility signature. Session-scoped redirect dispatch
    /// fails closed because it has no exact inbound transaction capability.
    pub async fn send_redirect_response_with_options(
        &self,
        _session_id: &SessionId,
        _status: u16,
        _contacts: Vec<String>,
        _extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        Err(SessionError::InvalidTransition(
            "session-scoped redirect dispatch has no exact inbound transaction authority"
                .to_string(),
        ))
    }

    /// Retained compatibility signature for a session-scoped redirect.
    pub async fn send_redirect_response(
        &self,
        _session_id: &SessionId,
        _status: u16,
        _contacts: Vec<String>,
    ) -> Result<()> {
        Err(SessionError::InvalidTransition(
            "session-scoped redirect dispatch has no exact inbound transaction authority"
                .to_string(),
        ))
    }

    /// Retained compatibility signature for a session-scoped UAS response
    /// with application headers. Exact transaction methods remain supported.
    pub async fn send_response_with_options(
        &self,
        _session_id: &SessionId,
        _code: u16,
        _sdp: Option<String>,
        _extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        Err(SessionError::InvalidTransition(
            "session-scoped response dispatch has no exact inbound transaction authority"
                .to_string(),
        ))
    }

    /// Send response (for UAS)
    pub async fn send_response(
        &self,
        _session_id: &SessionId,
        _code: u16,
        _sdp: Option<String>,
    ) -> Result<()> {
        Err(SessionError::InvalidTransition(
            "session-scoped response dispatch has no exact inbound transaction authority"
                .to_string(),
        ))
    }

    /// Send a UAS response through a known inbound server transaction.
    pub async fn send_response_for_transaction(
        &self,
        session_id: &SessionId,
        transaction_id: &TransactionKey,
        code: u16,
        sdp: Option<String>,
    ) -> Result<()> {
        let (transaction_method, transaction_direction) =
            exact_response_transaction_diagnostics(transaction_id);
        tracing::info!(
            session_id = %session_id.0,
            status_code = code,
            transaction_method,
            transaction_direction,
            sdp_present = sdp.is_some(),
            "DialogAdapter sending exact SIP response"
        );

        self.dialog_api
            .send_response_for_session_transaction(&session_id.0, transaction_id, code, sdp)
            .await
            .map_err(|_| {
                tracing::error!(
                    session_id = %session_id.0,
                    status_code = code,
                    transaction_method,
                    transaction_direction,
                    error_class = "dialog",
                    "Failed to send exact SIP response"
                );
                SessionError::DialogError(
                    "Failed to send exact SIP response (class=dialog)".to_string(),
                )
            })
    }

    /// Send a REFER final response through the exact inbound server
    /// transaction. This is the causal path; the cross-crate event bus only
    /// observes outcomes and is not required for wire progress.
    pub(crate) async fn send_refer_response_classified(
        &self,
        transaction_id: &str,
        code: u16,
    ) -> std::result::Result<
        rvoip_sip_dialog::FinalResponseCompletionDisposition,
        rvoip_sip_dialog::ExactResponseSendError,
    > {
        let transaction_id = transaction_id.parse::<TransactionKey>().map_err(|_| {
            rvoip_sip_dialog::ExactResponseSendError {
                source: rvoip_sip_dialog::ApiError::Protocol {
                    message: "pending REFER transaction identifier is invalid".to_string(),
                },
                disposition:
                    rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable,
            }
        })?;
        if transaction_id.method() != &rvoip_sip_core::Method::Refer || !transaction_id.is_server()
        {
            return Err(rvoip_sip_dialog::ExactResponseSendError {
                source: rvoip_sip_dialog::ApiError::Protocol {
                    message: "pending REFER response does not identify a server REFER transaction"
                        .to_string(),
                },
                disposition:
                    rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable,
            });
        }
        let status =
            StatusCode::from_u16(code).map_err(|_| rvoip_sip_dialog::ExactResponseSendError {
                source: rvoip_sip_dialog::ApiError::Protocol {
                    message: "pending REFER response has an invalid final status".to_string(),
                },
                disposition:
                    rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable,
            })?;
        self.dialog_api
            .send_status_response_classified(&transaction_id, status, None)
            .await
    }

    /// Send a transaction-oriented REGISTER response directly through the
    /// dialog/transaction API. The response event type remains available for
    /// compatibility observation, but wire correctness does not depend on it.
    pub(crate) async fn send_register_response_fields(
        &self,
        fields: &crate::api::respond::register_response::RegisterResponseEventFields,
    ) -> Result<()> {
        match self.send_register_response_fields_classified(fields).await {
            Ok(rvoip_sip_dialog::FinalResponseCompletionDisposition::WrittenSuccessTerminal)
            | Ok(rvoip_sip_dialog::FinalResponseCompletionDisposition::WireUnknownErrorTerminal) => {
                Ok(())
            }
            Ok(rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable) => {
                Err(SessionError::DialogError(
                    "failed to send exact REGISTER response before transport write".to_string(),
                ))
            }
            Err(error)
                if error.disposition
                    != rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable =>
            {
                tracing::warn!(
                    status_code = fields.status_code,
                    disposition = ?error.disposition,
                    "REGISTER final response became terminal at the transport boundary; suppressing duplicate fallback"
                );
                Ok(())
            }
            Err(_) => Err(SessionError::DialogError(
                "failed to send exact REGISTER response before transport write".to_string(),
            )),
        }
    }

    /// Classified exact-transaction form used by the built-in registrar.
    /// No session or dialog index participates because REGISTER is a
    /// transaction-oriented method.
    pub(crate) async fn send_register_response_fields_classified(
        &self,
        fields: &crate::api::respond::register_response::RegisterResponseEventFields,
    ) -> std::result::Result<
        rvoip_sip_dialog::FinalResponseCompletionDisposition,
        rvoip_sip_dialog::ExactResponseSendError,
    > {
        let transaction_id = fields
            .transaction_id
            .parse::<TransactionKey>()
            .map_err(|_| rvoip_sip_dialog::ExactResponseSendError {
                source: rvoip_sip_dialog::ApiError::Protocol {
                    message: "pending REGISTER transaction identifier is invalid".to_string(),
                },
                disposition:
                    rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable,
            })?;
        if transaction_id.method() != &rvoip_sip_core::Method::Register
            || !transaction_id.is_server()
        {
            return Err(rvoip_sip_dialog::ExactResponseSendError {
                source: rvoip_sip_dialog::ApiError::Protocol {
                    message: "REGISTER response does not identify a server REGISTER transaction"
                        .to_string(),
                },
                disposition:
                    rvoip_sip_dialog::FinalResponseCompletionDisposition::ZeroWireRetryable,
            });
        }
        self.dialog_api
            .send_register_response_with_extras_classified(
                &transaction_id,
                fields.status_code,
                &fields.reason,
                fields.www_authenticate.as_deref(),
                fields.contact.as_deref(),
                fields.expires,
                fields.min_expires,
                &fields.service_route,
                fields.path_echo,
                &fields.associated_uri,
                &fields.extra_headers,
            )
            .await
    }

    /// Send an exact final response while preserving the transaction layer's
    /// authoritative transport-write disposition for cancellation recovery.
    pub(crate) async fn send_response_for_transaction_classified(
        &self,
        session_id: &SessionId,
        transaction_id: &TransactionKey,
        code: u16,
        sdp: Option<String>,
    ) -> std::result::Result<
        rvoip_sip_dialog::FinalResponseCompletionDisposition,
        rvoip_sip_dialog::ExactResponseSendError,
    > {
        self.dialog_api
            .send_response_for_session_transaction_classified(
                &session_id.0,
                transaction_id,
                code,
                sdp,
            )
            .await
    }

    /// Send a UAS response with application headers through a known inbound
    /// server transaction. Dialog-core verifies that the transaction belongs
    /// to the dialog resolved from `session_id` before writing anything.
    pub async fn send_response_with_options_for_transaction(
        &self,
        session_id: &SessionId,
        transaction_id: &TransactionKey,
        code: u16,
        body: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> Result<()> {
        self.dialog_api
            .send_response_with_extras_for_session_transaction(
                &session_id.0,
                transaction_id,
                code,
                body,
                extra_headers,
            )
            .await
            .map_err(|_| {
                SessionError::DialogError("Failed to send exact in-dialog response".to_string())
            })
    }

    /// Classified exact response variant that also preserves application
    /// response headers.
    pub(crate) async fn send_response_with_options_for_transaction_classified(
        &self,
        session_id: &SessionId,
        transaction_id: &TransactionKey,
        code: u16,
        body: Option<String>,
        extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    ) -> std::result::Result<
        rvoip_sip_dialog::FinalResponseCompletionDisposition,
        rvoip_sip_dialog::ExactResponseSendError,
    > {
        self.dialog_api
            .send_response_with_extras_for_session_transaction_classified(
                &session_id.0,
                transaction_id,
                code,
                body,
                extra_headers,
            )
            .await
    }

    /// ACK generation for INVITE 2xx is owned by dialog/transaction response
    /// processing. Retain the established method signature, but reject a
    /// second application-authored ACK attempt.
    pub async fn send_ack(&self, session_id: &SessionId, _response: &Response) -> Result<()> {
        Err(SessionError::InvalidTransition(format!(
            "ACK for session {} is generated automatically by the exact INVITE transaction",
            session_id.0
        )))
    }

    pub(crate) async fn send_delayed_offer_ack_exact(
        &self,
        handle: &SessionRegistryHandle,
        transaction_id: &TransactionKey,
        response: &Response,
        sdp_answer: &str,
    ) -> Result<()> {
        self.store
            .get_session_snapshot_exact(handle)
            .map_err(|_| SessionError::SessionNotFound(handle.session_id().0.clone()))?;
        self.dialog_api
            .send_delayed_offer_ack_for_session_transaction(
                &handle.session_id().0,
                transaction_id,
                response,
                sdp_answer,
            )
            .await
            .map_err(|_| {
                SessionError::DialogError(
                    "Delayed-offer ACK failed exact validation or transport write".to_string(),
                )
            })
    }

    pub(crate) async fn send_invite_2xx_ack_exact(
        &self,
        handle: &SessionRegistryHandle,
        transaction_id: &TransactionKey,
        response: &Response,
    ) -> Result<()> {
        self.store
            .get_session_snapshot_exact(handle)
            .map_err(|_| SessionError::SessionNotFound(handle.session_id().0.clone()))?;
        self.dialog_api
            .send_invite_2xx_ack_for_session_transaction(
                &handle.session_id().0,
                transaction_id,
                response,
            )
            .await
            .map_err(|_| {
                SessionError::DialogError(
                    "INVITE 2xx ACK failed exact validation or transport write".to_string(),
                )
            })
    }

    /// Compatibility facade for a default established-call BYE.
    pub async fn send_bye_session(&self, session_id: &SessionId) -> Result<()> {
        self.send_bye_with_options(session_id, ByeRequestOptions::default())
            .await
    }

    /// Compatibility facade for an established BYE with RFC 3326 Reason.
    pub async fn send_bye_session_with_reason(
        &self,
        session_id: &SessionId,
        reason: rvoip_sip_core::types::reason::Reason,
    ) -> Result<()> {
        self.send_bye_with_options(
            session_id,
            ByeRequestOptions {
                reason: Some(reason.to_string()),
                ..Default::default()
            },
        )
        .await
    }

    /// SIP_API_DESIGN_2 Phase C — UPDATE (RFC 3311) dispatch routed
    /// through the new dialog-core options surface. SDP is optional;
    /// when present it rides on the UPDATE body. The builder layer
    /// supplies a fully-populated `UpdateRequestOptions`.
    pub async fn send_update_with_options(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::UpdateRequestOptions,
    ) -> Result<TransactionKey> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.dispatch_update_with_options(&session, opts, None)
            .await
    }

    pub(crate) async fn send_update_with_options_lane_owned(
        &self,
        session: &SessionState,
        opts: UpdateRequestOptions,
    ) -> Result<TransactionKey> {
        self.dispatch_update_with_options(session, opts, None).await
    }

    async fn dispatch_update_with_options(
        &self,
        session: &SessionState,
        mut opts: UpdateRequestOptions,
        auth_header: Option<(&str, String)>,
    ) -> Result<TransactionKey> {
        opts.extra_headers = match auth_header {
            Some((name, value)) => apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Update,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
                name,
                value,
            )?,
            None => apply_outbound_extras_policy(
                rvoip_sip_core::types::Method::Update,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
            )?,
        };
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
        self.dialog_api
            .send_update_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send UPDATE: {}", e)))
    }

    /// SIP_API_DESIGN_2 Phase C — re-INVITE dispatch routed through
    /// the new dialog-core options surface so applications can
    /// attach precomputed `Authorization:` or stage extra headers.
    pub async fn send_reinvite_with_options(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::ReInviteRequestOptions,
    ) -> Result<()> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.dispatch_reinvite_with_options(&session, opts, None)
            .await
            .map(|_| ())
    }

    pub(crate) async fn send_reinvite_with_options_lane_owned(
        &self,
        session: &SessionState,
        opts: rvoip_sip_dialog::api::unified::ReInviteRequestOptions,
    ) -> Result<TransactionKey> {
        self.dispatch_reinvite_with_options(session, opts, None)
            .await
    }

    pub(crate) async fn send_reinvite_with_auth_lane_owned(
        &self,
        session: &SessionState,
        opts: rvoip_sip_dialog::api::unified::ReInviteRequestOptions,
        header_name: &str,
        header_value: String,
    ) -> Result<TransactionKey> {
        self.dispatch_reinvite_with_options(session, opts, Some((header_name, header_value)))
            .await
    }

    async fn dispatch_reinvite_with_options(
        &self,
        session: &SessionState,
        mut opts: rvoip_sip_dialog::api::unified::ReInviteRequestOptions,
        auth_header: Option<(&str, String)>,
    ) -> Result<TransactionKey> {
        // A challenged precomputed credential is replaced, not appended.
        // Keeping it would cause dialog-core to materialize a second
        // Authorization field beside the exact retry header below.
        if auth_header.is_some() {
            opts.precomputed_authorization = None;
        }
        opts.extra_headers = match auth_header {
            Some((name, value)) => apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Invite,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
                name,
                value,
            )?,
            None => apply_outbound_extras_policy(
                rvoip_sip_core::types::Method::Invite,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
            )?,
        };
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
        self.dialog_api
            .send_reinvite_with_options(&dialog_id, opts)
            .await
            .map_err(|error| {
                redacted_invite_dispatch_error(InviteDispatchFailure::ReinviteWithOptions, error)
            })
    }

    /// SIP_API_DESIGN_2 Phase C — REFER dispatch through the new
    /// dialog-core options surface; carries the full RFC 3891
    /// `Replaces`, RFC 3892 `Referred-By`, RFC 4538 `Target-Dialog`
    /// trio.
    pub async fn send_refer_with_options(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::ReferRequestOptions,
    ) -> Result<TransactionKey> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.dispatch_refer_with_options(&session, opts, None).await
    }

    pub(crate) async fn send_refer_with_options_lane_owned(
        &self,
        session: &SessionState,
        opts: ReferRequestOptions,
    ) -> Result<TransactionKey> {
        self.dispatch_refer_with_options(session, opts, None).await
    }

    async fn dispatch_refer_with_options(
        &self,
        session: &SessionState,
        mut opts: ReferRequestOptions,
        auth_header: Option<(&str, String)>,
    ) -> Result<TransactionKey> {
        opts.extra_headers = match auth_header {
            Some((name, value)) => apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Refer,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
                name,
                value,
            )?,
            None => apply_outbound_extras_policy(
                rvoip_sip_core::types::Method::Refer,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
            )?,
        };
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
        self.dialog_api
            .send_refer_with_options(&dialog_id, opts)
            .await
            .map_err(|error| redacted_dialog_operation_error("REFER", error))
    }

    /// SIP_API_DESIGN_2 Phase C — INFO dispatch through the new
    /// dialog-core options surface, replacing the legacy
    /// `send_info(content_type, body)` path.
    pub async fn send_info_with_options(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::InfoRequestOptions,
    ) -> Result<TransactionKey> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.dispatch_info_with_options(&session, opts, None).await
    }

    pub(crate) async fn send_info_with_options_lane_owned(
        &self,
        session: &SessionState,
        opts: InfoRequestOptions,
    ) -> Result<TransactionKey> {
        self.dispatch_info_with_options(session, opts, None).await
    }

    async fn dispatch_info_with_options(
        &self,
        session: &SessionState,
        mut opts: InfoRequestOptions,
        auth_header: Option<(&str, String)>,
    ) -> Result<TransactionKey> {
        opts.extra_headers = match auth_header {
            Some((name, value)) => apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Info,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
                name,
                value,
            )?,
            None => apply_outbound_extras_policy(
                rvoip_sip_core::types::Method::Info,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
            )?,
        };
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
        self.dialog_api
            .send_info_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send INFO: {}", e)))
    }

    /// Preserve the adapter's established options signature while routing the
    /// request through one exact YAML action.
    pub async fn send_bye_with_options(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::ByeRequestOptions,
    ) -> Result<()> {
        let handle = self
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.to_string()))?;
        self.dispatch_state_machine_options_exact(
            &handle,
            EventType::SendOutboundBye,
            crate::state_machine::executor::PendingOptionsSlot::Bye(Arc::new(opts)),
        )
        .await
    }

    /// Dispatch a first-attempt BYE while the executor already owns this
    /// session's exact state-machine lane. Retained authorization bookkeeping
    /// stays in the executor's working state and is published by its one
    /// canonical event commit.
    pub(crate) async fn send_bye_with_options_lane_owned(
        &self,
        session: &mut SessionState,
        mut opts: ByeRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Bye,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)
            .map_err(|_| SessionError::SessionNotFound(session.session_id.0.clone()))?;
        let dialog = self
            .dialog_api
            .dialog_manager()
            .core()
            .get_dialog(&dialog_id)
            .map_err(|_| {
                SessionError::InvalidTransition(
                    "SIP BYE exact dialog is no longer available".to_string(),
                )
            })?;
        let request_uri = dialog.remote_target.to_string();
        let next_hop = dialog
            .route_set
            .first()
            .unwrap_or(&dialog.remote_target)
            .to_string();
        let transport = self.outbound_transport_context_for_uri(&next_hop);
        let headers = mutate_retained_dialog_auth(
            session,
            &dialog_id,
            RetainedDialogAuthMode::Request,
            "BYE",
            &request_uri,
            RetainedDialogAuthRoute {
                next_hop: &next_hop,
                transport: &transport,
            },
            None,
        )?;
        opts.extra_headers.extend(headers);

        let handle = session.lifecycle_handle.as_ref().ok_or_else(|| {
            SessionError::InvalidTransition(
                "SIP BYE exact session has no lifecycle authority".to_string(),
            )
        })?;
        self.dispatch_bye_with_options(handle, &dialog_id, opts, request_uri)
            .await
    }

    /// Canonical BYE dispatch for both first attempts and challenge retries.
    /// The exact transaction generation and completion handle are installed
    /// here, beside the only dialog-layer BYE wire call.
    async fn dispatch_bye_with_options(
        &self,
        handle: &SessionRegistryHandle,
        dialog_id: &RvoipDialogId,
        opts: ByeRequestOptions,
        request_uri: String,
    ) -> Result<()> {
        self.mark_initial_invite_protocol_teardown_exact(handle);
        let generation = self.next_outgoing_bye_generation();
        let (transaction_id, completion) = self
            .dialog_api
            .send_bye_with_options_and_completion(dialog_id, opts)
            .await
            .map_err(|error| redacted_dialog_operation_error("SIP BYE", error))?;
        self.retain_outgoing_bye_transaction(
            handle,
            generation,
            transaction_id,
            completion,
            request_uri,
        );
        Ok(())
    }

    fn next_outgoing_bye_generation(&self) -> u64 {
        self.next_outgoing_bye_generation
            .fetch_add(1, Ordering::Relaxed)
    }

    /// Publish cancellation-safe intent before any BYE wire dispatch. Exact
    /// response cleanup can then preserve a terminal receipt across the small
    /// dispatch-to-wait gap, while dropping the last owner reclaims a receipt
    /// if its public future is cancelled or exits on a bookkeeping error.
    pub(crate) fn begin_outgoing_bye_wait_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<OutgoingByeWaitOwner> {
        self.store.get_session_snapshot_exact(handle).map_err(|_| {
            SessionError::SessionNotFound(format!(
                "Session {} exact BYE lifetime is unavailable",
                handle.session_id().0
            ))
        })?;
        let after_generation = self
            .outgoing_bye_tx
            .get(handle)
            .filter(|transaction| transaction.handle == *handle)
            .map_or(0, |transaction| transaction.generation);
        self.outgoing_bye_wait_intents
            .entry(handle.clone())
            .and_modify(|intent| {
                if intent.handle == *handle {
                    intent.owners = intent.owners.saturating_add(1);
                    intent.min_after_generation = intent.min_after_generation.min(after_generation);
                } else {
                    *intent = OutgoingByeWaitIntentState {
                        handle: handle.clone(),
                        owners: 1,
                        min_after_generation: after_generation,
                    };
                }
            })
            .or_insert(OutgoingByeWaitIntentState {
                handle: handle.clone(),
                owners: 1,
                min_after_generation: after_generation,
            });
        Ok(OutgoingByeWaitOwner {
            handle: handle.clone(),
            wait_intents: Arc::clone(&self.outgoing_bye_wait_intents),
            transactions: Arc::clone(&self.outgoing_bye_tx),
            generation_watch: Arc::clone(&self.outgoing_bye_generation_watch),
        })
    }

    fn retain_outgoing_bye_transaction(
        &self,
        handle: &SessionRegistryHandle,
        generation: u64,
        transaction_id: TransactionKey,
        completion: ClientTransactionCompletionHandle,
        request_uri: String,
    ) {
        let transaction = OutboundByeTransaction {
            handle: handle.clone(),
            generation,
            transaction_id,
            completion,
            request_uri,
        };
        self.outgoing_bye_tx
            .entry(handle.clone())
            .and_modify(|current| {
                if current.handle != transaction.handle
                    || current.generation < transaction.generation
                {
                    *current = transaction.clone();
                }
            })
            .or_insert(transaction);
        let sender = self
            .outgoing_bye_generation_watch
            .entry(handle.clone())
            .or_insert_with(|| tokio::sync::watch::channel(0).0)
            .clone();
        sender.send_replace(generation);
    }

    fn latest_outgoing_bye_transaction(
        &self,
        handle: &SessionRegistryHandle,
        after_generation: u64,
    ) -> Option<OutboundByeTransaction> {
        self.outgoing_bye_tx
            .get(handle)
            .map(|entry| entry.value().clone())
            .filter(|transaction| {
                transaction.handle == *handle && transaction.generation > after_generation
            })
    }

    /// Capture the exact retained-BYE generation, if any, before a state
    /// machine dispatch. A caller can later prove that this dispatch reached
    /// the wire by observing a strictly newer generation for the same
    /// session; an unrelated session cannot satisfy that proof.
    pub(crate) fn outgoing_bye_generation_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Option<u64> {
        self.outgoing_bye_tx
            .get(handle)
            .filter(|transaction| transaction.handle == *handle)
            .map(|transaction| transaction.generation)
    }

    /// Configured Timer F horizon for non-INVITE client transactions.
    pub(crate) fn non_invite_transaction_timeout(&self) -> Duration {
        self.non_invite_transaction_timeout
    }

    /// Return whether this exact session retained a BYE after `generation`.
    /// This is side-effect evidence, not an error-string classification: the
    /// coordinator uses it only to join the already-required final-response
    /// confirmation after post-send bookkeeping loses a concurrent race.
    pub(crate) fn has_outgoing_bye_after_exact(
        &self,
        handle: &SessionRegistryHandle,
        generation: u64,
    ) -> bool {
        self.outgoing_bye_tx.get(handle).is_some_and(|transaction| {
            transaction.handle == *handle && transaction.generation > generation
        })
    }

    /// Prove that an authentication event owns the latest retained BYE
    /// generation for this exact session. Stale or cross-session challenge
    /// events must not be allowed to consume the immutable BYE retry stash.
    pub(crate) fn outgoing_bye_transaction_matches_exact(
        &self,
        handle: &SessionRegistryHandle,
        transaction_id: &TransactionKey,
    ) -> bool {
        self.outgoing_bye_tx.get(handle).is_some_and(|transaction| {
            transaction.handle == *handle && transaction.transaction_id == *transaction_id
        })
    }

    /// Admit a terminal BYE completion when it names the latest retained
    /// attempt, or when a cancelled public waiter has already reclaimed that
    /// receipt. A retained newer authentication retry fences a stale outcome.
    pub(crate) fn outgoing_bye_completion_is_current_or_unretained_exact(
        &self,
        handle: &SessionRegistryHandle,
        transaction_id: &TransactionKey,
    ) -> bool {
        self.outgoing_bye_tx.get(handle).is_none_or(|transaction| {
            transaction.handle == *handle && transaction.transaction_id == *transaction_id
        })
    }

    /// Return the Request-URI from this session's latest exact outbound BYE.
    ///
    /// Digest HA2 must use the URI that was actually placed on the challenged
    /// request line. An established dialog's remote target can differ from the
    /// original To URI after Contact/target refresh processing, so rebuilding
    /// it from session metadata would produce invalid credentials.
    /// Non-INVITE transaction tombstones deliberately do not retain request
    /// wire. The adapter therefore captures the dialog remote target at the
    /// local-teardown dispatch fence and carries it with the exact generation.
    /// A 401/407 retry reuses that captured value rather than consulting
    /// mutable session metadata or challenge text.
    pub(crate) async fn outgoing_bye_request_uri_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<String> {
        self.outgoing_bye_tx
            .get(handle)
            .filter(|transaction| transaction.handle == *handle)
            .map(|entry| entry.request_uri.clone())
            .ok_or_else(|| {
                tracing::warn!(
                    error_class = "missing-retained-transaction",
                    "SIP BYE authentication retry could not recover its exact request URI"
                );
                SessionError::InvalidTransition(
                    "SIP BYE authentication retry has no retained transaction".to_string(),
                )
            })
    }

    fn clear_outgoing_bye_transaction(&self, transaction: &OutboundByeTransaction) {
        let removed = self
            .outgoing_bye_tx
            .remove_if(&transaction.handle, |_, current| {
                current.handle == transaction.handle
                    && current.generation == transaction.generation
                    && current.transaction_id == transaction.transaction_id
            });
        if removed.is_some()
            && !self
                .outgoing_bye_tx
                .get(&transaction.handle)
                .is_some_and(|current| current.handle == transaction.handle)
        {
            self.outgoing_bye_generation_watch
                .remove(&transaction.handle);
        }
    }

    /// Wait until the latest BYE attempt reaches an authoritative terminal
    /// outcome. A 2xx confirms receipt, while RFC 3261 §15.1.1 defines 481
    /// as an already-terminated peer dialog and therefore a graceful BYE
    /// result. A 401/407 is not terminal: the generic request-auth flow may
    /// install one newer transaction, which this loop follows. Every other
    /// non-2xx, timeout, or unobservable transaction fails closed.
    pub(crate) async fn wait_for_outgoing_bye_final_response_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<()> {
        let deadline = tokio::time::Instant::now() + self.non_invite_transaction_timeout;
        let mut after_generation = 0;
        let mut last_transaction = None;
        let mut generation_changes = self
            .outgoing_bye_generation_watch
            .entry(handle.clone())
            .or_insert_with(|| tokio::sync::watch::channel(0).0)
            .subscribe();
        loop {
            let transaction = loop {
                if let Some(transaction) =
                    self.latest_outgoing_bye_transaction(handle, after_generation)
                {
                    break transaction;
                }
                let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
                if remaining.is_zero() {
                    if let Some(transaction) = last_transaction.as_ref() {
                        self.clear_outgoing_bye_transaction(transaction);
                    }
                    return Err(SessionError::Timeout(
                        "SIP BYE transaction was not available before its deadline".to_string(),
                    ));
                }
                if !matches!(
                    tokio::time::timeout(remaining, generation_changes.changed()).await,
                    Ok(Ok(()))
                ) {
                    if let Some(transaction) = last_transaction.as_ref() {
                        self.clear_outgoing_bye_transaction(transaction);
                    }
                    return Err(SessionError::Timeout(
                        "SIP BYE transaction was not available before its deadline".to_string(),
                    ));
                }
            };
            last_transaction = Some(transaction.clone());
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                self.clear_outgoing_bye_transaction(&transaction);
                return Err(SessionError::Timeout(
                    "SIP BYE final response timed out".to_string(),
                ));
            }
            let response = tokio::select! {
                response = transaction.completion.wait_for_outcome(remaining) => response,
                generation_change = generation_changes.changed() => {
                    // Response processing records the exact completion before
                    // publishing any event that can run terminal cleanup. If
                    // both futures become ready together, the watch branch is
                    // allowed to win the select; re-read the completion cell so
                    // cleanup cannot turn a successful BYE into a false timeout.
                    let newer_generation_exists = self
                        .latest_outgoing_bye_transaction(handle, transaction.generation)
                        .is_some();
                    let retained_transaction_exists =
                        self.outgoing_bye_tx.get(handle).is_some_and(|retained| {
                            retained.handle == *handle
                        });
                    match resolve_outgoing_bye_generation_wake(
                        transaction.completion.current_outcome(),
                        newer_generation_exists,
                        generation_change.is_err(),
                        retained_transaction_exists,
                    ) {
                        OutgoingByeGenerationWake::UseExactOutcome(current) => current,
                        OutgoingByeGenerationWake::FollowNewerGeneration => {
                            after_generation = transaction.generation;
                            continue;
                        }
                        OutgoingByeGenerationWake::RetryCurrentGeneration => continue,
                        OutgoingByeGenerationWake::CleanupInterrupted => {
                            return Err(SessionError::Timeout(
                                "SIP BYE confirmation ended during exact local cleanup".to_string(),
                            ));
                        }
                    }
                }
            };
            let newer_transaction = self
                .latest_outgoing_bye_transaction(handle, transaction.generation)
                .is_some();
            match response {
                Ok(Some(ClientTransactionOutcome::FinalResponse(response))) => {
                    match classify_outgoing_bye_final_response(response.status_code()) {
                        OutgoingByeFinalDisposition::Confirmed => {
                            self.clear_outgoing_bye_transaction(&transaction);
                            return Ok(());
                        }
                        OutgoingByeFinalDisposition::PeerAlreadyTerminated => {
                            tracing::debug!(
                                session = %handle.session_id(),
                                "SIP BYE peer already terminated the exact dialog"
                            );
                            self.clear_outgoing_bye_transaction(&transaction);
                            return Ok(());
                        }
                        OutgoingByeFinalDisposition::AuthenticationChallenge => {
                            after_generation = transaction.generation;
                        }
                        OutgoingByeFinalDisposition::Rejected => {
                            self.clear_outgoing_bye_transaction(&transaction);
                            return Err(SessionError::ProtocolError(
                                "SIP BYE received a non-success final response".to_string(),
                            ));
                        }
                    }
                }
                Ok(Some(ClientTransactionOutcome::Failure(_))) | Ok(None) => {
                    if newer_transaction {
                        after_generation = transaction.generation;
                        continue;
                    }
                    self.clear_outgoing_bye_transaction(&transaction);
                    return Err(SessionError::Timeout(
                        "SIP BYE final response timed out".to_string(),
                    ));
                }
                Err(_) => {
                    if newer_transaction {
                        after_generation = transaction.generation;
                        continue;
                    }
                    self.clear_outgoing_bye_transaction(&transaction);
                    return Err(SessionError::DialogError(
                        "SIP BYE final response could not be observed".to_string(),
                    ));
                }
            }
        }
    }

    /// SIP_API_DESIGN_2 Phase C — NOTIFY dispatch through the new
    /// dialog-core options surface.
    pub async fn send_notify_with_options(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::NotifyRequestOptions,
    ) -> Result<TransactionKey> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.dispatch_notify_with_options(&session, opts, None)
            .await
    }

    pub(crate) async fn send_notify_with_options_lane_owned(
        &self,
        session: &SessionState,
        opts: NotifyRequestOptions,
    ) -> Result<TransactionKey> {
        self.dispatch_notify_with_options(session, opts, None).await
    }

    async fn dispatch_notify_with_options(
        &self,
        session: &SessionState,
        mut opts: NotifyRequestOptions,
        auth_header: Option<(&str, String)>,
    ) -> Result<TransactionKey> {
        opts.extra_headers = match auth_header {
            Some((name, value)) => apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Notify,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
                name,
                value,
            )?,
            None => apply_outbound_extras_policy(
                rvoip_sip_core::types::Method::Notify,
                opts.extra_headers,
                self.outbound_proxy_uri.as_ref(),
            )?,
        };
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
        self.dialog_api
            .send_notify_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send NOTIFY: {}", e)))
    }

    /// Dispatch one standalone request snapshot, optionally adding the
    /// authorization header computed for that same snapshot.
    pub(crate) async fn send_standalone_request(
        &self,
        request: StandaloneRequestOptions,
        auth_header: Option<(&str, String)>,
    ) -> Result<rvoip_sip_core::Response> {
        let authenticated = auth_header.is_some();
        match request {
            StandaloneRequestOptions::Message(mut options) => {
                options.extra_headers = match auth_header {
                    Some((name, value)) => apply_outbound_extras_policy_with_auth(
                        rvoip_sip_core::Method::Message,
                        options.extra_headers,
                        self.outbound_proxy_uri.as_ref(),
                        name,
                        value,
                    )?,
                    None => apply_outbound_extras_policy(
                        rvoip_sip_core::Method::Message,
                        options.extra_headers,
                        self.outbound_proxy_uri.as_ref(),
                    )?,
                };
                self.dialog_api
                    .send_message_out_of_dialog_with_options(options)
                    .await
                    .map_err(|error| {
                        let operation = if authenticated {
                            "MESSAGE with auth"
                        } else {
                            "MESSAGE"
                        };
                        SessionError::DialogError(format!("Failed to send {operation}: {error}"))
                    })
            }
            StandaloneRequestOptions::Options(mut options) => {
                options.extra_headers = match auth_header {
                    Some((name, value)) => apply_outbound_extras_policy_with_auth(
                        rvoip_sip_core::Method::Options,
                        options.extra_headers,
                        self.outbound_proxy_uri.as_ref(),
                        name,
                        value,
                    )?,
                    None => apply_outbound_extras_policy(
                        rvoip_sip_core::Method::Options,
                        options.extra_headers,
                        self.outbound_proxy_uri.as_ref(),
                    )?,
                };
                self.dialog_api
                    .send_options_out_of_dialog_with_options(options)
                    .await
                    .map_err(|error| {
                        let operation = if authenticated {
                            "OPTIONS with auth"
                        } else {
                            "OPTIONS"
                        };
                        SessionError::DialogError(format!("Failed to send {operation}: {error}"))
                    })
            }
            StandaloneRequestOptions::Subscribe {
                target,
                mut options,
            } => {
                options.extra_headers = match auth_header {
                    Some((name, value)) => apply_outbound_extras_policy_with_auth(
                        rvoip_sip_core::Method::Subscribe,
                        options.extra_headers,
                        self.outbound_proxy_uri.as_ref(),
                        name,
                        value,
                    )?,
                    None => apply_outbound_extras_policy(
                        rvoip_sip_core::Method::Subscribe,
                        options.extra_headers,
                        self.outbound_proxy_uri.as_ref(),
                    )?,
                };
                self.dialog_api
                    .send_subscribe_with_options(&target, options)
                    .await
                    .map_err(|error| {
                        let operation = if authenticated {
                            "SUBSCRIBE with auth"
                        } else {
                            "SUBSCRIBE"
                        };
                        SessionError::DialogError(format!("Failed to send {operation}: {error}"))
                    })
            }
        }
    }

    /// SIP_API_DESIGN_2 Phase C — out-of-dialog MESSAGE dispatch
    /// through the new dialog-core options surface. Returns the
    /// registrar's `Response` so the caller can inspect 200 OK vs
    /// 401 auth-challenge vs 404. No session_id is required because
    /// MESSAGE is fire-and-forget per RFC 3428.
    pub async fn send_message_oob_with_options(
        &self,
        opts: rvoip_sip_dialog::api::unified::MessageRequestOptions,
    ) -> Result<rvoip_sip_core::Response> {
        self.send_standalone_request(StandaloneRequestOptions::Message(opts), None)
            .await
    }

    /// SIP_API_DESIGN_2 Phase C — out-of-dialog OPTIONS dispatch.
    /// Today returns the wire-`Response` when dialog-core ships the
    /// transaction-authorship; until then dialog-core's stub returns
    /// `NotImplemented` and that error bubbles through unchanged.
    pub async fn send_options_oob_with_options(
        &self,
        opts: rvoip_sip_dialog::api::unified::OptionsRequestOptions,
    ) -> Result<rvoip_sip_core::Response> {
        self.send_standalone_request(StandaloneRequestOptions::Options(opts), None)
            .await
    }

    /// SIP_API_DESIGN_2 Phase C — out-of-dialog SUBSCRIBE dispatch.
    /// Returns the registrar's `Response` so callers can inspect
    /// `Expires`, `Min-Expires`, or 401 challenge.
    pub async fn send_subscribe_oob_with_options(
        &self,
        target: &str,
        opts: rvoip_sip_dialog::api::unified::SubscribeRequestOptions,
    ) -> Result<rvoip_sip_core::Response> {
        self.send_standalone_request(
            StandaloneRequestOptions::Subscribe {
                target: target.to_string(),
                options: opts,
            },
            None,
        )
        .await
    }

    // ─────────────────────────────────────────────────────────────────────
    // SIP_API_DESIGN_2 R2 — auth-retry mirrors for non-INVITE/non-REGISTER
    // methods. Each `send_<method>_with_auth` takes the same options
    // struct as its non-auth sibling plus a pre-computed `Authorization:`
    // (or `Proxy-Authorization:`) header, validates the application
    // extras via `apply_outbound_extras_policy_with_auth`, then injects
    // the stack-computed auth header at the end before handing off to
    // dialog-core. Called by `Action::SendRequestWithAuth` after the
    // matching client auth scheme computes the response for the cached
    // challenge.
    // ─────────────────────────────────────────────────────────────────────

    /// Authentication retry is an executor-owned continuation of an exact
    /// challenged BYE. External callers cannot safely supply only a header
    /// without the retained transaction/challenge generation.
    pub async fn send_bye_with_auth(
        &self,
        session_id: &SessionId,
        _opts: rvoip_sip_dialog::api::unified::ByeRequestOptions,
        _auth_header_name: &str,
        _auth_header_value: String,
    ) -> Result<()> {
        Err(SessionError::InvalidTransition(format!(
            "BYE authentication retry for session {} requires the exact state-machine challenge owner",
            session_id.0
        )))
    }

    /// Dispatch an authentication retry while the executor already owns the
    /// exact session lane. Digest state was computed in the lane-owned action;
    /// this path only adds that immutable header to the retained request
    /// snapshot and therefore has no competing store writer.
    pub(crate) async fn send_bye_with_auth_lane_owned(
        &self,
        session: &mut SessionState,
        mut opts: ByeRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy_with_auth(
            rvoip_sip_core::types::Method::Bye,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
            auth_header_name,
            auth_header_value,
        )?;
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
        // Authentication retries must sign and retain the challenged
        // generation's exact Request-URI.
        let handle = session.lifecycle_handle.as_ref().ok_or_else(|| {
            SessionError::InvalidTransition(
                "SIP BYE exact session has no lifecycle authority".to_string(),
            )
        })?;
        let request_uri = self.outgoing_bye_request_uri_exact(handle).await?;
        self.dispatch_bye_with_options(handle, &dialog_id, opts, request_uri)
            .await
    }

    pub async fn send_refer_with_auth(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::ReferRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<TransactionKey> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.send_refer_with_auth_lane_owned(&session, opts, auth_header_name, auth_header_value)
            .await
    }

    pub(crate) async fn send_refer_with_auth_lane_owned(
        &self,
        session: &SessionState,
        opts: ReferRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<TransactionKey> {
        self.dispatch_refer_with_options(session, opts, Some((auth_header_name, auth_header_value)))
            .await
    }

    pub async fn send_notify_with_auth(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::NotifyRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<TransactionKey> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.send_notify_with_auth_lane_owned(&session, opts, auth_header_name, auth_header_value)
            .await
    }

    pub(crate) async fn send_notify_with_auth_lane_owned(
        &self,
        session: &SessionState,
        opts: NotifyRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<TransactionKey> {
        self.dispatch_notify_with_options(
            session,
            opts,
            Some((auth_header_name, auth_header_value)),
        )
        .await
    }

    pub async fn send_info_with_auth(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::InfoRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<TransactionKey> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.send_info_with_auth_lane_owned(&session, opts, auth_header_name, auth_header_value)
            .await
    }

    pub(crate) async fn send_info_with_auth_lane_owned(
        &self,
        session: &SessionState,
        opts: InfoRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<TransactionKey> {
        self.dispatch_info_with_options(session, opts, Some((auth_header_name, auth_header_value)))
            .await
    }

    pub async fn send_update_with_auth(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::UpdateRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<TransactionKey> {
        let Some((_handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };
        self.send_update_with_auth_lane_owned(&session, opts, auth_header_name, auth_header_value)
            .await
    }

    pub(crate) async fn send_update_with_auth_lane_owned(
        &self,
        session: &SessionState,
        opts: UpdateRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<TransactionKey> {
        self.dispatch_update_with_options(
            session,
            opts,
            Some((auth_header_name, auth_header_value)),
        )
        .await
    }

    pub async fn send_message_oob_with_auth(
        &self,
        opts: rvoip_sip_dialog::api::unified::MessageRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<rvoip_sip_core::Response> {
        self.send_standalone_request(
            StandaloneRequestOptions::Message(opts),
            Some((auth_header_name, auth_header_value)),
        )
        .await
    }

    pub async fn send_options_oob_with_auth(
        &self,
        opts: rvoip_sip_dialog::api::unified::OptionsRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<rvoip_sip_core::Response> {
        self.send_standalone_request(
            StandaloneRequestOptions::Options(opts),
            Some((auth_header_name, auth_header_value)),
        )
        .await
    }

    pub async fn send_subscribe_oob_with_auth(
        &self,
        target: &str,
        opts: rvoip_sip_dialog::api::unified::SubscribeRequestOptions,
        auth_header_name: &str,
        auth_header_value: String,
    ) -> Result<rvoip_sip_core::Response> {
        self.send_standalone_request(
            StandaloneRequestOptions::Subscribe {
                target: target.to_string(),
                options: opts,
            },
            Some((auth_header_name, auth_header_value)),
        )
        .await
    }

    /// Compatibility facade for cancelling the exact pending INVITE.
    pub async fn send_cancel(&self, session_id: &SessionId) -> Result<()> {
        self.send_cancel_with_options(session_id, CancelRequestOptions::default())
            .await
    }

    /// SIP_API_DESIGN_2 §7.1 — REGISTER dispatch through the new
    /// dialog-core options surface with policy validation and outbound-
    /// proxy routing. Both the public options method and the state-machine's
    /// canonical REGISTER attempt use this exact wire boundary.
    pub async fn send_register_with_options(
        &self,
        opts: rvoip_sip_dialog::api::unified::RegisterRequestOptions,
    ) -> Result<rvoip_sip_core::Response> {
        self.send_register_with_options_and_route(opts)
            .await
            .map(|(response, _route)| response)
    }

    pub(crate) async fn send_register_with_options_and_route(
        &self,
        mut opts: rvoip_sip_dialog::api::unified::RegisterRequestOptions,
    ) -> Result<(
        rvoip_sip_core::Response,
        rvoip_sip_transport::TransportRoute,
    )> {
        // An explicit options-level proxy is rendered structurally by
        // dialog-core. Only prepend the coordinator default when no explicit
        // route was materialized, otherwise the request would carry two Route
        // headers for the same hop.
        let default_proxy = opts
            .outbound_proxy_uri
            .is_none()
            .then_some(self.outbound_proxy_uri.as_ref())
            .flatten();
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Register,
            opts.extra_headers,
            default_proxy,
        )?;
        self.dialog_api
            .send_register_with_options_and_route(opts)
            .await
            .map_err(|error| redacted_dialog_operation_error("send REGISTER", error))
    }

    /// Preserve the adapter options signature while routing CANCEL through
    /// the initiating-state YAML action and its one dialog transaction owner.
    pub async fn send_cancel_with_options(
        &self,
        session_id: &SessionId,
        opts: rvoip_sip_dialog::api::unified::CancelRequestOptions,
    ) -> Result<()> {
        let handle = self
            .store
            .lifecycle_handle(session_id)
            .ok_or_else(|| SessionError::SessionNotFound(session_id.to_string()))?;
        self.dispatch_state_machine_options_exact(
            &handle,
            EventType::SendOutboundCancel,
            crate::state_machine::executor::PendingOptionsSlot::Cancel(Arc::new(opts)),
        )
        .await
    }

    pub(crate) async fn send_cancel_with_options_lane_owned(
        &self,
        session: &SessionState,
        opts: CancelRequestOptions,
    ) -> Result<()> {
        self.dispatch_cancel_with_options(session, opts).await
    }

    async fn dispatch_cancel_with_options(
        &self,
        session: &SessionState,
        mut opts: CancelRequestOptions,
    ) -> Result<()> {
        opts.extra_headers = apply_outbound_extras_policy(
            rvoip_sip_core::types::Method::Cancel,
            opts.extra_headers,
            self.outbound_proxy_uri.as_ref(),
        )?;
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
        let _handle = session.lifecycle_handle.as_ref().ok_or_else(|| {
            SessionError::InvalidTransition(
                "SIP CANCEL exact session has no lifecycle authority".to_string(),
            )
        })?;

        self.dialog_api
            .send_cancel_with_options(&dialog_id, opts)
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to send CANCEL: {}", e)))?;

        Ok(())
    }

    /// Send an in-dialog INFO request (RFC 6086) with a caller-chosen
    /// `Content-Type`. Used for SIP-INFO DTMF (`application/dtmf-relay`),
    /// fax flow control (`application/sipfrag`), and other application-level
    /// mid-dialog signalling.
    pub async fn send_info(
        &self,
        session_id: &SessionId,
        content_type: &str,
        body: &[u8],
    ) -> Result<()> {
        self.send_info_with_options(
            session_id,
            InfoRequestOptions {
                content_type: content_type.to_string(),
                body: bytes::Bytes::copy_from_slice(body),
                ..Default::default()
            },
        )
        .await?;

        tracing::debug!(
            session = %session_id.0,
            content_type = %content_type,
            body_len = body.len(),
            "Sent INFO"
        );
        Ok(())
    }

    /// Send REFER for blind transfer (for state machine)
    pub async fn send_refer_session(&self, session_id: &SessionId, refer_to: &str) -> Result<()> {
        self.send_refer_with_options(
            session_id,
            ReferRequestOptions {
                refer_to: refer_to.to_string(),
                ..Default::default()
            },
        )
        .await?;

        tracing::info!(
            session = %session_id.0,
            target_present = !refer_to.is_empty(),
            target_bytes = refer_to.len(),
            "Sent REFER"
        );
        Ok(())
    }

    /// Read the negotiated RFC 4028 timer only for the dialog owned by the
    /// lane-held exact session. Dialog-core remains the authority for header
    /// parsing and refresher negotiation; session-core uses this immutable
    /// result solely to arm its generation-qualified lifecycle deadline.
    pub(crate) fn session_timer_settings_lane_owned(
        &self,
        session: &SessionState,
    ) -> Result<Option<(u32, bool)>> {
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
        let dialog = self
            .dialog_api
            .dialog_manager()
            .core()
            .get_dialog(&dialog_id)
            .map_err(|_| {
                SessionError::InvalidTransition(
                    "RFC 4028 timer requires the exact dialog owner".to_string(),
                )
            })?;
        Ok(dialog
            .session_expires_secs
            .filter(|interval| *interval > 0)
            .map(|interval| (interval, dialog.is_session_refresher)))
    }

    /// Fetch the SIP-level dialog identity (`Call-ID`, `local_tag`, `remote_tag`)
    /// for a session. Returns `None` if the session has no dialog yet
    /// (e.g., the INVITE hasn't been sent) or the dialog was lost.
    ///
    /// Callers use this to construct a Replaces header value when driving
    /// attended transfer from a higher layer.
    pub async fn dialog_identity(&self, session_id: &SessionId) -> Result<Option<DialogIdentity>> {
        let handle = match self.store.lifecycle_handle(session_id) {
            Some(handle) => handle,
            None => return Ok(None),
        };
        self.dialog_identity_exact(&handle).await
    }

    /// Fetch dialog identity only for a captured session generation.
    pub(crate) async fn dialog_identity_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<Option<DialogIdentity>> {
        let dialog_id = match resolve_dialog_for_handle_exact(self.store.as_ref(), handle) {
            Some(dialog_id) => dialog_id,
            None => return Ok(None),
        };

        let dialog = match self.dialog_api.get_dialog_info(&dialog_id).await {
            Ok(d) => d,
            Err(_) => return Ok(None),
        };

        if resolve_dialog_for_handle_exact(self.store.as_ref(), handle).as_ref() != Some(&dialog_id)
        {
            return Ok(None);
        }

        Ok(Some(DialogIdentity {
            call_id: dialog.call_id,
            local_tag: dialog.local_tag,
            remote_tag: dialog.remote_tag,
        }))
    }

    /// Send a re-INVITE for hold/resume or mid-call SDP updates.
    ///
    /// RFC 3261 §14 — re-INVITE is the standard mechanism for modifying an
    /// established dialog's session parameters (SDP direction attributes for
    /// hold/resume, codec changes, etc.). This previously routed through
    /// UPDATE (RFC 3311) which caused Timer F timeouts when the remote
    /// didn't answer an UPDATE promptly; re-INVITE is both more widely
    /// supported and the RFC-recommended method here.
    pub async fn send_reinvite_session(&self, session_id: &SessionId, sdp: String) -> Result<()> {
        self.send_reinvite_with_options(
            session_id,
            rvoip_sip_dialog::api::unified::ReInviteRequestOptions {
                sdp: Some(sdp),
                ..Default::default()
            },
        )
        .await
    }

    /// Clean up all mappings and resources for a session
    pub async fn cleanup_session(&self, session_id: &SessionId) -> Result<()> {
        let (handle, lane) = self.store.state_machine_lane(session_id).ok_or_else(|| {
            SessionError::SessionNotFound(format!(
                "Session {} has no current cleanup lane",
                session_id.0
            ))
        })?;
        let _state_machine_lane = lane.lock_owned().await;
        self.store
            .get_session_snapshot_exact(&handle)
            .map_err(|_| {
                SessionError::SessionNotFound(format!(
                    "Session {} exact cleanup lifetime is unavailable",
                    session_id.0
                ))
            })?;
        self.cleanup_session_exact_lane_owned(&handle).await
    }

    /// Retire only rvoip-sip's generation-qualified adapter copies for a
    /// failed inbound initial INVITE while preserving dialog-core's exact
    /// dialog and server transaction for its causal 503 fallback.
    ///
    /// This boundary must never call a lower dialog cleanup API. The caller
    /// returns a negative processing ACK only after this completes; dialog-
    /// core still owns `(dialog_id, transaction_id)` and retires that lower
    /// route after a classified Written/WireUnknown final response.
    pub(crate) async fn cleanup_failed_inbound_session_preserving_lower_route_exact(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<()> {
        let lane = self
            .store
            .state_machine_lane_retained_exact(handle)
            .ok_or_else(|| {
                SessionError::SessionNotFound(format!(
                    "Session {} exact failed-inbound cleanup lane is unavailable",
                    handle.session_id().0
                ))
            })?;
        let _state_machine_lane = lane.lock_owned().await;
        self.store
            .get_session_retained_snapshot_exact(handle)
            .map_err(|_| {
                SessionError::SessionNotFound(format!(
                    "Session {} exact failed-inbound lifetime is unavailable",
                    handle.session_id().0
                ))
            })?;

        let session_id = handle.session_id();
        let dialog_id = self
            .store
            .registry()
            .get_dialog_retained_exact(handle)
            .map(Into::into);

        self.outgoing_invite_tx
            .remove_if(session_id, |_, current| current.handle == *handle);
        self.outbound_initial_invites
            .remove_if(session_id, |_, current| current.handle == *handle);
        if let Some(transaction) = self
            .outgoing_bye_tx
            .get(handle)
            .map(|current| current.value().clone())
        {
            self.clear_outgoing_bye_transaction(&transaction);
        }
        self.outgoing_bye_wait_intents.remove(handle);
        self.outgoing_bye_generation_watch.remove(handle);
        self.outbound_request_tracker.clear_exact(handle);

        if let Some(dialog_id) = dialog_id.as_ref() {
            let lane = self.data_message_dispatch_lanes.lane(dialog_id);
            self.data_message_dispatch_lanes
                .remove_exact(dialog_id, &lane);
            self.store
                .registry()
                .clear_dialog_handle_retained(handle, dialog_id.clone().into())
                .map_err(|_| {
                    SessionError::InternalError(
                        "failed-inbound registry retirement failed (class=lifecycle)".to_string(),
                    )
                })?;
        }

        Ok(())
    }

    /// Clean up only the dialog resources owned by one retained session
    /// lifetime. The exact store check happens before any lower mutation, so a
    /// delayed cleanup cannot target a later call that reused the raw ID.
    pub(crate) async fn cleanup_session_exact(&self, handle: &SessionRegistryHandle) -> Result<()> {
        let lane = self
            .store
            .state_machine_lane_retained_exact(handle)
            .ok_or_else(|| {
                SessionError::SessionNotFound(format!(
                    "Session {} exact cleanup lane is unavailable",
                    handle.session_id().0
                ))
            })?;
        let _state_machine_lane = lane.lock_owned().await;
        self.store
            .get_session_retained_snapshot_exact(handle)
            .map_err(|_| {
                SessionError::SessionNotFound(format!(
                    "Session {} exact cleanup lifetime is unavailable",
                    handle.session_id().0
                ))
            })?;
        self.cleanup_session_exact_lane_owned(handle).await
    }

    /// Execute exact dialog cleanup while the caller already owns this
    /// session's state-machine lane. State-table actions use this entry to
    /// avoid recursive acquisition; public and shutdown paths acquire and
    /// revalidate the same exact lane in their compatibility facades above.
    pub(crate) async fn cleanup_session_exact_lane_owned(
        &self,
        handle: &SessionRegistryHandle,
    ) -> Result<()> {
        self.store
            .get_session_retained_exact(handle)
            .await
            .map_err(|_| {
                SessionError::SessionNotFound(format!(
                    "Session {} exact lifetime is unavailable",
                    handle.session_id().0
                ))
            })?;
        let session_id = handle.session_id();
        let guard = cleanup_diag::stage_guard(CleanupStage::DialogCleanup, &session_id.0);
        self.cleanup_attempt_total.fetch_add(1, Ordering::Relaxed);
        // Capture exact identifiers without removing them. The lower core
        // cleanup suspends; retaining the mappings until it returns makes a
        // timeout-cancelled caller retryable with the same dialog identity.
        let dialog_id = self
            .store
            .registry()
            .get_dialog_retained_exact(handle)
            .map(Into::into);
        let outgoing_invite = self
            .outgoing_invite_tx
            .get(session_id)
            .map(|entry| entry.value().clone())
            .filter(|transaction| {
                dialog_id
                    .as_ref()
                    .is_some_and(|dialog_id| transaction.matches(handle, dialog_id))
            });
        let outgoing_bye = self
            .outgoing_bye_tx
            .get(handle)
            .map(|entry| entry.value().clone())
            .filter(|transaction| transaction.handle == *handle);
        let outbound_initial_invite = self
            .outbound_initial_invites
            .get(session_id)
            .map(|entry| entry.value().clone())
            .filter(|binding| {
                binding.handle == *handle
                    && dialog_id
                        .as_ref()
                        .is_some_and(|dialog_id| binding.owner.dialog_id() == dialog_id)
            });

        // Incomplete confirmation/auth work cannot outlive exact terminal
        // cleanup. Drop that owner before any lower cleanup suspension so its
        // retained supervisor wakes instead of sleeping until Timer F.
        //
        // Preserve an already-terminal completion, however. A fast peer
        // response can trigger this cleanup before SendBYE unwinds and before
        // the hangup supervisor enters its confirmation wait. The completion
        // is then the only exact handoff receipt proving the wire outcome; the
        // supervisor consumes and clears it as soon as dispatch unwinds.
        if let Some(transaction) = outgoing_bye.as_ref() {
            if outgoing_bye_cleanup_should_interrupt_waiter(
                transaction.completion.current_outcome(),
                self.outgoing_bye_wait_intents
                    .get(handle)
                    .is_some_and(|intent| intent.handle == *handle),
            ) {
                self.clear_outgoing_bye_transaction(transaction);
            }
        }

        // Serialize cleanup with exact-dialog DataMessage dispatch. Holding
        // this owner through lower cleanup and mapping removal makes queued
        // senders observe an unavailable dialog rather than send after close.
        let data_message_lane = dialog_id
            .as_ref()
            .map(|dialog_id| self.data_message_dispatch_lanes.lane(dialog_id));
        let _data_message_cleanup_guard = match data_message_lane.as_ref() {
            Some(lane) => Some(Arc::clone(lane).lock_owned().await),
            None => None,
        };

        if let Some(dialog_id) = dialog_id.as_ref() {
            self.cleanup_mapped_total.fetch_add(1, Ordering::Relaxed);
            self.dialog_api
                .dialog_manager()
                .core()
                .cleanup_dialog_storage_and_transactions(dialog_id)
                .await;

            // A final response (including a 3xx followed by a fresh INVITE)
            // terminates this exact initial-INVITE owner. Retire its lower
            // ownership and exact registry mapping before allowing a
            // replacement dialog to install for the same session lifetime.
            // The managed resource itself remains registered with the
            // lifecycle authority until whole-session teardown; its exact
            // release observes that this binding has been superseded and is
            // therefore harmless.
            if let Some(binding) = outbound_initial_invite.as_ref() {
                if self
                    .dialog_api
                    .initial_invite_owner_is_retained(&binding.owner)
                    && !self
                        .dialog_api
                        .finish_initial_invite_teardown(&binding.owner)
                        .await
                {
                    return Err(SessionError::InternalError(
                        "initial INVITE exact retirement failed (class=lifecycle)".to_string(),
                    ));
                }
                self.store
                    .registry()
                    .clear_dialog_handle_retained(handle, dialog_id.clone().into())
                    .map_err(|_| {
                        SessionError::InternalError(
                            "initial INVITE registry retirement failed (class=lifecycle)"
                                .to_string(),
                        )
                    })?;
                self.outbound_initial_invites
                    .remove_if(session_id, |_, current| {
                        current.matches(handle, &binding.owner)
                    });
            }
            if let Some(lane) = data_message_lane.as_ref() {
                self.data_message_dispatch_lanes
                    .remove_exact(dialog_id, lane);
            }
        } else {
            self.cleanup_missing_total.fetch_add(1, Ordering::Relaxed);
        }

        if outgoing_invite.is_some_and(|transaction| {
            self.outgoing_invite_tx
                .remove_if(session_id, |_, mapped| {
                    mapped.handle == transaction.handle
                        && mapped.dialog_id == transaction.dialog_id
                        && mapped.transaction_id == transaction.transaction_id
                })
                .is_some()
        }) {
            self.cleanup_outgoing_invite_removed_total
                .fetch_add(1, Ordering::Relaxed);
        }
        self.outbound_request_tracker.clear_exact(handle);

        tracing::debug!(
            "Cleaned up dialog adapter mappings for session {}",
            session_id.0
        );
        guard.finish_success();
        Ok(())
    }

    // ===== Registration Methods =====

    fn start_symmetric_registration_keepalive(
        &self,
        from_uri: &str,
        route: Option<rvoip_sip_transport::TransportRoute>,
    ) {
        let Some(params) = self.symmetric_flow_params.as_ref() else {
            return;
        };
        let Some(route) = route else {
            tracing::warn!(
                "symmetric registered-flow: successful REGISTER did not retain an exact route"
            );
            return;
        };
        let destination = route.destination;

        if self
            .dialog_api
            .dialog_manager()
            .core()
            .start_outbound_ping_on_route(
                (
                    from_uri.to_string(),
                    params.reg_id,
                    params.instance_urn.clone(),
                ),
                route,
            )
        {
            tracing::info!(
                aor_present = !from_uri.is_empty(),
                aor_bytes = from_uri.len(),
                reg_id = params.reg_id,
                instance_present = !params.instance_urn.is_empty(),
                instance_bytes = params.instance_urn.len(),
                destination = %destination,
                "symmetric registered-flow: keep-alive ping started"
            );
        }
    }

    /// Send one REGISTER from an immutable options snapshot and return the
    /// exact snapshot used on the wire.
    ///
    /// This is the sole dialog-owned REGISTER implementation. Initial sends,
    /// manual and automatic refreshes, authentication retries, 423 retries,
    /// and the compatibility actions all enter here with the same options
    /// shape. The state-machine remains responsible for lifecycle decisions
    /// and retry limits; this method owns request identity, Digest mechanics,
    /// transport selection, and response classification.
    pub(crate) async fn send_register_attempt(
        &self,
        session_id: &SessionId,
        mut options: RegisterRequestOptions,
        auth: Option<&crate::auth::SipClientAuth>,
        mut context: RegisterAttemptContext,
    ) -> Result<RegisterAttemptResult> {
        let registrar_uri = options.registrar_uri.clone();
        let from_uri = options.aor_uri.clone();
        let requested_contact_uri = options.contact_uri.clone();
        let expires = options.expires;
        tracing::info!(
            session_present = !session_id.0.is_empty(),
            session_bytes = session_id.0.len(),
            registrar_present = !options.registrar_uri.is_empty(),
            registrar_bytes = registrar_uri.len(),
            aor_present = !options.aor_uri.is_empty(),
            aor_bytes = from_uri.len(),
            contact_present = !options.contact_uri.is_empty(),
            contact_bytes = options.contact_uri.len(),
            expires,
            refresh = options.refresh,
            "outbound REGISTER starting"
        );

        // Build authorization header if auth material provided.
        let (authorization, proxy_authorization) = if let Some(auth) = auth {
            let auth_state = context
                .auth_challenge_raw
                .clone()
                .or_else(|| {
                    context.auth_challenge.as_ref().map(|challenge| {
                        rvoip_auth_core::DigestAuthenticator::new(challenge.realm.clone())
                            .format_www_authenticate(challenge)
                    })
                })
                .map(|challenge_raw| {
                    let digest_challenge = context.auth_challenge.clone().or_else(|| {
                        rvoip_auth_core::DigestAuthenticator::parse_challenge(&challenge_raw).ok()
                    });
                    let nc_value = if let Some(challenge) = digest_challenge.as_ref() {
                        let nc_key = (challenge.realm.clone(), challenge.nonce.clone());
                        *context
                            .digest_nc
                            .entry(nc_key)
                            .and_modify(|n| *n += 1)
                            .or_insert(1)
                    } else {
                        1
                    };
                    let transport_context = context
                        .pending_auth_transport
                        .take()
                        .unwrap_or_else(|| self.outbound_transport_context_for_uri(&registrar_uri));
                    let status = context.pending_auth_status.unwrap_or(401);
                    (challenge_raw, nc_value, transport_context, status)
                });
            if let Some((challenge_raw, nc_value, transport_context, status)) = auth_state {
                // RFC 7616 §3.4.5 — bump the per-(realm, nonce) NC
                // counter before computing. REGISTER reuses one nonce
                // across many refreshes, so this is exactly the path
                // where carriers reject `nc=00000001` repeats.
                tracing::info!(
                    registrar_present = !registrar_uri.is_empty(),
                    registrar_bytes = registrar_uri.len(),
                    nonce_count = nc_value,
                    "outbound REGISTER authentication computing"
                );

                // REGISTER body is empty; pass `None` so the qop
                // selector picks `auth` (or legacy if no qop offered)
                // rather than `auth-int`.
                let selected = auth
                    .authorization_for_challenge_with_transport_context(
                        &challenge_raw,
                        "REGISTER",
                        &registrar_uri,
                        nc_value,
                        None,
                        &transport_context,
                    )
                    .map_err(|error| {
                        crate::errors::redacted_outbound_auth_error(
                            crate::errors::OutboundAuthOperation::Register,
                            error,
                        )
                    })?;

                tracing::info!(
                    auth_scheme = register_auth_scheme_class(&selected.scheme),
                    "outbound REGISTER authentication computed"
                );

                if status == 407 {
                    (options.authorization.clone(), Some(selected.value))
                } else {
                    (Some(selected.value), options.proxy_authorization.clone())
                }
            } else {
                tracing::debug!("No challenge stored, sending without auth");
                (
                    options.authorization.clone(),
                    options.proxy_authorization.clone(),
                )
            }
        } else {
            (
                options.authorization.clone(),
                options.proxy_authorization.clone(),
            )
        };

        // RFC 3581 NAT discovery: if the dialog manager has learned a
        // public address from a prior response's `Via:
        // …;received=…;rport=…`, rewrite the host:port portion of the
        // Contact URI so the registrar binds the new registration to
        // the externally-routable address (RFC 5626 §5). First
        // REGISTER goes out with the bind-address Contact; the
        // response carries `received=`/`rport=` which populates the
        // discovery cache; subsequent REGISTERs (refresh, auth retry)
        // use the discovered address.
        let rewritten_contact = if let Some(public) = self.dialog_api.discovered_public_addr().await
        {
            let rewritten = rewrite_contact_host(&requested_contact_uri, public);
            if rewritten != requested_contact_uri {
                tracing::info!(
                    contact_present = !requested_contact_uri.is_empty(),
                    contact_bytes = requested_contact_uri.len(),
                    rewritten_contact_present = !rewritten.is_empty(),
                    rewritten_contact_bytes = rewritten.len(),
                    public_address_family = if public.is_ipv4() { "ipv4" } else { "ipv6" },
                    public_port = public.port(),
                    "outbound REGISTER Contact rewritten from NAT discovery"
                );
            }
            rewritten
        } else {
            requested_contact_uri.clone()
        };

        // Reserve registration identity for this new logical REGISTER
        // transaction. This is registration-scoped only; dialog-core still owns
        // all in-dialog CSeq state and transaction-layer retransmissions reuse
        // the request created below.
        let registration_call_id = options
            .call_id
            .clone()
            .or_else(|| context.registration_call_id.clone())
            .unwrap_or_else(|| format!("reg-{}", uuid::Uuid::new_v4()));
        context.registration_call_id = Some(registration_call_id.clone());

        // A builder may reserve the next CSeq before it enters the lane. Use
        // that value when it is newer than the committed registration CSeq;
        // otherwise this is an auth/423/automatic retry and must advance once.
        let requested_cseq = options.cseq.unwrap_or_default();
        let registration_cseq = if requested_cseq > context.registration_cseq {
            requested_cseq
        } else {
            context.registration_cseq.saturating_add(1).max(1)
        };
        context.registration_cseq = registration_cseq;

        options.contact_uri = rewritten_contact;
        options.authorization = authorization;
        options.proxy_authorization = proxy_authorization;
        options.call_id = Some(registration_call_id);
        options.cseq = Some(registration_cseq);
        if options.outbound_contact.is_none() {
            options.outbound_contact = self.outbound_contact_params.clone();
        }
        if options.outbound_proxy_uri.is_none() {
            options.outbound_proxy_uri = self.outbound_proxy_uri.clone();
        }

        // Send REGISTER through dialog-core API and get response.
        // A5 Phase 2a: when the coordinator is configured for RFC 5626 SIP
        // Outbound, route through the outbound-aware REGISTER so the Contact
        // carries `+sip.instance` + `reg-id` + `;ob`.
        let (response, register_route) = self
            .send_register_with_options_and_route(options.clone())
            .await
            .map_err(|error| redacted_dialog_operation_error("send REGISTER", error))?;

        tracing::info!(
            "REGISTER response received: {} for session {}",
            response.status_code(),
            session_id.0
        );

        context.pending_auth_transport = self.register_response_transport_context(&response);

        let mut outcome = Self::register_attempt_outcome_from_response(
            &response,
            &requested_contact_uri,
            expires,
        );
        if let RegisterAttemptOutcome::Registered { metadata, .. } = &mut outcome {
            metadata.transport_route = Some(register_route);
        }

        Ok(RegisterAttemptResult {
            outcome,
            context,
            request_options: options,
        })
    }

    pub async fn send_subscribe(
        &self,
        session_id: &SessionId,
        from_uri: &str,
        to_uri: &str,
        event_package: &str,
        expires: u32,
    ) -> Result<Option<EventType>> {
        tracing::info!(
            "Sending SUBSCRIBE for session {} from {} to {} for event {}",
            session_id.0,
            from_uri,
            to_uri,
            event_package
        );

        // Externally configured state tables may still select SendSUBSCRIBE.
        // Keep that action as a facade over the same standalone request
        // implementation used by the public builder.
        let response = self
            .send_standalone_request(
                StandaloneRequestOptions::Subscribe {
                    target: to_uri.to_string(),
                    options: SubscribeRequestOptions {
                        event: event_package.to_string(),
                        expires,
                        from_uri: Some(from_uri.to_string()),
                        contact_uri: Some(from_uri.to_string()),
                        ..Default::default()
                    },
                },
                None,
            )
            .await?;

        tracing::info!(
            "SUBSCRIBE response: {} for session {}",
            response.status_code(),
            session_id.0
        );

        // Return the response-driven follow-up to the state-machine queue.
        // Publishing it synchronously through the global bus would re-enter
        // this exact session while its complete-event lane is still held.
        let follow_up = if response.status_code() == 200 || response.status_code() == 202 {
            Some(EventType::SubscriptionAccepted)
        } else if response.status_code() >= 400 {
            Some(EventType::SubscriptionFailed(response.status_code()))
        } else {
            None
        };

        Ok(follow_up)
    }

    /// Send a NOTIFY request within a subscription dialog
    pub async fn send_notify(
        &self,
        session_id: &SessionId,
        event_package: &str,
        body: Option<String>,
        subscription_state: Option<String>,
    ) -> Result<()> {
        tracing::info!(
            "Sending NOTIFY for session {} with event {} and state {:?}",
            session_id.0,
            event_package,
            subscription_state
        );

        self.send_notify_with_options(
            session_id,
            NotifyRequestOptions {
                event: event_package.to_string(),
                subscription_state: subscription_state.unwrap_or_default(),
                body: body.map(bytes::Bytes::from),
                ..Default::default()
            },
        )
        .await?;

        tracing::info!("NOTIFY sent successfully for session {}", session_id.0);
        Ok(())
    }

    /// Send NOTIFY for REFER implicit subscription (RFC 3515)
    ///
    /// Convenience method that automatically formats NOTIFY for transfer progress
    pub async fn send_refer_notify(
        &self,
        session_id: &SessionId,
        status_code: u16,
        reason: &str,
    ) -> Result<()> {
        tracing::info!(
            session = %session_id.0,
            status_code,
            reason_present = !reason.is_empty(),
            reason_bytes = reason.len(),
            "Sending REFER NOTIFY"
        );
        let Some((handle, _lane, session)) =
            lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
        else {
            return Err(SessionError::SessionNotFound(session_id.0.clone()));
        };

        self.send_refer_notify_lane_owned(&handle, &session, status_code, reason)
            .await
    }

    /// Send one REFER progress NOTIFY while the caller owns the exact
    /// session's state-machine lane.
    ///
    /// State-machine actions must use this entry point instead of the public
    /// raw-ID facade above. Requiring both the retained registry handle and
    /// its lane-owned snapshot prevents a delayed transfer callback from
    /// crossing session-ID reuse into a replacement dialog.
    pub(crate) async fn send_refer_notify_lane_owned(
        &self,
        handle: &SessionRegistryHandle,
        session: &SessionState,
        status_code: u16,
        reason: &str,
    ) -> Result<()> {
        if session.lifecycle_handle.as_ref() != Some(handle)
            || &session.session_id != handle.session_id()
        {
            return Err(SessionError::InvalidTransition(
                "REFER NOTIFY requires the matching exact session authority".to_string(),
            ));
        }

        // Build REFER progress through the same exact, tracked NOTIFY path as
        // application-generated requests. Keeping the immutable options in
        // the tracker preserves the sipfrag body for Digest auth-int retry,
        // correlates the final response to this transaction, and guarantees
        // automatic operator headers are applied without exposing them in
        // diagnostics.
        let subscription_state = if status_code >= 200 {
            "terminated;reason=noresource"
        } else {
            "active;expires=60"
        };
        let options = Arc::new(NotifyRequestOptions {
            event: "refer".to_string(),
            subscription_state: subscription_state.to_string(),
            content_type: Some("message/sipfrag".to_string()),
            body: Some(bytes::Bytes::from(format!(
                "SIP/2.0 {} {}",
                status_code, reason
            ))),
            subscription_id: None,
            extra_headers: self.auto_emit_extra_headers.clone(),
        });
        let lease = self
            .outbound_request_tracker
            .prepare(handle, TrackedInDialogOptions::Notify(Arc::clone(&options)))?;
        let transaction_id = self
            .send_notify_with_options_lane_owned(session, (*options).clone())
            .await
            .map_err(|error| redacted_dialog_operation_error("REFER NOTIFY", error))?;
        self.outbound_request_tracker
            .activate(lease, transaction_id)?;

        tracing::info!(
            "REFER NOTIFY sent successfully for session {}",
            handle.session_id().0
        );
        Ok(())
    }

    // ===== MESSAGE Methods =====

    /// Send a validated, byte-preserving MESSAGE on one exact dialog.
    ///
    /// `send_request_in_dialog` currently converts generic bodies through a
    /// UTF-8 `String`. Build the request with an equal-length placeholder and
    /// replace only its public `Bytes` body before dispatch, preserving the
    /// builder's exact Content-Length while retaining arbitrary binary bytes.
    pub(crate) async fn send_data_message_on_dialog(
        &self,
        dialog_id: &RvoipDialogId,
        message: SipDataMessage,
    ) -> Result<()> {
        self.send_data_message_on_dialog_driver(
            dialog_id,
            message,
            DataMessageStateLane::AcquireExact {
                expected_handle: None,
            },
        )
        .await
    }

    /// Canonical in-dialog MESSAGE owner.
    ///
    /// Both the byte-preserving data-message API and the legacy `String`
    /// facade enter this driver. It alone materializes the request, allocates
    /// CSeq, writes to the transaction layer, observes the final response, and
    /// performs the single bounded fresh-challenge retry.
    async fn send_data_message_on_dialog_driver(
        &self,
        dialog_id: &RvoipDialogId,
        message: SipDataMessage,
        mut state_lane: DataMessageStateLane<'_>,
    ) -> Result<()> {
        let manager = self.dialog_api.dialog_manager().core();
        let mut fresh_challenge = None;

        // One initial attempt plus one bounded retry for a fresh 401/407.
        // Creating a new dialog template on each pass advances CSeq as RFC
        // 3261 requires for the challenged replacement request.
        for attempt in 0..=1 {
            // DNS is intentionally outside both serialization lanes. Capture
            // the dialog routing inputs, resolve them, then acquire exact
            // state -> MESSAGE and revalidate the same route before allocating
            // a CSeq. A target refresh restarts this preflight without consuming
            // a sequence number; cleanup can win at any point and makes the
            // later exact-state resolution fail closed.
            let (mut attempt_state, dispatch_guard, mut request, next_hop, candidates) = 'route_preflight: loop {
                let route_snapshot = manager.get_dialog(dialog_id).map_err(|_| {
                    SessionError::InvalidTransition(
                        "SIP MESSAGE exact dialog is no longer available".to_string(),
                    )
                })?;
                if route_snapshot.state != DialogState::Confirmed {
                    return Err(SessionError::InvalidTransition(
                        "SIP MESSAGE requires a confirmed dialog".to_string(),
                    ));
                }
                let expected_target = route_snapshot.remote_target;
                let expected_routes = route_snapshot.route_set;
                let expected_next_hop = expected_routes
                    .first()
                    .cloned()
                    .unwrap_or_else(|| expected_target.clone());
                let candidates = manager.resolve_uri_to_candidates(&expected_next_hop).await;
                if candidates.is_empty() {
                    return Err(SessionError::DialogError(
                        "SIP MESSAGE exact next hop is unavailable".to_string(),
                    ));
                }

                // Cleanup uses this same exact state -> MESSAGE order. The
                // state lane remains owned only through active-dialog and auth
                // publication; the MESSAGE lane owns this attempt through its
                // wire/final-response outcome.
                let attempt_state = match &mut state_lane {
                    DataMessageStateLane::AcquireExact { expected_handle } => {
                        let (handle, guard, session) = lock_and_load_exact_data_message_session(
                            self.store.as_ref(),
                            dialog_id,
                        )
                        .await?;
                        match expected_handle.as_ref() {
                            Some(expected) if expected != &handle => {
                                return Err(SessionError::InvalidTransition(
                                    "SIP MESSAGE exact session generation changed before dispatch"
                                        .to_string(),
                                ));
                            }
                            None => *expected_handle = Some(handle.clone()),
                            Some(_) => {}
                        }
                        DataMessageAttemptState::AcquiredExact {
                            handle,
                            _guard: guard,
                            session: Box::new(session),
                        }
                    }
                    DataMessageStateLane::AlreadyOwned(session) => {
                        let exact_dialog =
                            resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)?;
                        if &exact_dialog != dialog_id {
                            return Err(SessionError::InvalidTransition(
                                "SIP MESSAGE lane-owned dialog identity changed before dispatch"
                                    .to_string(),
                            ));
                        }
                        let handle = session.lifecycle_handle.clone().ok_or_else(|| {
                            SessionError::InvalidTransition(
                                "SIP MESSAGE lane-owned session has no lifecycle authority"
                                    .to_string(),
                            )
                        })?;
                        DataMessageAttemptState::AlreadyOwned { handle, session }
                    }
                };
                let dispatch_lane = self.data_message_dispatch_lanes.lane(dialog_id);
                let dispatch_guard = Arc::clone(&dispatch_lane).lock_owned().await;
                let template = {
                    let mut dialog = match manager.get_dialog_mut(dialog_id) {
                        Ok(dialog) => dialog,
                        Err(_) => {
                            // Cleanup may have removed the original lane before
                            // this already-captured sender entered. Remove only
                            // this exact replacement lane; a concurrently
                            // installed successor remains independently owned.
                            self.data_message_dispatch_lanes
                                .remove_exact(dialog_id, &dispatch_lane);
                            return Err(SessionError::InvalidTransition(
                                "SIP MESSAGE exact dialog is no longer available".to_string(),
                            ));
                        }
                    };
                    if dialog.state != DialogState::Confirmed {
                        return Err(SessionError::InvalidTransition(
                            "SIP MESSAGE requires a confirmed dialog".to_string(),
                        ));
                    }
                    if dialog.remote_target != expected_target
                        || dialog.route_set != expected_routes
                    {
                        drop(dialog);
                        drop(dispatch_guard);
                        drop(attempt_state);
                        continue 'route_preflight;
                    }
                    let template = dialog.create_request_template(rvoip_sip_core::Method::Message);
                    let local_tag = template
                        .local_tag
                        .filter(|value| !value.is_empty())
                        .ok_or_else(|| {
                            SessionError::InvalidTransition(
                                "SIP MESSAGE confirmed dialog is missing its local tag".to_string(),
                            )
                        })?;
                    let remote_tag = template
                        .remote_tag
                        .filter(|value| !value.is_empty())
                        .ok_or_else(|| {
                            SessionError::InvalidTransition(
                                "SIP MESSAGE confirmed dialog is missing its remote tag"
                                    .to_string(),
                            )
                        })?;
                    let local_address = manager.local_address_for_target_and_routes(
                        &template.target_uri,
                        &template.route_set,
                    );
                    DialogRequestTemplate {
                        call_id: template.call_id,
                        from_uri: template.local_uri.to_string(),
                        from_tag: local_tag,
                        to_uri: template.remote_uri.to_string(),
                        to_tag: remote_tag,
                        request_uri: template.target_uri.to_string(),
                        cseq: template.cseq_number,
                        local_address,
                        route_set: template.route_set,
                        contact: None,
                    }
                };

                let request = build_sip_data_request(&template, message.clone()).map_err(|_| {
                    SessionError::InvalidInput(
                        "SIP data message failed local request construction".to_string(),
                    )
                })?;
                let next_hop = exact_next_hop_uri_for_request(&request).map_err(|_| {
                    SessionError::InvalidInput(
                        "SIP data message has an unusable exact next hop".to_string(),
                    )
                })?;
                if next_hop != expected_next_hop {
                    return Err(SessionError::InvalidTransition(
                        "SIP MESSAGE exact route changed during request construction".to_string(),
                    ));
                }
                break 'route_preflight (
                    attempt_state,
                    dispatch_guard,
                    request,
                    next_hop,
                    candidates,
                );
            };

            let next_hop_text = next_hop.to_string();
            let transport = self.outbound_transport_context_for_uri(&next_hop_text);
            match &mut attempt_state {
                DataMessageAttemptState::AcquiredExact {
                    handle, session, ..
                } => authorize_data_message_lane_owned_exact(
                    self.store.as_ref(),
                    handle,
                    session,
                    dialog_id,
                    &mut request,
                    &next_hop_text,
                    fresh_challenge.as_ref(),
                    &transport,
                )?,
                DataMessageAttemptState::AlreadyOwned { handle, session } => {
                    if self
                        .store
                        .registry()
                        .get_dialog_handle_exact(handle)
                        .as_ref()
                        != Some(&dialog_id.clone().into())
                    {
                        return Err(SessionError::InvalidTransition(
                            "SIP MESSAGE lane-owned exact dialog changed during authentication"
                                .to_string(),
                        ));
                    }
                    let request_uri = request.uri.to_string();
                    let headers = mutate_retained_dialog_auth(
                        session,
                        dialog_id,
                        RetainedDialogAuthMode::DataMessage {
                            fresh_challenge: fresh_challenge.as_ref(),
                        },
                        "MESSAGE",
                        &request_uri,
                        RetainedDialogAuthRoute {
                            next_hop: &next_hop_text,
                            transport: &transport,
                        },
                        Some(request.body.as_ref()),
                    )?;
                    request.headers.extend(headers);
                }
            }

            // The exact-locking facade releases its acquired state lane before
            // wire I/O. The state-machine facade merely releases this borrow;
            // its caller necessarily retains the already-owned executor lane.
            // Both retain the MESSAGE lane through the final-response outcome.
            drop(attempt_state);
            let (transaction_id, _) = manager
                // This operation owns its final response and bounded auth
                // retry. Deliberately do not publish the transaction through
                // the generic session AuthRequired path, which otherwise
                // would race a second MESSAGE retry from the state machine.
                .send_request_with_candidate_failover(request, candidates, None)
                .await
                .map_err(|error| redacted_dialog_operation_error("SIP MESSAGE", error))?;
            let response = manager
                .transaction_manager()
                .wait_for_final_response(&transaction_id, DATA_MESSAGE_FINAL_RESPONSE_TIMEOUT)
                .await
                .map_err(|_| {
                    SessionError::DialogError(
                        "SIP MESSAGE final response could not be observed".to_string(),
                    )
                })?
                .ok_or_else(|| {
                    SessionError::DialogError("SIP MESSAGE final response timed out".to_string())
                })?;
            match response.status_code() {
                200..=299 => return Ok(()),
                status @ (401 | 407) if attempt == 0 => {
                    use rvoip_sip_core::types::headers::HeaderAccess;

                    let header_name = if status == 407 {
                        rvoip_sip_core::types::header::HeaderName::ProxyAuthenticate
                    } else {
                        rvoip_sip_core::types::header::HeaderName::WwwAuthenticate
                    };
                    let values = response
                        .raw_headers(&header_name)
                        .into_iter()
                        .map(|value| String::from_utf8(value).map_err(|_| ()))
                        .collect::<std::result::Result<Vec<_>, _>>()
                        .map_err(|_| {
                            SessionError::AuthError(
                                "SIP MESSAGE challenge is not valid header text".to_string(),
                            )
                        })?;
                    if values.is_empty() {
                        return Err(SessionError::AuthError(
                            "SIP MESSAGE challenge response omitted its challenge".to_string(),
                        ));
                    }
                    let challenge = DataMessageAuthChallenge {
                        status,
                        value: values.join(", "),
                    };
                    // A retry releases this attempt's MESSAGE lane before
                    // returning to the top of the loop. Exact-locking callers
                    // have also released their acquired state lane; an
                    // executor caller still owns the lane it lent us and
                    // revalidates its exact mapping on the next pass.
                    drop(dispatch_guard);
                    fresh_challenge = Some(challenge);
                    continue;
                }
                401 | 407 => {
                    return Err(SessionError::AuthError(
                        "SIP MESSAGE authentication retry was rejected".to_string(),
                    ));
                }
                status => {
                    return Err(SessionError::ProtocolError(format!(
                        "SIP MESSAGE peer rejected delivery with status {status}"
                    )));
                }
            }
        }

        Err(SessionError::AuthError(
            "SIP MESSAGE authentication retry was exhausted".to_string(),
        ))
    }

    /// Send a MESSAGE request (can be in-dialog or out-of-dialog)
    pub async fn send_message(
        &self,
        session_id: &SessionId,
        from_uri: &str,
        to_uri: &str,
        body: String,
        in_dialog: bool,
    ) -> Result<Option<EventType>> {
        tracing::info!(
            "Sending MESSAGE for session {} from {} to {} (in_dialog: {})",
            session_id.0,
            from_uri,
            to_uri,
            in_dialog
        );

        if in_dialog {
            let Some((handle, lane, session)) =
                lock_and_load_exact_current_session(self.store.as_ref(), session_id).await
            else {
                return Err(SessionError::DialogError(
                    "No dialog for session".to_string(),
                ));
            };
            let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), &session)
                .map_err(|_| SessionError::DialogError("No dialog for session".to_string()))?;
            drop(lane);
            self.send_data_message_on_dialog_driver(
                &dialog_id,
                legacy_text_data_message(body),
                DataMessageStateLane::AcquireExact {
                    expected_handle: Some(handle),
                },
            )
            .await?;
            return Ok(None);
        }

        self.send_message_out_of_dialog_legacy(session_id, from_uri, to_uri, body)
            .await
    }

    pub(crate) async fn send_message_lane_owned(
        &self,
        session: &mut SessionState,
        from_uri: &str,
        to_uri: &str,
        body: String,
        in_dialog: bool,
    ) -> Result<Option<EventType>> {
        if in_dialog {
            self.send_message_in_dialog_lane_owned(session, body).await
        } else {
            self.send_message_out_of_dialog_legacy(&session.session_id, from_uri, to_uri, body)
                .await
        }
    }

    async fn send_message_in_dialog_lane_owned(
        &self,
        session: &mut SessionState,
        body: String,
    ) -> Result<Option<EventType>> {
        let dialog_id = resolve_dialog_for_lane_owned_session(self.store.as_ref(), session)
            .map_err(|_| SessionError::DialogError("No dialog for session".to_string()))?;
        self.send_data_message_on_dialog_driver(
            &dialog_id,
            legacy_text_data_message(body),
            DataMessageStateLane::AlreadyOwned(session),
        )
        .await?;
        tracing::info!(
            "MESSAGE sent successfully for session {}",
            session.session_id.0
        );
        Ok(None)
    }

    async fn send_message_out_of_dialog_legacy(
        &self,
        session_id: &SessionId,
        from_uri: &str,
        to_uri: &str,
        body: String,
    ) -> Result<Option<EventType>> {
        // Externally configured state tables may still select SendMESSAGE.
        // Keep that action as a facade over the same standalone request
        // implementation used by the public builder.
        let response = self
            .send_standalone_request(
                StandaloneRequestOptions::Message(MessageRequestOptions {
                    from_uri: from_uri.to_string(),
                    to_uri: to_uri.to_string(),
                    content_type: String::from("text/plain"),
                    body: bytes::Bytes::from(body),
                    ..Default::default()
                }),
                None,
            )
            .await?;

        let follow_up = if response.status_code() == 200 {
            Some(EventType::MessageDelivered)
        } else if response.status_code() >= 400 {
            Some(EventType::MessageFailed(response.status_code()))
        } else {
            None
        };
        tracing::info!("MESSAGE sent successfully for session {}", session_id.0);
        Ok(follow_up)
    }

    // ===== Helper Methods =====

    // ===== Inbound Events (from dialog-core) =====

    /// Start the dialog API (no event handling here)
    pub async fn start(&self) -> Result<()> {
        // Start the dialog API
        self.dialog_api
            .start()
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to start dialog API: {}", e)))?;

        Ok(())
    }

    /// Stop the dialog API and release its transaction transports.
    pub async fn stop(&self) -> Result<()> {
        self.dialog_api
            .stop()
            .await
            .map_err(|e| SessionError::DialogError(format!("Failed to stop dialog API: {}", e)))?;

        Ok(())
    }
}

impl Clone for DialogAdapter {
    fn clone(&self) -> Self {
        Self {
            dialog_api: self.dialog_api.clone(),
            store: self.store.clone(),
            outgoing_invite_tx: self.outgoing_invite_tx.clone(),
            outgoing_bye_tx: self.outgoing_bye_tx.clone(),
            outgoing_bye_generation_watch: self.outgoing_bye_generation_watch.clone(),
            outgoing_bye_wait_intents: self.outgoing_bye_wait_intents.clone(),
            next_outgoing_bye_generation: self.next_outgoing_bye_generation.clone(),
            non_invite_transaction_timeout: self.non_invite_transaction_timeout,
            outbound_request_tracker: self.outbound_request_tracker.clone(),
            outbound_initial_invites: self.outbound_initial_invites.clone(),
            data_message_dispatch_lanes: self.data_message_dispatch_lanes.clone(),
            auto_emit_extra_headers: self.auto_emit_extra_headers.clone(),
            global_coordinator: self.global_coordinator.clone(),
            state_machine: self.state_machine.clone(),
            outbound_proxy_uri: self.outbound_proxy_uri.clone(),
            outbound_contact_params: self.outbound_contact_params.clone(),
            symmetric_flow_params: self.symmetric_flow_params.clone(),
            registration_auto_refresh: self.registration_auto_refresh,
            registration_refresh_jitter_percent: self.registration_refresh_jitter_percent,
            registration_refresh_admission: self.registration_refresh_admission.clone(),
            registration_refresh_tasks: self.registration_refresh_tasks.clone(),
            registration_refresh_retained: self.registration_refresh_retained.clone(),
            next_registration_refresh_generation: self.next_registration_refresh_generation.clone(),
            #[cfg(test)]
            registration_refresh_dispatch_pause: self.registration_refresh_dispatch_pause.clone(),
            cleanup_attempt_total: self.cleanup_attempt_total.clone(),
            cleanup_mapped_total: self.cleanup_mapped_total.clone(),
            cleanup_missing_total: self.cleanup_missing_total.clone(),
            cleanup_outgoing_invite_removed_total: self
                .cleanup_outgoing_invite_removed_total
                .clone(),
            trace_redactor: self.trace_redactor.clone(),
        }
    }
}

#[cfg(test)]
// Policy helpers remain below this focused diagnostic module so the production
// API stays grouped with its documentation.
#[allow(clippy::items_after_test_module)]
mod tests {
    use super::*;
    use crate::state_table::Role;

    #[test]
    fn failed_inbound_adapter_cleanup_preserves_lower_response_authority() {
        let source = include_str!("dialog_adapter.rs");
        let cleanup = source
            .split(
                "    pub(crate) async fn cleanup_failed_inbound_session_preserving_lower_route_exact(",
            )
            .nth(1)
            .and_then(|tail| tail.split("    /// Clean up only the dialog resources").next())
            .expect("failed-inbound preserving cleanup source");

        for forbidden in [
            "cleanup_dialog_storage_and_transactions",
            "cleanup_transaction_receiver",
            "terminate_transaction",
            "finish_initial_invite_teardown",
            "remove_dialog_storage",
        ] {
            assert!(
                !cleanup.contains(forbidden),
                "upper failed-inbound cleanup retired lower response authority via {forbidden}"
            );
        }
        assert!(cleanup.contains("clear_dialog_handle_retained"));
        assert!(cleanup.contains("outbound_request_tracker.clear_exact"));
        assert!(cleanup.contains("data_message_dispatch_lanes"));
    }

    fn transfer_observation(id: usize) -> crate::api::events::Event {
        crate::api::events::Event::ReferProgress {
            call_id: SessionId(format!("transfer-observer-{id}")),
            status_code: 180,
            reason: "Ringing".to_string(),
        }
    }

    #[tokio::test]
    async fn post_commit_transfer_observation_ignores_absent_and_full_observers() {
        use rvoip_infra_common::events::EventCoordinatorConfig;

        let absent = Arc::new(
            GlobalEventCoordinator::new(
                EventCoordinatorConfig::monolithic().with_channel_capacity(1),
            )
            .await
            .expect("create coordinator without observer"),
        );
        tokio::time::timeout(
            Duration::from_secs(1),
            spawn_api_event_observation(Arc::clone(&absent), transfer_observation(1)),
        )
        .await
        .expect("absent observer blocked detached publication")
        .expect("absent-observer publication task panicked");
        absent.shutdown().await.expect("shutdown absent fixture");

        let saturated = Arc::new(
            GlobalEventCoordinator::new(
                EventCoordinatorConfig::monolithic().with_channel_capacity(1),
            )
            .await
            .expect("create saturated-observer coordinator"),
        );
        let observer = saturated
            .subscribe("session_to_app")
            .await
            .expect("subscribe bounded app observer");
        tokio::time::timeout(
            Duration::from_secs(1),
            spawn_api_event_observation(Arc::clone(&saturated), transfer_observation(2)),
        )
        .await
        .expect("first observation publication stalled")
        .expect("first observation task panicked");
        tokio::time::timeout(Duration::from_secs(1), async {
            while observer.is_empty() {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("first observation never filled bounded observer queue");
        assert_eq!(observer.len(), 1, "observer queue must be full");

        for id in 3..=4 {
            tokio::time::timeout(
                Duration::from_secs(1),
                spawn_api_event_observation(Arc::clone(&saturated), transfer_observation(id)),
            )
            .await
            .expect("full observer affected detached publication")
            .expect("full-observer publication task panicked");
        }
        assert_eq!(observer.len(), 1, "test must retain observer pressure");

        drop(observer);
        saturated
            .shutdown()
            .await
            .expect("shutdown saturated fixture");
    }

    #[test]
    fn fast_register_200_updates_one_lane_owned_state() {
        let mut session = SessionState::new(SessionId::new(), Role::UAC);
        session.registration_retry_count = 2;
        session.registration_last_failure = Some("old failure".into());
        session.local_sdp = Some("v=0\r\n".into());
        let now = Instant::now();

        let effect = record_registration_success_state(
            &mut session,
            RegistrationSuccessStateInput {
                registrar_uri: "sip:registrar.example.test",
                from_uri: "sip:alice@example.test",
                contact_uri: "sip:alice@192.0.2.10:5060",
                accepted_expires: 600,
                now,
                next_refresh_at: None,
                metadata: RegistrationResponseMetadata {
                    service_route: Some(vec!["sip:edge.example.test;lr".into()]),
                    pub_gruu: Some("sip:alice@example.test;gr=public".into()),
                    temp_gruu: Some("sip:opaque@example.test;gr=temp".into()),
                    transport_route: None,
                },
            },
        );

        assert!(session.is_registered);
        assert_eq!(session.registration_expires, Some(600));
        assert_eq!(session.registration_accepted_expires, Some(600));
        assert_eq!(session.registration_registered_at, Some(now));
        assert_eq!(session.registration_retry_count, 0);
        assert!(session.registration_last_failure.is_none());
        assert_eq!(session.local_sdp.as_deref(), Some("v=0\r\n"));
        assert!(matches!(
            effect,
            RegistrationPostCommitEffect::Registered {
                accepted_expires: 600,
                ..
            }
        ));
    }

    #[test]
    fn register_wire_helper_has_no_session_store_writer() {
        let source = include_str!("dialog_adapter.rs");
        let helper = source
            .split("pub(crate) async fn send_register_attempt(")
            .nth(1)
            .and_then(|tail| tail.split("pub async fn send_subscribe(").next())
            .expect("send_register_attempt source");
        assert!(!helper.contains("self.store"));
        assert!(!helper.contains("update_session_with"));
    }

    #[test]
    fn recorded_bye_success_wins_simultaneous_cleanup_watch_close() {
        let outcome = Ok(Some(ClientTransactionOutcome::FinalResponse(
            rvoip_sip_core::Response::new(rvoip_sip_core::StatusCode::Ok),
        )));

        match resolve_outgoing_bye_generation_wake(outcome, false, true, false) {
            OutgoingByeGenerationWake::UseExactOutcome(Ok(Some(
                ClientTransactionOutcome::FinalResponse(response),
            ))) => assert_eq!(response.status_code(), 200),
            _ => panic!("the recorded exact BYE response must outrank cleanup watch closure"),
        }
    }

    #[test]
    fn bye_final_response_classifies_crossed_481_as_graceful_terminal() {
        assert_eq!(
            classify_outgoing_bye_final_response(200),
            OutgoingByeFinalDisposition::Confirmed
        );
        assert_eq!(
            classify_outgoing_bye_final_response(299),
            OutgoingByeFinalDisposition::Confirmed
        );
        assert_eq!(
            classify_outgoing_bye_final_response(401),
            OutgoingByeFinalDisposition::AuthenticationChallenge
        );
        assert_eq!(
            classify_outgoing_bye_final_response(407),
            OutgoingByeFinalDisposition::AuthenticationChallenge
        );
        assert_eq!(
            classify_outgoing_bye_final_response(481),
            OutgoingByeFinalDisposition::PeerAlreadyTerminated
        );
        for rejected in [300, 403, 408, 480, 482, 500, 603] {
            assert_eq!(
                classify_outgoing_bye_final_response(rejected),
                OutgoingByeFinalDisposition::Rejected,
                "unexpected graceful classification for {rejected}"
            );
        }
    }

    #[test]
    fn recorded_bye_success_survives_cleanup_before_waiter_lookup() {
        let outcome = Ok(Some(ClientTransactionOutcome::FinalResponse(
            rvoip_sip_core::Response::new(rvoip_sip_core::StatusCode::Ok),
        )));

        assert!(!outgoing_bye_cleanup_should_interrupt_waiter(outcome, true));
        assert!(outgoing_bye_cleanup_should_interrupt_waiter(Ok(None), true));
        assert!(outgoing_bye_cleanup_should_interrupt_waiter(
            Ok(Some(ClientTransactionOutcome::FinalResponse(
                rvoip_sip_core::Response::new(rvoip_sip_core::StatusCode::Ok),
            ))),
            false,
        ));
    }

    #[test]
    fn exact_response_transaction_diagnostics_are_bounded_and_redacted() {
        const SECRET_BRANCH: &str = "z9hG4bK-exact-response-secret-branch";
        const SECRET_METHOD: &str = "X-EXACT-RESPONSE-SECRET-METHOD";
        let transaction = TransactionKey::new(
            SECRET_BRANCH.to_string(),
            rvoip_sip_core::Method::Extension(SECRET_METHOD.to_string()),
            true,
        );

        let diagnostics = exact_response_transaction_diagnostics(&transaction);
        let rendered = format!("{diagnostics:?}");
        assert_eq!(diagnostics, ("extension", "server"));
        assert!(!rendered.contains(SECRET_BRANCH));
        assert!(!rendered.contains(SECRET_METHOD));

        let source = include_str!("dialog_adapter.rs");
        let forbidden_raw_format = ["via transaction ", "{}"].concat();
        assert!(
            !source.contains(&forbidden_raw_format),
            "exact response diagnostics regained raw transaction formatting"
        );
    }

    #[tokio::test]
    async fn initial_invite_publishes_exact_dialog_before_wire_dispatch() {
        let store = SessionStore::new();
        let session_id = SessionId::new();
        let created = store
            .create_session(session_id.clone(), crate::state_table::Role::UAC, false)
            .await
            .expect("create exact initial-INVITE session");
        let handle = created
            .lifecycle_handle
            .clone()
            .expect("initial INVITE has exact lifecycle handle");
        let dialog_id = RvoipDialogId::new();

        publish_initial_invite_dialog_exact(&store, &handle, &dialog_id)
            .expect("publish exact dialog before dispatch");
        let published = store
            .get_session_snapshot(&session_id)
            .await
            .expect("read pre-wire session publication");
        assert_eq!(
            published
                .dialog_id
                .as_ref()
                .map(crate::types::DialogId::as_uuid),
            Some(&dialog_id.0)
        );

        publish_initial_invite_dialog_exact(&store, &handle, &dialog_id)
            .expect("same exact dialog publication is idempotent");
        let replacement = RvoipDialogId::new();
        assert!(matches!(
            publish_initial_invite_dialog_exact(&store, &handle, &replacement),
            Err(SessionError::InvalidTransition(_))
        ));
        assert_eq!(
            store
                .get_session_snapshot(&session_id)
                .await
                .expect("read exact dialog after rejected replacement")
                .dialog_id
                .as_ref()
                .map(crate::types::DialogId::as_uuid),
            Some(&dialog_id.0)
        );

        store
            .registry()
            .map_dialog_exact(
                handle.key(),
                handle.slot_revision(),
                dialog_id.clone().into(),
            )
            .expect("install initial exact registry dialog");
        assert!(store
            .registry()
            .clear_dialog_handle_retained(&handle, dialog_id.clone().into())
            .expect("retire initial exact registry dialog"));
        store
            .registry()
            .map_dialog_exact(
                handle.key(),
                handle.slot_revision(),
                replacement.clone().into(),
            )
            .expect("install registry-proven redirect replacement");
        publish_initial_invite_dialog_exact(&store, &handle, &replacement)
            .expect("adopt registry-proven redirect replacement");
        assert_eq!(
            store
                .get_session_snapshot(&session_id)
                .await
                .expect("read registry-proven replacement")
                .dialog_id
                .as_ref()
                .map(crate::types::DialogId::as_uuid),
            Some(&replacement.0)
        );
    }

    #[tokio::test]
    async fn invite_retry_exact_resolver_uses_registry_without_compatibility_map() {
        let store = SessionStore::new();
        let session_id = SessionId::new();
        let created = store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create exact INVITE-retry session");
        let handle = created
            .lifecycle_handle
            .clone()
            .expect("INVITE-retry exact handle");

        assert!(matches!(
            resolve_exact_invite_retry_dialog(&store, &session_id),
            Err(SessionError::SessionNotFound(_))
        ));

        // No DialogAdapter (and therefore no compatibility DashMap) exists in
        // this fixture. The exact registry mapping is sufficient by design.
        let dialog_id = RvoipDialogId::new();
        store
            .registry()
            .map_dialog_handle(&handle, dialog_id.clone().into())
            .expect("install canonical exact dialog mapping");
        assert_eq!(
            resolve_exact_invite_retry_dialog(&store, &session_id)
                .expect("resolve exact registry-owned dialog"),
            dialog_id
        );
    }

    #[tokio::test]
    async fn invite_retry_exact_resolver_cannot_cross_raw_id_reuse() {
        let store = SessionStore::new();
        let session_id = SessionId("invite-retry-reused-session".to_string());
        let generation_a = store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create INVITE-retry generation A");
        let handle_a = generation_a
            .lifecycle_handle
            .clone()
            .expect("generation A exact handle");
        let stale_key = handle_a.key().clone();
        let stale_revision = handle_a.slot_revision();
        let dialog_a = RvoipDialogId::new();
        store
            .registry()
            .map_dialog_handle(&handle_a, dialog_a.clone().into())
            .expect("map generation A dialog");
        assert_eq!(
            resolve_exact_invite_retry_dialog(&store, &session_id)
                .expect("resolve generation A dialog"),
            dialog_a
        );

        store
            .remove_session_exact(&handle_a)
            .await
            .expect("retire INVITE-retry generation A");
        assert!(matches!(
            resolve_exact_invite_retry_dialog(&store, &session_id),
            Err(SessionError::SessionNotFound(_))
        ));
        drop(handle_a);
        drop(generation_a);
        assert!(store.authority().elapse_reuse_horizon_for_test(&session_id));

        let generation_b = store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create INVITE-retry generation B");
        let handle_b = generation_b
            .lifecycle_handle
            .clone()
            .expect("generation B exact handle");
        let dialog_b = RvoipDialogId::new();
        store
            .registry()
            .map_dialog_handle(&handle_b, dialog_b.clone().into())
            .expect("map generation B dialog");

        assert!(store
            .registry()
            .get_dialog_exact(&stale_key, stale_revision)
            .is_none());
        assert_eq!(
            resolve_exact_invite_retry_dialog(&store, &session_id)
                .expect("raw ID resolves only current generation B"),
            dialog_b
        );
    }

    #[test]
    fn invite_retry_resolution_has_no_polling_or_compatibility_fallback() {
        let source = include_str!("dialog_adapter.rs");
        let resolver = rust_function_source(source, "resolve_exact_invite_retry_dialog");
        assert_eq!(resolver.matches(".lifecycle_handle(").count(), 1);
        assert_eq!(
            resolver.matches("resolve_dialog_for_handle_exact(").count(),
            1
        );
        assert!(!resolver.contains("session_to_dialog"));

        for (retry, lower_wire) in [
            ("resend_invite_with_auth", ".send_invite_with_auth_options("),
            (
                "resend_invite_with_session_timer_override",
                ".send_invite_with_session_timer_options(",
            ),
        ] {
            let body = rust_function_source(source, retry);
            assert_eq!(
                body.matches("resolve_exact_invite_retry_dialog(").count(),
                1,
                "{retry} must resolve its exact dialog once"
            );
            for forbidden in [
                "session_to_dialog",
                "tokio::time::sleep",
                "Duration::",
                "Instant::",
                "loop {",
            ] {
                assert!(
                    !body.contains(forbidden),
                    "{retry} regained obsolete polling/fallback token {forbidden}"
                );
            }
            let exact_resolution = body
                .find("resolve_exact_invite_retry_dialog(")
                .expect("exact retry resolution");
            let wire = body.find(lower_wire).expect("retry lower wire dispatch");
            assert!(exact_resolution < wire);
        }

        let initial_dispatch = rust_function_source(source, "send_initial_invite_staged");
        let install = initial_dispatch
            .find("install_adapter_bindings")
            .expect("exact mapping installation");
        let publish = initial_dispatch
            .find("publish_initial_invite_dialog_exact")
            .expect("exact state publication");
        let wire = initial_dispatch
            .find("dispatch_initial_invite")
            .expect("initial/redirect wire dispatch");
        assert!(
            install < publish && publish < wire,
            "initial and redirect INVITEs must install mapping, publish state, then dispatch wire"
        );
    }

    #[tokio::test]
    async fn registration_refresh_shutdown_cooperatively_cancels_long_sleep() {
        let coordinator = crate::api::unified::UnifiedCoordinator::new(
            crate::api::unified::Config::local("refresh-drain", 0),
        )
        .await
        .expect("coordinator");
        let adapter = Arc::clone(coordinator.dialog_adapter());
        let session_id = SessionId::new();
        let created = adapter
            .store
            .create_session(session_id, Role::UAC, false)
            .await
            .expect("refresh session");
        let handle = created
            .lifecycle_handle
            .clone()
            .expect("refresh exact handle");
        adapter
            .schedule_registration_refresh(handle, Some(Instant::now() + Duration::from_secs(60)));
        assert_eq!(adapter.registration_refresh_tasks.len(), 1);
        assert_eq!(adapter.registration_refresh_retained.count(), 1);
        assert_eq!(
            adapter.perf_diagnostic_counts()["registration_refresh_retained_tasks"],
            1
        );

        adapter
            .abort_all_registration_refreshes_and_wait()
            .await
            .expect("cooperative refresh cancellation drained");
        assert!(adapter.registration_refresh_tasks.is_empty());
        assert_eq!(adapter.registration_refresh_retained.count(), 0);
        assert!(!adapter.registration_refresh_retained.panicked());
        assert_eq!(
            adapter.perf_diagnostic_counts()["registration_refresh_retained_tasks"],
            0
        );

        coordinator
            .shutdown_gracefully(Some(Duration::from_secs(1)))
            .await
            .expect("coordinator shutdown remains idempotent");
    }

    #[tokio::test]
    async fn paused_refresh_cannot_target_reused_session_generation() {
        let coordinator = crate::api::unified::UnifiedCoordinator::new(
            crate::api::unified::Config::local("refresh-generation", 0),
        )
        .await
        .expect("coordinator");
        let adapter = Arc::clone(coordinator.dialog_adapter());
        let session_id = SessionId::new();
        let created_a = adapter
            .store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("generation A");
        let handle_a = created_a
            .lifecycle_handle
            .clone()
            .expect("generation A exact handle");
        let pause = Arc::new(RegistrationRefreshDispatchPause::new());
        *adapter
            .registration_refresh_dispatch_pause
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(Arc::clone(&pause));

        adapter.schedule_registration_refresh(handle_a.clone(), Some(Instant::now()));
        tokio::time::timeout(Duration::from_secs(1), pause.wait_entered())
            .await
            .expect("refresh reached pre-dispatch pause");

        adapter
            .store
            .remove_session_exact(&handle_a)
            .await
            .expect("retire generation A");
        // Production deliberately quarantines a retired raw identifier for
        // the anti-reuse horizon. Advance only that test-owned deadline so B
        // can coexist with the still-paused exact-A refresh; releasing the
        // pause below then proves the stale handle cannot enter B's lane.
        assert!(adapter
            .store
            .authority()
            .elapse_reuse_horizon_for_test(&session_id));
        let created_b = adapter
            .store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("generation B");
        let handle_b = created_b
            .lifecycle_handle
            .clone()
            .expect("generation B exact handle");
        adapter
            .store
            .update_session_exact_with(&handle_b, None, |session| {
                session.registration_retry_count = 77;
            })
            .expect("mark generation B");
        let before = adapter
            .store
            .get_session_snapshot_exact(&handle_b)
            .expect("generation B before stale wake");

        *adapter
            .registration_refresh_dispatch_pause
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = None;
        pause.release();
        tokio::time::timeout(
            Duration::from_secs(1),
            adapter.registration_refresh_retained.wait_idle(),
        )
        .await
        .expect("stale refresh completed");

        let after = adapter
            .store
            .get_session_snapshot_exact(&handle_b)
            .expect("generation B after stale wake");
        assert_eq!(after.revision(), before.revision());
        assert_eq!(after.registration_retry_count, 77);
        assert_eq!(after.registration_call_id, None);

        coordinator
            .shutdown_gracefully(Some(Duration::from_secs(1)))
            .await
            .expect("coordinator shutdown");
    }

    #[tokio::test]
    async fn stale_refresh_schedule_cannot_replace_reused_generation_task() {
        let coordinator = crate::api::unified::UnifiedCoordinator::new(
            crate::api::unified::Config::local("refresh-stale-schedule", 0),
        )
        .await
        .expect("coordinator");
        let adapter = Arc::clone(coordinator.dialog_adapter());
        let session_id = SessionId::new();
        let created_a = adapter
            .store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("generation A");
        let handle_a = created_a
            .lifecycle_handle
            .clone()
            .expect("generation A exact handle");
        adapter
            .store
            .remove_session_exact(&handle_a)
            .await
            .expect("retire generation A");
        assert!(adapter
            .store
            .authority()
            .elapse_reuse_horizon_for_test(&session_id));
        let created_b = adapter
            .store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("generation B");
        let handle_b = created_b
            .lifecycle_handle
            .clone()
            .expect("generation B exact handle");

        let refresh_at = Instant::now() + Duration::from_secs(60);
        adapter.schedule_registration_refresh(handle_b.clone(), Some(refresh_at));
        let generation_b = {
            let task = adapter
                .registration_refresh_tasks
                .get(&session_id)
                .expect("generation B refresh task");
            assert_eq!(task.handle, handle_b);
            task.generation
        };

        // Simulate a delayed generation-A post-commit effect arriving after B
        // has published its own refresh owner.
        adapter.schedule_registration_refresh(handle_a, Some(refresh_at));

        let task = adapter
            .registration_refresh_tasks
            .get(&session_id)
            .expect("generation B refresh survives stale schedule");
        assert_eq!(task.handle, handle_b);
        assert_eq!(task.generation, generation_b);
        drop(task);
        assert_eq!(adapter.registration_refresh_retained.count(), 1);

        adapter
            .abort_all_registration_refreshes_and_wait()
            .await
            .expect("refresh tasks drained");
        coordinator
            .shutdown_gracefully(Some(Duration::from_secs(1)))
            .await
            .expect("coordinator shutdown");
    }

    #[tokio::test]
    async fn stale_refresh_abort_cannot_cancel_reused_generation_task() {
        let coordinator = crate::api::unified::UnifiedCoordinator::new(
            crate::api::unified::Config::local("refresh-stale-abort", 0),
        )
        .await
        .expect("coordinator");
        let adapter = Arc::clone(coordinator.dialog_adapter());
        let session_id = SessionId::new();
        let created_a = adapter
            .store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("generation A");
        let handle_a = created_a
            .lifecycle_handle
            .clone()
            .expect("generation A exact handle");
        adapter
            .store
            .remove_session_exact(&handle_a)
            .await
            .expect("retire generation A");
        assert!(adapter
            .store
            .authority()
            .elapse_reuse_horizon_for_test(&session_id));
        let created_b = adapter
            .store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("generation B");
        let handle_b = created_b
            .lifecycle_handle
            .clone()
            .expect("generation B exact handle");

        adapter.schedule_registration_refresh(
            handle_b.clone(),
            Some(Instant::now() + Duration::from_secs(60)),
        );
        let generation_b = adapter
            .registration_refresh_tasks
            .get(&session_id)
            .expect("generation B refresh task")
            .generation;

        // Simulate generation A's delayed failure/unregistration completion.
        adapter.abort_registration_refresh_exact(&handle_a);

        let task = adapter
            .registration_refresh_tasks
            .get(&session_id)
            .expect("generation B refresh survives stale abort");
        assert_eq!(task.handle, handle_b);
        assert_eq!(task.generation, generation_b);
        drop(task);
        assert_eq!(adapter.registration_refresh_retained.count(), 1);

        adapter.abort_registration_refresh_exact(&handle_b);
        tokio::time::timeout(
            Duration::from_secs(1),
            adapter.registration_refresh_retained.wait_idle(),
        )
        .await
        .expect("generation B refresh cancellation drained");
        coordinator
            .shutdown_gracefully(Some(Duration::from_secs(1)))
            .await
            .expect("coordinator shutdown");
    }

    #[tokio::test]
    async fn refresh_without_yaml_transition_does_not_write_or_dispatch() {
        let coordinator = crate::api::unified::UnifiedCoordinator::new(
            crate::api::unified::Config::local("refresh-no-transition", 0),
        )
        .await
        .expect("coordinator");
        let adapter = Arc::clone(coordinator.dialog_adapter());
        let session_id = SessionId::new();
        let created = adapter
            .store
            .create_session(session_id, Role::UAC, false)
            .await
            .expect("idle registration session");
        let handle = created.lifecycle_handle.clone().expect("idle exact handle");
        let before = adapter
            .store
            .get_session_snapshot_exact(&handle)
            .expect("snapshot before no-transition refresh");

        adapter.schedule_registration_refresh(handle.clone(), Some(Instant::now()));
        tokio::time::timeout(
            Duration::from_secs(1),
            adapter.registration_refresh_retained.wait_idle(),
        )
        .await
        .expect("no-transition refresh completed");

        let after = adapter
            .store
            .get_session_snapshot_exact(&handle)
            .expect("snapshot after no-transition refresh");
        assert_eq!(after.revision(), before.revision());
        assert_eq!(after.registration_call_id, None);
        assert_eq!(after.registration_cseq, 0);
        assert_eq!(after.registration_retry_count, 0);

        let source = include_str!("dialog_adapter.rs");
        let removed_fallback = ["send_registration_refresh", "_direct"].concat();
        assert!(!source.contains(&removed_fallback));

        coordinator
            .shutdown_gracefully(Some(Duration::from_secs(1)))
            .await
            .expect("coordinator shutdown");
    }

    const RETAINED_AUTH_PASSWORD: &str = "retained-auth-password";

    fn retained_auth_challenge(realm: &str, nonce: &str, stale: bool, qop: &str) -> String {
        let stale = if stale { ", stale=true" } else { "" };
        format!("Digest realm=\"{realm}\", nonce=\"{nonce}\", algorithm=MD5, qop=\"{qop}\"{stale}")
    }

    fn retained_auth_session(dialog_id: &RvoipDialogId, origin_target: &str) -> SessionState {
        let mut session = SessionState::new(SessionId::new(), Role::UAC);
        session.dialog_id = Some(dialog_id.clone().into());
        session.dialog_established = true;
        session.call_state = crate::types::CallState::Active;
        session.remote_uri = Some(origin_target.to_string());
        session.auth = Some(crate::auth::SipClientAuth::digest(
            "retained-auth-user",
            RETAINED_AUTH_PASSWORD,
        ));
        session
    }

    fn retain_digest_credential(
        session: &mut SessionState,
        kind: crate::session_store::state::InviteCredentialKind,
        protection_target: &str,
        realm: &str,
        nonce: &str,
        qop: &str,
    ) {
        session.invite_authorization_credentials.push(
            crate::session_store::state::InviteAuthorizationCredential {
                kind,
                protection_target: protection_target.to_string(),
                challenge_raw: retained_auth_challenge(realm, nonce, false, qop),
                realm: realm.to_string(),
                nonce: Some(nonce.to_string()),
                stale_refreshes: 0,
                value: String::new(),
            },
        );
    }

    fn typed_auth_value(header: &rvoip_sip_core::types::TypedHeader) -> (&'static str, String) {
        match header {
            rvoip_sip_core::types::TypedHeader::Authorization(value) => {
                ("origin", value.to_string())
            }
            rvoip_sip_core::types::TypedHeader::ProxyAuthorization(value) => {
                ("proxy", value.to_string())
            }
            rvoip_sip_core::types::TypedHeader::Other(
                rvoip_sip_core::types::HeaderName::Authorization,
                rvoip_sip_core::types::headers::HeaderValue::Raw(value),
            ) => (
                "origin",
                String::from_utf8(value.clone()).expect("validated origin auth text"),
            ),
            rvoip_sip_core::types::TypedHeader::Other(
                rvoip_sip_core::types::HeaderName::ProxyAuthorization,
                rvoip_sip_core::types::headers::HeaderValue::Raw(value),
            ) => (
                "proxy",
                String::from_utf8(value.clone()).expect("validated proxy auth text"),
            ),
            other => panic!("unexpected retained auth header: {other:?}"),
        }
    }

    async fn install_active_data_message_session(
        store: &SessionStore,
        session_id: SessionId,
        dialog_id: &RvoipDialogId,
        with_route_auth: bool,
    ) -> SessionRegistryHandle {
        let created = store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create exact MESSAGE session");
        let handle = created
            .lifecycle_handle
            .clone()
            .expect("MESSAGE session has an exact lifecycle handle");
        store
            .update_session_exact_with(&handle, None, |session| {
                session.dialog_id = Some(dialog_id.clone().into());
                session.dialog_established = true;
                session.call_state = crate::types::CallState::Active;
                session.remote_uri = Some("sip:bob@example.test".to_string());
                session.auth = with_route_auth.then(|| {
                    crate::auth::SipClientAuth::digest("retained-auth-user", RETAINED_AUTH_PASSWORD)
                });
            })
            .expect("publish active exact MESSAGE state");
        store
            .registry()
            .map_dialog_handle(&handle, dialog_id.clone().into())
            .expect("install canonical exact MESSAGE dialog mapping");
        handle
    }

    #[tokio::test]
    async fn retained_message_auth_is_write_free_until_challenged_and_retries_immutably() {
        const REALM: &str = "message-lane-owned";
        const NONCE: &str = "message-lane-owned-nonce";
        const REQUEST_URI: &str = "sip:bob@contact.example.test";
        const BODY: &[u8] = b"\x00immutable\xffmessage-body";

        let store = SessionStore::new();
        let dialog_id = RvoipDialogId::new();
        let handle =
            install_active_data_message_session(&store, SessionId::new(), &dialog_id, true).await;
        let lanes = SipDataMessageDispatchLanes::default();
        let immutable_body = bytes::Bytes::from_static(BODY);
        let transport = crate::auth::SipTransportSecurityContext::from_transport_name("UDP");

        let (first_handle, first_state_guard, mut first_session) =
            lock_and_load_exact_data_message_session(&store, &dialog_id)
                .await
                .expect("load first exact MESSAGE attempt");
        assert_eq!(first_handle, handle);
        let first_message_lane = lanes.lane(&dialog_id);
        let first_message_guard = Arc::clone(&first_message_lane).lock_owned().await;
        let before_unauth = store
            .get_session_snapshot_exact(&handle)
            .expect("snapshot before unauthenticated MESSAGE")
            .revision();
        let mut unauthenticated = rvoip_sip_core::Request::new(
            rvoip_sip_core::Method::Message,
            Uri::from_str(REQUEST_URI).expect("MESSAGE request URI"),
        );
        unauthenticated.body = immutable_body.clone();
        authorize_data_message_lane_owned_exact(
            &store,
            &first_handle,
            &mut first_session,
            &dialog_id,
            &mut unauthenticated,
            REQUEST_URI,
            None,
            &transport,
        )
        .expect("prepare unauthenticated MESSAGE attempt");
        assert!(unauthenticated.headers.is_empty());
        assert_eq!(unauthenticated.body.as_ref(), BODY);
        assert_eq!(
            store
                .get_session_snapshot_exact(&handle)
                .expect("snapshot after unauthenticated MESSAGE")
                .revision(),
            before_unauth,
            "an attempt without retained credentials or a challenge must not publish"
        );
        drop(first_state_guard);
        drop(first_message_guard);

        let challenge = DataMessageAuthChallenge {
            status: 401,
            value: retained_auth_challenge(REALM, NONCE, false, "auth-int"),
        };
        let (retry_handle, retry_state_guard, mut retry_session) =
            lock_and_load_exact_data_message_session(&store, &dialog_id)
                .await
                .expect("reacquire exact state for challenged MESSAGE retry");
        let retry_message_guard = lanes.lane(&dialog_id).lock_owned().await;
        let mut retry = rvoip_sip_core::Request::new(
            rvoip_sip_core::Method::Message,
            Uri::from_str(REQUEST_URI).expect("MESSAGE retry URI"),
        );
        retry.body = immutable_body.clone();
        authorize_data_message_lane_owned_exact(
            &store,
            &retry_handle,
            &mut retry_session,
            &dialog_id,
            &mut retry,
            REQUEST_URI,
            Some(&challenge),
            &transport,
        )
        .expect("authorize challenged MESSAGE retry");
        assert!(unauthenticated.headers.is_empty());
        assert_eq!(unauthenticated.body.as_ref(), BODY);
        assert_eq!(retry.body.as_ref(), BODY);
        assert_eq!(retry.headers.len(), 1);
        let (_, authorization) = typed_auth_value(&retry.headers[0]);
        let parsed = crate::auth::DigestAuthenticator::parse_authorization(&authorization)
            .expect("parse challenged MESSAGE authorization");
        assert_eq!(parsed.nc.as_deref(), Some("00000001"));
        assert!(crate::auth::DigestAuthenticator::new(REALM)
            .validate_response_with_body(&parsed, "MESSAGE", RETAINED_AUTH_PASSWORD, Some(BODY),)
            .expect("validate immutable auth-int MESSAGE retry body"));
        drop(retry_state_guard);
        drop(retry_message_guard);

        let (next_handle, next_state_guard, mut next_session) =
            lock_and_load_exact_data_message_session(&store, &dialog_id)
                .await
                .expect("reacquire exact state for the next MESSAGE attempt");
        let next_message_guard = lanes.lane(&dialog_id).lock_owned().await;
        let mut next = rvoip_sip_core::Request::new(
            rvoip_sip_core::Method::Message,
            Uri::from_str(REQUEST_URI).expect("next MESSAGE URI"),
        );
        next.body = immutable_body;
        authorize_data_message_lane_owned_exact(
            &store,
            &next_handle,
            &mut next_session,
            &dialog_id,
            &mut next,
            REQUEST_URI,
            None,
            &transport,
        )
        .expect("reuse retained MESSAGE protection space");
        let (_, authorization) = typed_auth_value(&next.headers[0]);
        let parsed = crate::auth::DigestAuthenticator::parse_authorization(&authorization)
            .expect("parse next retained MESSAGE authorization");
        assert_eq!(parsed.nc.as_deref(), Some("00000002"));
        assert!(crate::auth::DigestAuthenticator::new(REALM)
            .validate_response_with_body(&parsed, "MESSAGE", RETAINED_AUTH_PASSWORD, Some(BODY),)
            .expect("validate exact body after monotonic nonce advance"));
        drop(next_state_guard);
        drop(next_message_guard);

        let published = store
            .get_session_snapshot_exact(&handle)
            .expect("read retained MESSAGE auth publication");
        assert_eq!(
            published
                .digest_nc
                .get(&(REALM.to_string(), NONCE.to_string())),
            Some(&2)
        );
    }

    #[tokio::test]
    async fn retained_message_cleanup_acquires_state_then_waits_for_attempt_lane() {
        let store = Arc::new(SessionStore::new());
        let lanes = Arc::new(SipDataMessageDispatchLanes::default());
        let dialog_id = RvoipDialogId::new();
        let handle = install_active_data_message_session(
            store.as_ref(),
            SessionId::new(),
            &dialog_id,
            false,
        )
        .await;

        let (_, state_guard, _) =
            lock_and_load_exact_data_message_session(store.as_ref(), &dialog_id)
                .await
                .expect("load active MESSAGE attempt");
        let attempt_lane = lanes.lane(&dialog_id);
        let attempt_guard = Arc::clone(&attempt_lane).lock_owned().await;
        drop(state_guard);

        let cleanup_state_lane = store
            .state_machine_lane_exact(&handle)
            .expect("cleanup resolves the exact state lane");
        let cleanup_message_lane = Arc::clone(&attempt_lane);
        let cleanup_store = Arc::clone(&store);
        let cleanup_lanes = Arc::clone(&lanes);
        let cleanup_handle = handle.clone();
        let cleanup_dialog = dialog_id.clone();
        let state_entered = Arc::new(tokio::sync::Notify::new());
        let cleanup_state_entered = Arc::clone(&state_entered);
        let message_entered = Arc::new(AtomicBool::new(false));
        let cleanup_message_entered = Arc::clone(&message_entered);
        let cleanup = tokio::spawn(async move {
            let _cleanup_state_guard = cleanup_state_lane.lock_owned().await;
            cleanup_state_entered.notify_one();
            let _cleanup_message_guard = cleanup_message_lane.lock_owned().await;
            cleanup_message_entered.store(true, Ordering::Release);
            cleanup_store
                .registry()
                .clear_dialog_handle_retained(&cleanup_handle, cleanup_dialog.clone().into())
                .expect("clear canonical exact dialog during cleanup");
            cleanup_lanes.remove_exact(&cleanup_dialog, &attempt_lane);
        });

        tokio::time::timeout(Duration::from_secs(1), state_entered.notified())
            .await
            .expect("cleanup entered exact state lane");
        tokio::task::yield_now().await;
        assert!(
            !message_entered.load(Ordering::Acquire),
            "cleanup crossed a MESSAGE attempt that still owns its per-wire lane"
        );

        drop(attempt_guard);
        tokio::time::timeout(Duration::from_secs(1), cleanup)
            .await
            .expect("cleanup acquired MESSAGE lane after attempt release")
            .expect("cleanup lock-order task did not panic");
        assert!(message_entered.load(Ordering::Acquire));
        assert!(matches!(
            lock_and_load_exact_data_message_session(store.as_ref(), &dialog_id).await,
            Err(SessionError::InvalidTransition(_))
        ));
    }

    #[tokio::test]
    async fn retained_message_exact_resolution_cannot_cross_raw_session_id_reuse() {
        let store = SessionStore::new();
        let session_id = SessionId("message-reused-session".to_string());
        let dialog_a = RvoipDialogId::new();
        let handle_a =
            install_active_data_message_session(&store, session_id.clone(), &dialog_a, false).await;
        let stale_key = handle_a.key().clone();
        let stale_revision = handle_a.slot_revision();
        let (resolved_a, guard_a, _) = lock_and_load_exact_data_message_session(&store, &dialog_a)
            .await
            .expect("resolve MESSAGE generation A");
        assert_eq!(resolved_a, handle_a);
        drop(guard_a);

        store
            .remove_session_exact(&handle_a)
            .await
            .expect("retire MESSAGE generation A");
        assert!(matches!(
            lock_and_load_exact_data_message_session(&store, &dialog_a).await,
            Err(SessionError::InvalidTransition(_))
        ));
        drop(resolved_a);
        drop(handle_a);
        assert!(store.authority().elapse_reuse_horizon_for_test(&session_id));

        let dialog_b = RvoipDialogId::new();
        let handle_b =
            install_active_data_message_session(&store, session_id, &dialog_b, false).await;
        assert!(store
            .registry()
            .get_dialog_exact(&stale_key, stale_revision)
            .is_none());
        assert!(matches!(
            lock_and_load_exact_data_message_session(&store, &dialog_a).await,
            Err(SessionError::InvalidTransition(_))
        ));
        let (resolved_b, guard_b, _) = lock_and_load_exact_data_message_session(&store, &dialog_b)
            .await
            .expect("resolve only current MESSAGE generation B");
        assert_eq!(resolved_b, handle_b);
        drop(guard_b);
    }

    #[test]
    fn retained_message_lock_order_and_auth_publication_have_one_authority() {
        let source = include_str!("dialog_adapter.rs");
        let resolver = rust_function_source(source, "lock_and_load_exact_data_message_session");
        let registry_owner = resolver
            .find("get_handle_by_dialog_exact")
            .expect("MESSAGE resolves its canonical registry owner");
        let lane_resolution = resolver
            .find("state_machine_lane_exact(&handle)")
            .expect("MESSAGE resolves the owner's exact state lane");
        let state_lock = resolver
            .find("lock_owned().await")
            .expect("MESSAGE acquires the exact state lane");
        let snapshot_revalidation = resolver
            .find("get_session_snapshot_exact")
            .expect("MESSAGE revalidates exact state after lane acquisition");
        let dialog_revalidation = resolver
            .find("get_dialog_handle_exact")
            .expect("MESSAGE revalidates canonical dialog ownership");
        assert!(
            registry_owner < lane_resolution
                && lane_resolution < state_lock
                && state_lock < snapshot_revalidation
                && snapshot_revalidation < dialog_revalidation
        );
        assert!(!resolver.contains("dialog_to_session"));
        assert!(!resolver.contains("session_to_dialog"));

        let cleanup = rust_function_source(source, "cleanup_session_exact_lane_owned");
        let canonical_cleanup_dialog = cleanup
            .find("get_dialog_retained_exact(handle)")
            .expect("cleanup resolves its MESSAGE lane from canonical exact ownership");
        let cleanup_message_lane = cleanup
            .find("data_message_dispatch_lanes.lane")
            .expect("cleanup serializes with the canonical dialog's MESSAGE lane");
        assert!(canonical_cleanup_dialog < cleanup_message_lane);
        assert!(!cleanup.contains("session_to_dialog.get"));

        let external_facade = rust_function_source(source, "send_data_message_on_dialog");
        assert_eq!(
            external_facade
                .matches("send_data_message_on_dialog_driver(")
                .count(),
            1,
            "the exact-locking facade delegates once to the canonical driver"
        );
        assert!(!external_facade.contains("build_sip_data_request"));
        assert!(!external_facade.contains("send_request_with_candidate_failover"));
        assert!(!external_facade.contains("wait_for_final_response"));

        let lane_owned_facade = rust_function_source(source, "send_message_in_dialog_lane_owned");
        assert_eq!(
            lane_owned_facade
                .matches("send_data_message_on_dialog_driver(")
                .count(),
            1,
            "the already-lane-owned facade delegates once to the canonical driver"
        );
        assert!(lane_owned_facade.contains("DataMessageStateLane::AlreadyOwned(session)"));
        assert!(!lane_owned_facade.contains("send_request_in_dialog"));
        assert!(!lane_owned_facade.contains("build_sip_data_request"));
        assert!(!lane_owned_facade.contains("send_request_with_candidate_failover"));
        assert!(!lane_owned_facade.contains("wait_for_final_response"));

        let legacy_message = rust_function_source(source, "legacy_text_data_message");
        assert!(legacy_message.contains("content_type: \"text/plain\""));
        assert!(legacy_message.contains("extra_headers: Vec::new()"));
        let legacy_value = legacy_text_data_message("legacy body".to_string());
        assert_eq!(legacy_value.content_type, "text/plain");
        assert_eq!(legacy_value.bytes.as_ref(), b"legacy body");
        assert!(legacy_value.extra_headers.is_empty());

        let public_legacy_facade = rust_function_source(source, "send_message");
        assert_eq!(
            public_legacy_facade
                .matches("send_data_message_on_dialog_driver(")
                .count(),
            1,
            "the public in-dialog String facade delegates once to the canonical driver"
        );
        assert!(public_legacy_facade.contains("expected_handle: Some(handle)"));
        assert!(!public_legacy_facade.contains("send_request_in_dialog"));

        let dispatch = rust_function_source(source, "send_data_message_on_dialog_driver");
        let route_snapshot = dispatch
            .find("manager.get_dialog(dialog_id)")
            .expect("MESSAGE snapshots dialog routing before DNS");
        let candidate_resolution = dispatch
            .find("resolve_uri_to_candidates")
            .expect("MESSAGE resolves its exact route");
        let zero_candidate_gate = dispatch
            .find("if candidates.is_empty()")
            .expect("MESSAGE preserves zero-candidate no-write behavior");
        let state_attempt = dispatch
            .find("lock_and_load_exact_data_message_session")
            .expect("MESSAGE acquires exact state after DNS preflight");
        let message_attempt = dispatch
            .find("data_message_dispatch_lanes.lane")
            .expect("MESSAGE attempt acquires the per-dialog wire lane second");
        let route_revalidation = dispatch
            .find("dialog.remote_target != expected_target")
            .expect("MESSAGE revalidates the DNS route under both lanes");
        let cseq_allocation = dispatch
            .find("create_request_template")
            .expect("MESSAGE allocates one CSeq after route revalidation");
        let auth_publish = dispatch
            .find("authorize_data_message_lane_owned_exact")
            .expect("MESSAGE authorizes while exact state is owned");
        let state_release = dispatch[auth_publish..]
            .find("drop(attempt_state)")
            .map(|offset| auth_publish + offset)
            .expect("MESSAGE releases the per-attempt state binding before wire I/O");
        let wire = dispatch
            .find("send_request_with_candidate_failover")
            .expect("MESSAGE wire dispatch");
        let final_wait = dispatch
            .find("wait_for_final_response")
            .expect("MESSAGE final-response wait");
        assert!(
            route_snapshot < candidate_resolution
                && candidate_resolution < zero_candidate_gate
                && zero_candidate_gate < state_attempt
                && state_attempt < message_attempt
                && message_attempt < route_revalidation
                && route_revalidation < cseq_allocation
                && cseq_allocation < auth_publish
                && auth_publish < state_release
                && state_release < wire
                && wire < final_wait
        );
        let message_release = dispatch[final_wait..]
            .find("drop(dispatch_guard)")
            .map(|offset| final_wait + offset)
            .expect("challenge retry releases its MESSAGE lane");
        let retain_challenge = dispatch
            .find("fresh_challenge = Some(challenge)")
            .expect("challenge retained for the bounded retry");
        let retry = dispatch[retain_challenge..]
            .find("continue;")
            .map(|offset| retain_challenge + offset)
            .expect("challenge retry returns to exact state acquisition");
        assert!(message_release < retain_challenge && retain_challenge < retry);
        assert_eq!(
            dispatch.matches("data_message_dispatch_lanes.lane").count(),
            1,
            "each loop pass acquires one per-attempt MESSAGE lane"
        );
        assert_eq!(
            dispatch.matches("build_sip_data_request(").count(),
            1,
            "one request materializer owns every in-dialog MESSAGE shape"
        );
        assert_eq!(
            dispatch
                .matches("send_request_with_candidate_failover(")
                .count(),
            1,
            "one wire owner dispatches every in-dialog MESSAGE"
        );
        assert_eq!(
            dispatch.matches("wait_for_final_response(").count(),
            1,
            "one final-response owner observes every in-dialog MESSAGE"
        );
        assert!(source.contains(
            "const DATA_MESSAGE_FINAL_RESPONSE_TIMEOUT: Duration = Duration::from_secs(5);"
        ));

        let auth = rust_function_source(source, "authorize_data_message_lane_owned_exact");
        assert_eq!(auth.matches("mutate_retained_dialog_auth(").count(), 1);
        assert_eq!(
            auth.matches("update_retained_auth_lane_owned_exact(")
                .count(),
            1
        );
        assert!(!auth.contains("dialog_to_session"));
        assert!(!auth.contains("session_to_dialog"));

        for authority_source in [
            source,
            include_str!("../session_store/store.rs"),
            include_str!("../state_machine/executor.rs"),
        ] {
            for deleted in [
                ["auth_required", "_event"].concat(),
                ["preserve_auth", "_coordination"].concat(),
                ["auth_coordination", "_changed"].concat(),
            ] {
                assert!(
                    !authority_source.contains(&deleted),
                    "deleted competing auth authority returned: {deleted}"
                );
            }
        }
    }

    #[test]
    fn retained_auth_pure_bye_binds_exact_method_and_dialog_target() {
        use crate::session_store::state::InviteCredentialKind;

        const REALM: &str = "bye-retained";
        const NONCE: &str = "bye-retained-nonce";
        const ORIGIN_TARGET: &str = "sip:bob@example.test";
        const REQUEST_URI: &str = "sip:bob@contact.example.test";

        let dialog_id = RvoipDialogId::new();
        let mut session = retained_auth_session(&dialog_id, ORIGIN_TARGET);
        retain_digest_credential(
            &mut session,
            InviteCredentialKind::Origin,
            ORIGIN_TARGET,
            REALM,
            NONCE,
            "auth",
        );

        let headers = mutate_retained_dialog_auth(
            &mut session,
            &dialog_id,
            RetainedDialogAuthMode::Request,
            "BYE",
            REQUEST_URI,
            RetainedDialogAuthRoute {
                next_hop: REQUEST_URI,
                transport: &crate::auth::SipTransportSecurityContext::from_transport_name("UDP"),
            },
            None,
        )
        .expect("pure BYE retained auth");
        assert_eq!(headers.len(), 1);
        let (kind, value) = typed_auth_value(&headers[0]);
        assert_eq!(kind, "origin");
        let parsed = crate::auth::DigestAuthenticator::parse_authorization(&value)
            .expect("parse retained BYE authorization");
        assert_eq!(parsed.uri, REQUEST_URI);
        assert!(crate::auth::DigestAuthenticator::new(REALM)
            .validate_response_with_body(&parsed, "BYE", RETAINED_AUTH_PASSWORD, None)
            .expect("validate BYE method binding"));
        assert!(!crate::auth::DigestAuthenticator::new(REALM)
            .validate_response_with_body(&parsed, "INVITE", RETAINED_AUTH_PASSWORD, None)
            .expect("reject INVITE method substitution"));
        assert_eq!(session.invite_authorization_credentials[0].value, value);
    }

    #[test]
    fn retained_auth_pure_message_installs_one_fresh_and_one_stale_refresh() {
        const REALM: &str = "message-retained";
        const OLD_NONCE: &str = "message-old-nonce";
        const FRESH_NONCE: &str = "message-fresh-nonce";
        const THIRD_NONCE: &str = "message-third-nonce";
        const ORIGIN_TARGET: &str = "sip:bob@example.test";
        const REQUEST_URI: &str = "sip:bob@contact.example.test";

        let dialog_id = RvoipDialogId::new();
        let mut session = retained_auth_session(&dialog_id, ORIGIN_TARGET);
        let initial = DataMessageAuthChallenge {
            status: 401,
            value: retained_auth_challenge(REALM, OLD_NONCE, false, "auth"),
        };
        mutate_retained_dialog_auth(
            &mut session,
            &dialog_id,
            RetainedDialogAuthMode::DataMessage {
                fresh_challenge: Some(&initial),
            },
            "MESSAGE",
            REQUEST_URI,
            RetainedDialogAuthRoute {
                next_hop: REQUEST_URI,
                transport: &crate::auth::SipTransportSecurityContext::from_transport_name("UDP"),
            },
            Some(b"fresh-message"),
        )
        .expect("install initial MESSAGE protection space");
        assert_eq!(session.invite_authorization_credentials.len(), 1);
        assert_eq!(
            session.invite_authorization_credentials[0].nonce.as_deref(),
            Some(OLD_NONCE)
        );
        assert_eq!(
            session.invite_authorization_credentials[0].stale_refreshes,
            0
        );

        let stale = DataMessageAuthChallenge {
            status: 401,
            value: retained_auth_challenge(REALM, FRESH_NONCE, true, "auth"),
        };
        mutate_retained_dialog_auth(
            &mut session,
            &dialog_id,
            RetainedDialogAuthMode::DataMessage {
                fresh_challenge: Some(&stale),
            },
            "MESSAGE",
            REQUEST_URI,
            RetainedDialogAuthRoute {
                next_hop: REQUEST_URI,
                transport: &crate::auth::SipTransportSecurityContext::from_transport_name("UDP"),
            },
            Some(b"fresh-message"),
        )
        .expect("refresh MESSAGE protection space once");
        assert_eq!(
            session.invite_authorization_credentials[0].nonce.as_deref(),
            Some(FRESH_NONCE)
        );
        assert_eq!(
            session.invite_authorization_credentials[0].stale_refreshes,
            1
        );
        assert_eq!(
            session
                .digest_nc
                .get(&(REALM.to_string(), FRESH_NONCE.to_string())),
            Some(&1)
        );

        let counts_before_rejection = session.digest_nc.clone();
        let rejected = DataMessageAuthChallenge {
            status: 401,
            value: retained_auth_challenge(REALM, THIRD_NONCE, true, "auth"),
        };
        let error = mutate_retained_dialog_auth(
            &mut session,
            &dialog_id,
            RetainedDialogAuthMode::DataMessage {
                fresh_challenge: Some(&rejected),
            },
            "MESSAGE",
            REQUEST_URI,
            RetainedDialogAuthRoute {
                next_hop: REQUEST_URI,
                transport: &crate::auth::SipTransportSecurityContext::from_transport_name("UDP"),
            },
            Some(b"fresh-message"),
        )
        .expect_err("a second stale refresh must fail");
        assert!(matches!(error, SessionError::AuthError(_)));
        assert_eq!(session.digest_nc, counts_before_rejection);
        assert_eq!(
            session.invite_authorization_credentials[0].nonce.as_deref(),
            Some(FRESH_NONCE),
            "rejected refresh must not partially replace retained state"
        );
    }

    #[test]
    fn retained_auth_pure_message_keeps_origin_and_proxy_targets_isolated() {
        const ORIGIN_REALM: &str = "message-origin";
        const PROXY_REALM: &str = "message-proxy";
        const ORIGIN_TARGET: &str = "sip:bob@example.test";
        const REQUEST_URI: &str = "sip:bob@contact.example.test";
        const PROXY_TARGET: &str = "sip:proxy.example.test;lr";

        let dialog_id = RvoipDialogId::new();
        let mut session = retained_auth_session(&dialog_id, ORIGIN_TARGET);
        let origin = DataMessageAuthChallenge {
            status: 401,
            value: retained_auth_challenge(ORIGIN_REALM, "origin-nonce", false, "auth"),
        };
        mutate_retained_dialog_auth(
            &mut session,
            &dialog_id,
            RetainedDialogAuthMode::DataMessage {
                fresh_challenge: Some(&origin),
            },
            "MESSAGE",
            REQUEST_URI,
            RetainedDialogAuthRoute {
                next_hop: PROXY_TARGET,
                transport: &crate::auth::SipTransportSecurityContext::from_transport_name("UDP"),
            },
            Some(b"origin-and-proxy"),
        )
        .expect("install origin protection space");

        let proxy = DataMessageAuthChallenge {
            status: 407,
            value: retained_auth_challenge(PROXY_REALM, "proxy-nonce", false, "auth"),
        };
        let headers = mutate_retained_dialog_auth(
            &mut session,
            &dialog_id,
            RetainedDialogAuthMode::DataMessage {
                fresh_challenge: Some(&proxy),
            },
            "MESSAGE",
            REQUEST_URI,
            RetainedDialogAuthRoute {
                next_hop: PROXY_TARGET,
                transport: &crate::auth::SipTransportSecurityContext::from_transport_name("UDP"),
            },
            Some(b"origin-and-proxy"),
        )
        .expect("install independent proxy protection space");
        assert_eq!(headers.len(), 2);
        let mut kinds = headers
            .iter()
            .map(typed_auth_value)
            .map(|(kind, _)| kind)
            .collect::<Vec<_>>();
        kinds.sort_unstable();
        assert_eq!(kinds, vec!["origin", "proxy"]);

        let proxy_count = session
            .digest_nc
            .get(&(PROXY_REALM.to_string(), "proxy-nonce".to_string()))
            .copied();
        let changed_hop_headers = mutate_retained_dialog_auth(
            &mut session,
            &dialog_id,
            RetainedDialogAuthMode::DataMessage {
                fresh_challenge: None,
            },
            "MESSAGE",
            REQUEST_URI,
            RetainedDialogAuthRoute {
                next_hop: "sip:other-proxy.example.test;lr",
                transport: &crate::auth::SipTransportSecurityContext::from_transport_name("UDP"),
            },
            Some(b"origin-and-proxy"),
        )
        .expect("reauthor exact changed next hop");
        assert_eq!(changed_hop_headers.len(), 1);
        assert_eq!(typed_auth_value(&changed_hop_headers[0]).0, "origin");
        assert_eq!(
            session
                .digest_nc
                .get(&(PROXY_REALM.to_string(), "proxy-nonce".to_string()))
                .copied(),
            proxy_count,
            "a proxy credential must not advance for a different next hop"
        );
    }

    #[test]
    fn retained_auth_pure_digest_nonce_count_is_monotonic_and_body_exact() {
        use crate::session_store::state::InviteCredentialKind;

        const REALM: &str = "message-auth-int";
        const NONCE: &str = "message-auth-int-nonce";
        const ORIGIN_TARGET: &str = "sip:bob@example.test";
        const REQUEST_URI: &str = "sip:bob@contact.example.test";
        const BODY: &[u8] = b"\x00binary\xffbody";

        let dialog_id = RvoipDialogId::new();
        let mut session = retained_auth_session(&dialog_id, ORIGIN_TARGET);
        retain_digest_credential(
            &mut session,
            InviteCredentialKind::Origin,
            ORIGIN_TARGET,
            REALM,
            NONCE,
            "auth-int",
        );
        let transport = crate::auth::SipTransportSecurityContext::from_transport_name("UDP");

        for expected in 1..=2 {
            let headers = mutate_retained_dialog_auth(
                &mut session,
                &dialog_id,
                RetainedDialogAuthMode::DataMessage {
                    fresh_challenge: None,
                },
                "MESSAGE",
                REQUEST_URI,
                RetainedDialogAuthRoute {
                    next_hop: REQUEST_URI,
                    transport: &transport,
                },
                Some(BODY),
            )
            .expect("advance retained Digest nonce count");
            let (_, value) = typed_auth_value(&headers[0]);
            let parsed = crate::auth::DigestAuthenticator::parse_authorization(&value)
                .expect("parse retained auth-int response");
            let expected_nc = format!("{expected:08x}");
            assert_eq!(parsed.nc.as_deref(), Some(expected_nc.as_str()));
            assert!(
                crate::auth::DigestAuthenticator::new(REALM)
                    .validate_response_with_body(
                        &parsed,
                        "MESSAGE",
                        RETAINED_AUTH_PASSWORD,
                        Some(BODY),
                    )
                    .expect("validate exact auth-int body")
            );
        }
        assert_eq!(
            session
                .digest_nc
                .get(&(REALM.to_string(), NONCE.to_string())),
            Some(&2)
        );
    }

    #[test]
    fn retained_dialog_auth_wrappers_share_one_pure_implementation() {
        let source = include_str!("dialog_adapter.rs");
        let implementation_marker = ["fn mutate_retained_dialog_auth", "("].concat();
        assert_eq!(
            source.matches(&implementation_marker).count(),
            1,
            "retained dialog authentication must have one pure implementation"
        );
        for wrapper in [
            "send_bye_with_options_lane_owned",
            "authorize_data_message_lane_owned_exact",
        ] {
            let body = rust_function_source(source, wrapper);
            assert_eq!(
                body.matches("mutate_retained_dialog_auth(").count(),
                1,
                "{wrapper} must delegate exactly once to the shared mutator"
            );
            assert!(!body.contains("authorization_for_challenge_with_transport_context"));
            assert!(!body.contains("invite_authorization_credentials ="));
            assert!(!body.contains("digest_nc.entry"));
        }
    }

    #[tokio::test]
    async fn legacy_dialog_resolution_fails_closed_and_fences_raw_id_reuse() {
        let store = Arc::new(SessionStore::new());
        let missing_dialog = RvoipDialogId::new();
        assert!(
            matches!(
                lock_and_load_exact_legacy_dialog_session(store.as_ref(), &missing_dialog).await,
                Err(SessionError::SessionNotFound(_))
            ),
            "an unmapped legacy Dialog-ID must fail closed"
        );

        let session_id = SessionId("legacy-dialog-reused-session".to_string());
        let dialog_a = RvoipDialogId::new();
        let handle_a = install_active_data_message_session(
            store.as_ref(),
            session_id.clone(),
            &dialog_a,
            false,
        )
        .await;
        let held_lane = store
            .state_machine_lane_exact(&handle_a)
            .expect("generation A exact lane")
            .lock_owned()
            .await;
        let waiting_store = Arc::clone(&store);
        let waiting_dialog = dialog_a.clone();
        let waiting = tokio::spawn(async move {
            lock_and_load_exact_legacy_dialog_session(waiting_store.as_ref(), &waiting_dialog).await
        });
        tokio::task::yield_now().await;
        assert!(
            !waiting.is_finished(),
            "legacy resolver bypassed its exact lane"
        );

        store
            .remove_session_exact(&handle_a)
            .await
            .expect("retire legacy dialog generation A");
        drop(held_lane);
        let stale = tokio::time::timeout(Duration::from_secs(1), waiting)
            .await
            .expect("stale legacy resolution remained blocked")
            .expect("stale legacy resolution task panicked");
        assert!(
            matches!(
                stale,
                Err(SessionError::SessionNotFound(_)) | Err(SessionError::InvalidTransition(_))
            ),
            "a queued legacy operation survived exact retirement"
        );

        drop(handle_a);
        assert!(store.authority().elapse_reuse_horizon_for_test(&session_id));
        let dialog_b = RvoipDialogId::new();
        let handle_b =
            install_active_data_message_session(store.as_ref(), session_id, &dialog_b, false).await;
        assert!(
            matches!(
                lock_and_load_exact_legacy_dialog_session(store.as_ref(), &dialog_a).await,
                Err(SessionError::SessionNotFound(_))
            ),
            "generation A dialog resolved through raw session-ID reuse"
        );
        let (resolved_b, lane_b, _) =
            lock_and_load_exact_legacy_dialog_session(store.as_ref(), &dialog_b)
                .await
                .expect("generation B dialog resolves its exact owner");
        assert_eq!(resolved_b, handle_b);
        drop(lane_b);
    }

    #[tokio::test]
    async fn signaling_and_quiesced_cleanup_serialize_on_the_same_exact_lane() {
        let store = Arc::new(SessionStore::new());
        let session_id = SessionId::new();
        let created = store
            .create_session(session_id.clone(), Role::UAC, false)
            .await
            .expect("create BYE/cleanup serialization session");
        let handle = created
            .lifecycle_handle
            .clone()
            .expect("BYE/cleanup exact handle");
        let (_, signaling_lane) = store
            .state_machine_lane(&session_id)
            .expect("active signaling lane");
        let signaling_guard = Arc::clone(&signaling_lane).lock_owned().await;

        store
            .quiesce_session_exact(&handle)
            .await
            .expect("quiesce while signaling lane is held");
        let cleanup_lane = store
            .state_machine_lane_retained_exact(&handle)
            .expect("shutdown retained cleanup lane");
        assert!(Arc::ptr_eq(&signaling_lane, &cleanup_lane));

        let attempted = Arc::new(AtomicBool::new(false));
        let entered = Arc::new(AtomicBool::new(false));
        let waiting_attempted = Arc::clone(&attempted);
        let waiting_entered = Arc::clone(&entered);
        let cleanup_waiter = tokio::spawn(async move {
            waiting_attempted.store(true, Ordering::Release);
            let _cleanup_guard = cleanup_lane.lock_owned().await;
            waiting_entered.store(true, Ordering::Release);
        });
        while !attempted.load(Ordering::Acquire) {
            tokio::task::yield_now().await;
        }
        tokio::task::yield_now().await;
        assert!(
            !entered.load(Ordering::Acquire),
            "shutdown cleanup entered while signaling owned the exact lane"
        );

        drop(signaling_guard);
        tokio::time::timeout(Duration::from_secs(1), cleanup_waiter)
            .await
            .expect("shutdown cleanup remained blocked after BYE released lane")
            .expect("shutdown cleanup serialization task panicked");
        assert!(entered.load(Ordering::Acquire));
    }

    #[test]
    fn bye_uses_only_the_executor_lane_and_canonical_wire_dispatch() {
        let source = include_str!("dialog_adapter.rs");
        for lane_owned in [
            "send_bye_with_options_lane_owned",
            "send_bye_with_auth_lane_owned",
            "dispatch_bye_with_options",
        ] {
            let body = rust_function_source(source, lane_owned);
            assert!(
                !body.contains("data_message_dispatch_lanes"),
                "{lane_owned} must not acquire the MESSAGE/cleanup lane"
            );
        }

        let first_attempt = rust_function_source(source, "send_bye_with_options_lane_owned");
        assert!(first_attempt.contains("mutate_retained_dialog_auth("));
        assert!(!first_attempt.contains("update_retained_auth_lane_owned_exact"));
        assert!(!first_attempt.contains("update_session_and_snapshot"));

        let public_cleanup = rust_function_source(source, "cleanup_session");
        assert!(public_cleanup.contains("state_machine_lane(session_id)"));
        let exact_cleanup = rust_function_source(source, "cleanup_session_exact");
        let cleanup_lock = exact_cleanup
            .find("lock_owned().await")
            .expect("shutdown cleanup locks retained exact lane");
        let cleanup_revalidation = exact_cleanup
            .find("get_session_retained_snapshot_exact")
            .expect("shutdown cleanup revalidates retained exact cell");
        assert!(cleanup_lock < cleanup_revalidation);
        assert!(exact_cleanup.contains("state_machine_lane_retained_exact"));
        assert!(!exact_cleanup.contains("data_message_dispatch_lanes"));

        let lane_owned_cleanup = rust_function_source(source, "cleanup_session_exact_lane_owned");
        assert!(lane_owned_cleanup.contains("data_message_dispatch_lanes.lane"));

        let actions = include_str!("../state_machine/actions.rs");
        assert_eq!(
            actions
                .matches(".send_bye_with_options_lane_owned(")
                .count(),
            2,
            "both first-attempt BYE actions must reuse the executor lane"
        );
        assert_eq!(
            actions.matches(".send_bye_with_auth_lane_owned(").count(),
            1,
            "BYE auth retry must reuse the executor lane"
        );
        assert!(!actions.contains(".send_bye_with_options(&session.session_id"));
        assert!(!actions.contains(".send_bye_with_auth(&session.session_id"));
        assert_eq!(
            actions
                .matches(".cleanup_session_exact_lane_owned(")
                .count(),
            4,
            "every state-machine dialog cleanup path must reuse its held exact lane"
        );
        assert!(!actions.contains("dialog_adapter.cleanup_session("));
        assert!(!actions.contains("dialog_adapter.cleanup_session_exact("));
    }

    #[tokio::test]
    async fn retained_auth_exact_update_runs_under_the_exact_state_lane() {
        let store = SessionStore::new();
        let session_id = SessionId::new();
        let dialog_id = DialogId::new();
        store
            .create_session(session_id.clone(), crate::state_table::Role::UAC, false)
            .await
            .expect("create exact retained-auth session");
        store
            .update_session_with(&session_id, |session| {
                session.dialog_id = Some(dialog_id);
                session.dialog_established = true;
                session.call_state = crate::types::CallState::Active;
                session.remote_uri = Some("sip:peer@example.test".to_string());
            })
            .await
            .expect("publish established dialog");

        store
            .update_session_with(&session_id, |session| {
                session.call_established_triggered = true;
                session.sdp_origin_version = session.sdp_origin_version.saturating_add(1);
            })
            .await
            .expect("publish benign concurrent mutation");
        let (handle, lane) = store
            .state_machine_lane(&session_id)
            .expect("resolve retained-auth exact lane");
        let _state_lane_guard = lane.lock_owned().await;
        let auth_read_revision = store
            .get_session_snapshot_exact(&handle)
            .expect("capture lane-owned auth revision")
            .revision();

        let observed_origin_version = update_retained_auth_lane_owned_exact(
            &store,
            &handle,
            "retained auth exact session changed",
            |session| {
                assert_eq!(session.dialog_id.as_ref(), Some(&dialog_id));
                let nonce_count = session
                    .digest_nc
                    .entry(("dialog-realm".to_string(), "dialog-nonce".to_string()))
                    .or_insert(0);
                *nonce_count = nonce_count.saturating_add(1);
                Ok(session.sdp_origin_version)
            },
        )
        .expect("latest exact session revision accepts retained auth update");

        let after = store
            .get_session_snapshot(&session_id)
            .await
            .expect("read retained-auth result");
        assert!(after.revision() > auth_read_revision);
        assert!(after.state().call_established_triggered);
        assert_eq!(after.state().sdp_origin_version, observed_origin_version);
        assert_eq!(
            after
                .state()
                .digest_nc
                .get(&("dialog-realm".to_string(), "dialog-nonce".to_string())),
            Some(&1)
        );
    }

    #[test]
    fn invite_dispatch_errors_do_not_relay_lower_sources() {
        const SECRET: &str = "lower-dialog-option-secret-canary";
        for failure in [
            InviteDispatchFailure::Initial,
            InviteDispatchFailure::InitialWithExtraHeaders,
            InviteDispatchFailure::InitialWithOptions,
            InviteDispatchFailure::AuthRetry,
            InviteDispatchFailure::SessionTimerRetry,
            InviteDispatchFailure::ReinviteWithOptions,
        ] {
            let error = redacted_invite_dispatch_error(
                failure,
                format!(
                    "invalid From sip:{SECRET}@from.invalid; target=sip:{SECRET}@target.invalid; Authorization: Bearer {SECRET}; X-App: {SECRET}"
                ),
            );
            let display = error.to_string();
            let debug = format!("{error:?}");
            for rendered in [&display, &debug] {
                assert!(!rendered.contains(SECRET), "source leaked: {rendered}");
                assert!(!rendered.contains("sip:"));
                assert!(!rendered.contains("Authorization"));
                assert!(!rendered.contains("X-App"));
            }
            let SessionError::DialogError(detail) = &error else {
                panic!("unexpected invite error class: {error:?}");
            };
            assert!(detail.contains("class="));
            assert!(detail.contains(failure.diagnostic()));
        }
    }

    #[test]
    fn invite_wrapper_source_has_no_lower_error_relay_templates() {
        let source = include_str!("dialog_adapter.rs");
        for forbidden in [
            ["Failed to make call", ": {}"].concat(),
            ["Failed to make call with extra headers", ": {}"].concat(),
            ["Failed to send INVITE with options", ": {}"].concat(),
            ["resend_invite_with_auth failed for session {}", ": {}"].concat(),
            [
                "resend_invite_with_session_timer_override failed for session {}",
                ": {}",
            ]
            .concat(),
            ["Failed to send re-INVITE", ": {}"].concat(),
        ] {
            assert!(
                !source.contains(&forbidden),
                "lower error relay template returned: {forbidden}"
            );
        }
    }

    fn rust_function_source<'a>(source: &'a str, name: &str) -> &'a str {
        let marker = format!("fn {name}(");
        let start = source
            .find(&marker)
            .unwrap_or_else(|| panic!("missing Rust function {name}"));
        let body_start = start
            + source[start..]
                .find('{')
                .unwrap_or_else(|| panic!("missing body for Rust function {name}"));
        let mut depth = 0usize;
        for (offset, byte) in source.as_bytes()[body_start..].iter().enumerate() {
            match byte {
                b'{' => depth += 1,
                b'}' => {
                    depth -= 1;
                    if depth == 0 {
                        return &source[start..=body_start + offset];
                    }
                }
                _ => {}
            }
        }
        panic!("unterminated Rust function {name}")
    }

    #[test]
    fn retained_in_dialog_methods_have_one_lower_wire_authority() {
        let source = include_str!("dialog_adapter.rs");
        for (authority, lower_wire_call) in [
            (
                "dispatch_bye_with_options",
                ".send_bye_with_options_and_completion(",
            ),
            ("dispatch_cancel_with_options", ".send_cancel_with_options("),
            (
                "dispatch_reinvite_with_options",
                ".send_reinvite_with_options(",
            ),
            ("dispatch_refer_with_options", ".send_refer_with_options("),
            ("dispatch_notify_with_options", ".send_notify_with_options("),
            ("dispatch_info_with_options", ".send_info_with_options("),
            ("dispatch_update_with_options", ".send_update_with_options("),
        ] {
            let body = rust_function_source(source, authority);
            assert_eq!(
                body.matches(lower_wire_call).count(),
                1,
                "{authority} must retain exactly one {lower_wire_call} wire call"
            );
        }
    }

    #[test]
    fn legacy_dialog_facades_have_no_false_success_or_placeholder_path() {
        let source = include_str!("dialog_adapter.rs");
        let response = rust_function_source(source, "send_response_by_dialog");
        assert!(response.contains("SessionError::InvalidTransition"));
        assert!(response.contains("no exact inbound transaction authority"));
        assert!(!response.contains("self.dialog_api"));

        for facade in ["send_reinvite", "send_refer"] {
            let body = rust_function_source(source, facade);
            assert!(body.contains("lock_and_load_exact_legacy_dialog_session"));
            assert!(body.contains(".await?"));
            assert!(!body.contains("let Some("));
            assert!(!body.contains("No session found for dialog"));
        }

        let remote_uri = rust_function_source(source, "get_remote_uri");
        assert!(remote_uri.contains("get_dialog_info"));
        assert!(remote_uri.contains("dialog.remote_uri.to_string()"));
        assert!(!remote_uri.contains("sip:remote@example.com"));
    }

    #[test]
    fn session_scoped_response_facades_fail_closed_without_transaction_rediscovery() {
        let source = include_str!("dialog_adapter.rs");
        for facade in [
            "send_response_by_dialog",
            "send_redirect_response_with_options",
            "send_redirect_response",
            "send_response_with_options",
            "send_response",
        ] {
            let body = rust_function_source(source, facade);
            assert!(body.contains("SessionError::InvalidTransition"), "{facade}");
            assert!(
                body.contains("no exact inbound transaction authority"),
                "{facade}"
            );
            assert!(!body.contains("self.dialog_api"), "{facade}");
            assert!(!body.contains("pending_response"), "{facade}");
        }
    }

    #[test]
    fn retained_in_dialog_facades_do_not_bypass_canonical_dispatch() {
        let source = include_str!("dialog_adapter.rs");
        for facade in [
            "send_ack",
            "send_bye",
            "send_bye_session",
            "send_bye_session_with_reason",
            "send_bye_with_options",
            "send_bye_with_auth",
            "send_cancel",
            "send_cancel_with_options",
            "send_reinvite",
            "send_reinvite_session",
            "send_reinvite_with_options",
            "send_refer",
            "send_refer_session",
            "send_refer_with_options",
            "send_refer_with_auth",
            "send_notify",
            "send_notify_with_options",
            "send_notify_with_auth",
            "send_info",
            "send_info_with_options",
            "send_info_with_auth",
            "send_update_with_options",
            "send_update_with_auth",
        ] {
            let body = rust_function_source(source, facade);
            assert!(
                !body.contains("self.dialog_api"),
                "{facade} bypasses its canonical in-dialog dispatcher"
            );
        }

        let ack = rust_function_source(source, "send_ack");
        assert!(ack.contains("generated automatically by the exact INVITE transaction"));
        let bye = rust_function_source(source, "send_bye_with_options");
        assert!(bye.contains("dispatch_state_machine_options_exact"));
        assert!(bye.contains("EventType::SendOutboundBye"));
        let cancel = rust_function_source(source, "send_cancel_with_options");
        assert!(cancel.contains("dispatch_state_machine_options_exact"));
        assert!(cancel.contains("EventType::SendOutboundCancel"));

        assert!(
            !rust_function_source(source, "send_reinvite").contains("send_update_with_options"),
            "the re-INVITE compatibility facade must not regain an UPDATE wire path"
        );
        assert!(
            !rust_function_source(source, "send_reinvite_session")
                .contains("send_request_in_dialog"),
            "the session re-INVITE facade must not regain a generic wire path"
        );
    }

    #[test]
    fn register_diagnostics_never_format_live_uri_contact_or_scheme_values() {
        let source = include_str!("dialog_adapter.rs");
        for forbidden in [
            ["Sending REGISTER for session {}", " to {}"].concat(),
            ["Computing auth for REGISTER", " uri={}"].concat(),
            ["Computed REGISTER auth", " using {:?}"].concat(),
            ["rewriting REGISTER Contact", " {}"].concat(),
            ["Failed to send REGISTER", ": {}"].concat(),
        ] {
            assert!(
                !source.contains(&forbidden),
                "live REGISTER diagnostic template returned: {forbidden}"
            );
        }

        let scheme_canary = "SCHEME_CANARY_SECRET_19cf";
        assert_eq!(
            register_auth_scheme_class(&crate::auth::SipAuthScheme::Other(
                scheme_canary.to_string()
            )),
            "other"
        );
        assert!(
            !register_auth_scheme_class(&crate::auth::SipAuthScheme::Other(
                scheme_canary.to_string()
            ))
            .contains(scheme_canary)
        );
    }

    // ---- NAT-aware Contact rewrite (Sprint 1.A3) -------------------

    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    fn pub_addr() -> SocketAddr {
        SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 7)), 54321)
    }

    #[test]
    fn rewrite_contact_swaps_host_port_after_user() {
        // Standard `sip:user@host:port` form — host:port replaced.
        let input = "sip:alice@192.168.1.10:5060";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sip:alice@203.0.113.7:54321"
        );
    }

    #[test]
    fn rewrite_contact_preserves_uri_params() {
        let input = "sip:alice@192.168.1.10:5060;transport=tcp";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sip:alice@203.0.113.7:54321;transport=tcp"
        );
    }

    #[test]
    fn rewrite_contact_handles_no_port_in_input() {
        let input = "sip:alice@192.168.1.10";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sip:alice@203.0.113.7:54321"
        );
    }

    #[test]
    fn rewrite_contact_handles_no_user() {
        // Some Contacts omit the user-part — rewrite host:port anyway.
        let input = "sip:192.168.1.10:5060";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sip:203.0.113.7:54321"
        );
    }

    #[test]
    fn rewrite_contact_passes_through_sips_scheme() {
        let input = "sips:alice@192.168.1.10:5061;transport=tls";
        assert_eq!(
            rewrite_contact_host(input, pub_addr()),
            "sips:alice@203.0.113.7:54321;transport=tls"
        );
    }

    // ---- E4 outbound proxy pre-loaded Route ---------------------------

    use rvoip_sip_core::types::{uri::Uri, TypedHeader};
    use std::str::FromStr;

    #[test]
    fn prepend_outbound_proxy_route_with_proxy_adds_first_route() {
        let proxy = Uri::from_str("sip:sbc.example.com;lr").unwrap();
        let headers = prepend_outbound_proxy_route(Vec::new(), Some(&proxy));
        assert_eq!(headers.len(), 1);
        match &headers[0] {
            TypedHeader::Route(route) => {
                assert_eq!(route.len(), 1);
                assert_eq!(route[0].0.uri.to_string(), "sip:sbc.example.com;lr");
            }
            other => panic!("expected TypedHeader::Route, got {:?}", other),
        }
    }

    #[test]
    fn prepend_outbound_proxy_route_without_proxy_is_identity() {
        let pai_uri = Uri::from_str("sip:alice@pai.example.com").unwrap();
        let existing = vec![TypedHeader::PAssertedIdentity(
            rvoip_sip_core::types::p_asserted_identity::PAssertedIdentity::with_uri(pai_uri),
        )];
        let headers = prepend_outbound_proxy_route(existing.clone(), None);
        assert_eq!(headers.len(), existing.len());
        assert!(matches!(headers[0], TypedHeader::PAssertedIdentity(_)));
    }

    #[test]
    fn prepend_outbound_proxy_route_preserves_existing_before_route() {
        // Route goes FIRST, caller extras preserved after.
        let proxy = Uri::from_str("sip:sbc.example.com;lr").unwrap();
        let pai_uri = Uri::from_str("sip:alice@pai.example.com").unwrap();
        let existing = vec![TypedHeader::PAssertedIdentity(
            rvoip_sip_core::types::p_asserted_identity::PAssertedIdentity::with_uri(pai_uri),
        )];
        let headers = prepend_outbound_proxy_route(existing, Some(&proxy));
        assert_eq!(headers.len(), 2);
        assert!(matches!(headers[0], TypedHeader::Route(_)));
        assert!(matches!(headers[1], TypedHeader::PAssertedIdentity(_)));
    }

    #[test]
    fn auth_retry_policy_rejects_line_smuggling_for_401_and_407_headers() {
        for header_name in ["Authorization", "Proxy-Authorization"] {
            let canary = format!("Bearer safe\r\nX-Injected-{header_name}: yes");
            let error = apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Invite,
                Vec::new(),
                None,
                header_name,
                canary.clone(),
            )
            .expect_err("auth retry controls must fail before header insertion");
            assert!(!error.to_string().contains(&canary));
        }
    }

    #[test]
    fn auth_retry_policy_preserves_valid_values_for_401_and_407_headers() {
        use rvoip_sip_core::types::headers::{HeaderName, HeaderValue};

        for (wire_name, expected_name) in [
            ("Authorization", HeaderName::Authorization),
            ("Proxy-Authorization", HeaderName::ProxyAuthorization),
        ] {
            let value = "Digest username=\"alice\", response=\"safe\"";
            let headers = apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Invite,
                Vec::new(),
                None,
                wire_name,
                value.to_string(),
            )
            .expect("valid retry header");
            assert!(matches!(
                headers.as_slice(),
                [TypedHeader::Other(name, HeaderValue::Raw(bytes))]
                    if *name == expected_name && bytes.as_slice() == value.as_bytes()
            ));
        }
    }

    #[test]
    fn auth_retry_policy_accepts_case_aliases_and_rejects_unknown_names() {
        let value = "Digest username=\"alice\", response=\"safe\"".to_string();
        for name in ["authorization", "PROXY-authorization"] {
            apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Invite,
                Vec::new(),
                None,
                name,
                value.clone(),
            )
            .expect("case-insensitive credential header name");
        }
        for name in ["", "Proxy-Authenticate", "Authorization ", "X-Auth"] {
            let error = apply_outbound_extras_policy_with_auth(
                rvoip_sip_core::types::Method::Invite,
                Vec::new(),
                None,
                name,
                value.clone(),
            )
            .expect_err("unknown credential header names must fail closed");
            assert!(error.to_string().contains("unsupported"));
        }
    }
}

/// Rewrite the host (and port) portion of a SIP URI in a `Contact:`
/// value with the supplied public address. Preserves the scheme,
/// user-part (if any), and any URI parameters.
///
/// Used by `DialogAdapter::send_register` to redirect the registrar's
/// stored binding to the NAT-discovered public address (RFC 5626 §5).
/// Pure / sync so the rewrite is trivially testable without standing
/// up the full adapter.
///
/// Format we handle: `<scheme>:[<user>@]<host>[:<port>][;<params>]`.
/// We deliberately don't lean on a full URI parser here — the input
/// is always a Contact value we built ourselves earlier in the
/// pipeline, so the structure is predictable.
pub(crate) fn rewrite_contact_host(input: &str, public: std::net::SocketAddr) -> String {
    // Split off any URI params (`;name=value` after the host[:port]).
    let (host_section, params_suffix) = match input.find(';') {
        Some(idx) => (&input[..idx], &input[idx..]),
        None => (input, ""),
    };

    // Split scheme: prefix (`sip:` or `sips:`).
    let (scheme_prefix, after_scheme) = match host_section.find(':') {
        Some(idx) => (&host_section[..=idx], &host_section[idx + 1..]),
        None => return input.to_string(), // No `:` — not a SIP URI we recognise.
    };

    // Split optional `<user>@`.
    let (user_at, _existing_host_port) = match after_scheme.find('@') {
        Some(idx) => (&after_scheme[..=idx], &after_scheme[idx + 1..]),
        None => ("", after_scheme),
    };

    format!("{}{}{}{}", scheme_prefix, user_at, public, params_suffix)
}

/// SBC topology hiding (RFC 3261 §16-style) — strip every `Via:`
/// header below the topmost one.
///
/// Used when an SBC or stateless proxy mutates an inbound request
/// in-place before forwarding it, and wants to hide upstream hop
/// identities from the downstream peer. The top Via is preserved so
/// that the response can route back to *some* sender (typically the
/// SBC itself after it re-stamps the top Via with its own sent-by).
///
/// **NOT used by the B2BUA pattern in this codebase** — the standard
/// `coord.invite(...)` path builds a fresh outbound Request with the
/// SBC's own Via stamped fresh, so there's nothing to strip. This
/// helper is meaningful for proxy-style flows on top of
/// `Transport::send_message_raw` (i.e. the helpers planned for Phase
/// 8.5 stateless-proxy support).
///
/// Returns the number of Via headers removed (0 if there was only
/// one to begin with — common for endpoints that talk directly to
/// the SBC without intermediate proxies).
pub fn strip_via_below_top(request: &mut rvoip_sip_core::Request) -> usize {
    use rvoip_sip_core::types::TypedHeader;
    let mut seen_first_via = false;
    let mut removed = 0;
    request.headers.retain(|h| {
        if matches!(h, TypedHeader::Via(_)) {
            if seen_first_via {
                removed += 1;
                false
            } else {
                seen_first_via = true;
                true
            }
        } else {
            true
        }
    });
    removed
}

/// SBC topology hiding — strip every `Record-Route:` header whose
/// host does NOT match the supplied `self_host` (the SBC's own
/// public-facing host).
///
/// RFC 3261 §16.6 requires proxies to insert their own Record-Route
/// before forwarding so subsequent in-dialog requests come back
/// through them. An SBC doing topology hiding wants downstream to
/// see ONLY the SBC's own entry, not the upstream proxies that
/// previously inserted theirs.
///
/// `self_host` is matched against `Address.uri.host` as a case-
/// insensitive string. Pass the SBC's externally-visible host (e.g.
/// `"sbc.example.com"` or `"203.0.113.5"`) — typically what's also
/// used in `rewrite_contact_host`.
///
/// Returns the number of Record-Route entries (across all headers)
/// removed.
pub fn strip_record_route_below_self(
    request: &mut rvoip_sip_core::Request,
    self_host: &str,
) -> usize {
    use rvoip_sip_core::types::TypedHeader;
    let self_lower = self_host.to_ascii_lowercase();
    let mut removed = 0;

    // First pass: filter each RecordRoute header's entries.
    for header in request.headers.iter_mut() {
        if let TypedHeader::RecordRoute(rr) = header {
            let before = rr.0.len();
            rr.0.retain(|entry| {
                let host = entry.0.uri.host.to_string().to_ascii_lowercase();
                host == self_lower
            });
            removed += before - rr.0.len();
        }
    }

    // Second pass: drop any RecordRoute headers that became empty.
    request.headers.retain(|h| match h {
        TypedHeader::RecordRoute(rr) => !rr.0.is_empty(),
        _ => true,
    });

    removed
}

/// E4 / RFC 3261 §8.1.2: produce the full `extra_headers` list for an
/// outgoing INVITE, prepending a pre-loaded `Route` header when an outbound
/// proxy is configured on the `DialogAdapter`.
///
/// Pure so the "which headers travel on the wire" decision can be validated
/// without constructing a dialog_api / transport stack. Callers:
/// `DialogAdapter::send_invite_with_extra_headers`.
pub(crate) fn prepend_outbound_proxy_route(
    extra_headers: Vec<rvoip_sip_core::types::TypedHeader>,
    outbound_proxy_uri: Option<&rvoip_sip_core::types::uri::Uri>,
) -> Vec<rvoip_sip_core::types::TypedHeader> {
    let mut headers = extra_headers;
    if let Some(uri) = outbound_proxy_uri {
        use rvoip_sip_core::types::{route::Route, TypedHeader};
        headers.insert(0, TypedHeader::Route(Route::with_uri(uri.clone())));
    }
    headers
}

/// SIP_API_DESIGN_2 §5.4 + §6.1 — the canonical pre-dispatch step for
/// every `send_*_with_options` mirror on [`DialogAdapter`]. Runs
/// [`crate::api::headers::policy::validate_outbound`] against the
/// application extras (catches stack-managed names that bypassed the
/// builder's strictness gate), then prepends the configured outbound
/// proxy's `Route:` header via [`prepend_outbound_proxy_route`].
///
/// Returns the rewritten extras vector or a typed `SessionError` if
/// the header policy rejects the staged set. The dialog-adapter
/// mirror passes the returned vector through to dialog-core.
pub(crate) fn apply_outbound_extras_policy(
    method: rvoip_sip_core::types::Method,
    extras: Vec<rvoip_sip_core::types::TypedHeader>,
    outbound_proxy_uri: Option<&rvoip_sip_core::types::uri::Uri>,
) -> Result<Vec<rvoip_sip_core::types::TypedHeader>> {
    if let Err(violations) = crate::api::headers::policy::validate_outbound(method, &extras) {
        // Map the first violation to SessionError::HeaderPolicy; the
        // policy returns the StackManaged-in-extras case as a
        // MissingRequiredHeader-shaped violation today.
        let first = violations.into_iter().next().expect("non-empty on Err");
        return Err(SessionError::HeaderPolicy {
            method: first.method,
            header: first.name,
            reason: crate::api::headers::ViolationReason::StackManaged,
        });
    }
    Ok(prepend_outbound_proxy_route(extras, outbound_proxy_uri))
}

/// SIP_API_DESIGN_2 R2 — auth-retry mirror of
/// [`apply_outbound_extras_policy`]. Runs the same policy validation
/// on the application extras, then **appends** the
/// `Authorization:` / `Proxy-Authorization:` header *after* policy
/// validation. The auth header bypasses the policy because:
///
/// 1. The HeaderPolicy classifies `Authorization` as `MethodShaped`
///    for INVITE / REGISTER / SUBSCRIBE / MESSAGE / OPTIONS / REFER,
///    meaning application code can't stage it via `with_raw_header`.
/// 2. But the state machine *itself* stages it on the auth-retry hop
///    via `Action::SendRequestWithAuth`, computed from the digest
///    challenge. That's a stack-managed injection, not an application
///    one, so the policy guard is intentionally bypassed.
///
/// `auth_header_name` is the raw wire name (`"Authorization"` or
/// `"Proxy-Authorization"`); `auth_header_value` is the rendered
/// `Digest username="..", ...` body.
pub(crate) fn apply_outbound_extras_policy_with_auth(
    method: rvoip_sip_core::types::Method,
    extras: Vec<rvoip_sip_core::types::TypedHeader>,
    outbound_proxy_uri: Option<&rvoip_sip_core::types::uri::Uri>,
    auth_header_name: &str,
    auth_header_value: String,
) -> Result<Vec<rvoip_sip_core::types::TypedHeader>> {
    let mut validated = apply_outbound_extras_policy(method, extras, outbound_proxy_uri)?;
    let header_name = rvoip_sip_core::validation::authorization_header_name(auth_header_name)
        .map_err(|_| {
            crate::errors::SessionError::AuthError(
                "unsupported outbound SIP authorization header name".to_string(),
            )
        })?;
    let authorization =
        rvoip_sip_core::validation::validated_authorization_header(header_name, auth_header_value)
            .map_err(|_| {
                crate::errors::SessionError::AuthError(
                    "outbound SIP authorization header failed wire-safety validation".to_string(),
                )
            })?;
    validated.push(authorization);
    Ok(validated)
}