alkhttp 0.5.0

HTTP interface for the alk stack: serves HTTP/1.1 + HTTP/2 on standard ALPNs (with WebSocket upgrade carrying the channels protocol) and hosts the HTTP-backed call-protocol adapters
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
//! `OpenAPISpec` — the parsed OpenAPI 3.x document model shared by the
//! `from_openapi` adapter (consume) and the `to_openapi` projection
//! (produce). JSON + YAML parsing (ADR-051: `yaml_serde` 0.10.x is YAML
//! 1.2; JSON-first detection under `from_str`), plus `$ref` resolution
//! against the raw document.
//!
//! # YAML/JSON parity contract (review 002 OAI-12)
//!
//! Both entry points must mean the same thing for the same document, or
//! the difference must fail loudly:
//!
//! - **Duplicate keys** — rejected on the YAML path, loudly, with the
//!   key and its line/column. The JSON path inherits `serde_json`'s
//!   `Map::insert` semantics and silently last-wins; the YAML path is
//!   deliberately stricter, so a duplicate-key document can never
//!   silently mean different things through the two entry points (the
//!   YAML side fails instead of agreeing with the last value).
//! - **Merge keys** (`<<: *anchor`) — YAML 1.1-style merge keys are
//!   *applied* via `apply_merge()` and never advertised as literal
//!   properties. This is a deliberate, tested deviation from strict
//!   YAML 1.2 core-schema processing.
//! - **Non-finite floats** (`.inf`/`-.inf`/`.nan`) — rejected loudly.
//!   `serde_json::Number` cannot represent them; the naive passthrough
//!   silently nulls the value, so [`from_yaml`](OpenAPISpec::from_yaml)
//!   errors with the JSON pointer of the offending value instead.
//! - **Non-string mapping keys** — a non-string key that has no
//!   round-trip-stable string form (e.g. `~`, `[a]: 1`) is rejected;
//!   scalar keys are stringified exactly as the YAML 1.2 core schema
//!   renders them (`200:` → `"200"`), matching what the JSON path
//!   requires (`{"200": ...}`) — so response codes, the shape OpenAPI
//!   overwhelmingly uses, mean the same thing in both formats.
//! - **Bare `yes`/`no`/`on`/`off` and tags** — identical behavior on
//!   both paths by YAML 1.2 core schema (strings, `!!str 200` →
//!   `"200"`); unknown tags fail loudly on both.
//!
//! # Version stance (review 002 OAI-10)
//!
//! Documents are interpreted under **OpenAPI 3.0 semantics**; there is
//! no `openapi: 3.1` version gate. The one divergence that matters here
//! is `$ref` siblings: 3.0 ignores them, 3.1 applies them alongside the
//! resolved target. A `$ref` carrying sibling keys therefore imports
//! with the 3.0 reading and a `tracing::warn` naming the dropped keys —
//! the advertise/enforce drift a 3.1-authored constraint would
//! otherwise hide is visible at import instead of surfacing as a
//! silent `/schema` overstatement.

#[cfg(all(feature = "client", feature = "openapi"))]
use std::collections::HashSet;
use std::collections::{BTreeMap, HashMap};

use crate::adapters::input_validation::bounded_join;
use alkcall::client::AdapterError;
use serde_json::Value;
#[cfg(feature = "openapi")]
use yaml_serde::Value as YamlValue;

/// Maximum structural nesting depth for recursive `$ref` resolution
/// (review 001 OAI-01). Bounds schema object/array height so a
/// pathologically deep component fails import with a clean
/// [`AdapterError::SchemaParse`] instead of exhausting the stack.
/// `$ref` hop chains are bounded separately by [`MAX_REF_HOP_DEPTH`] —
/// one hop per schema level is legitimate above this height (a 40-level
/// chain nests ~2 objects per level).
#[cfg(all(feature = "client", feature = "openapi"))]
pub(crate) const MAX_REF_RESOLUTION_DEPTH: usize = 128;

/// Maximum `$ref` hop-chain length in one resolution (review 002 OAI-11).
/// Depth of *expansion* and length of *pointer chasing* are different
/// axes: the deepest structure reached and the number of distinct refs
/// dereferenced along the way. A linear schema chain of any realistic
/// size stays well under this; runaway chains fail with a clean
/// [`AdapterError::SchemaParse`].
#[cfg(all(feature = "client", feature = "openapi"))]
pub(crate) const MAX_REF_HOP_DEPTH: usize = 64;

/// Maximum number of `Value` nodes materialized by one `resolve_refs_recursive`
/// call (review 002 OAI-11). Memoization makes repeated `$ref` hops cheap, but
/// the fully-inlined output of an acyclic shared-ref chain still grows
/// exponentially in the chain length — a doubly-linked-list spec
/// (`S_i` referenced by both `a` and `b` of `S_{i-1}`) inlines to ~2^N nodes.
/// Neither the visited set nor the depth budget fires for that shape; this
/// budget does, failing import with a clean [`AdapterError::SchemaParse`]
/// instead of wedging with no error (or exhausting memory).
#[cfg(all(feature = "client", feature = "openapi"))]
pub(crate) const MAX_REF_EXPANSION_NODES: usize = 1_000_000;

/// The `paths`-level HTTP methods the adapter models. `trace` is
/// deliberately absent (OAI-06): a path carrying only unsupported
/// methods is skipped with a warning, not imported as a mis-behaving op.
pub(crate) const HTTP_METHODS: &[&str] =
    &["get", "post", "put", "patch", "delete", "head", "options"];

/// Response keys, in precedence order, under which a success envelope
/// may be declared: concrete 2XX statuses first, then the class
/// wildcard `2XX`, then `default` (OAI-06, review 002 OAI-13). The
/// first key present governs SSE detection and the output schema, so a
/// concrete status outranks the wildcard and the wildcard outranks
/// `default`.
#[cfg(all(feature = "client", feature = "openapi"))]
pub(crate) const SUCCESS_RESPONSE_KEYS: &[&str] = &[
    "200", "201", "202", "203", "204", "205", "206", "226", "2XX", "default",
];

/// The `info` block of an OpenAPI document.
#[derive(Clone, Debug)]
pub struct OpenAPIInfo {
    /// Human-readable title (OpenAPI `info.title`).
    pub title: String,
    /// Declared spec/API version (OpenAPI `info.version`).
    pub version: String,
}

/// One entry of a path item: a concrete path plus the operations
/// declared on it.
#[derive(Clone, Debug)]
pub struct PathItem {
    /// `(method, operation)` pairs, methods lowercase as declared in the
    /// document (`get`, `post`, ...), in parsed order.
    pub operations: Vec<(String, Operation)>,
    /// Path-item-level `parameters` shared by every operation under the
    /// path (review 002 OAI-13). Operation-level entries override these
    /// per OpenAPI spec semantics (`name`+`in` identity); at parse time
    /// the two lists are concatenated and the override is resolved when
    /// the input schema is built from the merged sequence.
    pub parameters: Vec<Parameter>,
}

/// One OpenAPI operation parsed into the shared model.
#[derive(Clone, Debug)]
pub struct Operation {
    /// `operationId` when declared; `from_openapi` falls back to
    /// `method_path_derived` naming when absent.
    pub operation_id: Option<String>,
    /// Operation-level (non-`$ref`) parameters; `parameter $ref`s are
    /// resolved before this model is built.
    pub parameters: Vec<Parameter>,
    /// `requestBody` when declared; `requestBody $ref`s are resolved
    /// before this model is built.
    pub request_body: Option<RequestBody>,
    /// Responses keyed by their declared key — concrete statuses
    /// (`"200"`, `"404"`), wildcards (`"4XX"`), or `"default"`. Consumers
    /// must decide how to treat non-numeric keys (OAI-06).
    pub responses: BTreeMap<String, Response>,
}

/// One OpenAPI parameter (`name`/`in`/`required`/`schema`).
#[derive(Clone, Debug)]
pub struct Parameter {
    /// Declared parameter name; must be unique per location per
    /// operation in a valid document.
    pub name: String,
    /// Parameter location: `path`, `query`, `header`, or `cookie`
    /// (the last unsupported and rejected loudly at import).
    pub in_: String,
    /// Whether the operation fails without the parameter.
    pub required: bool,
    /// The parameter's schema as declared (unresolved `$ref`s are
    /// resolved by the consumer via `resolve_refs_recursive`).
    pub schema: Option<Value>,
}

/// An OpenAPI request body — the media-type → schema map of its
/// `content` field.
#[derive(Clone, Debug)]
pub struct RequestBody {
    /// Media type (e.g. `application/json`) → the body schema.
    pub content: BTreeMap<String, Value>,
}

/// An OpenAPI response — the media-type → schema map of its `content`
/// field.
#[derive(Clone, Debug)]
pub struct Response {
    /// Media type (e.g. `application/json`) → the response schema.
    pub content: BTreeMap<String, Value>,
}

/// The `components` block: reusable schemas, parameters, and request
/// bodies keyed by name.
#[derive(Clone, Debug)]
pub struct Components {
    /// `components/schemas` entries.
    pub schemas: HashMap<String, Value>,
    /// `components/parameters` entries.
    pub parameters: HashMap<String, Value>,
    /// `components/requestBodies` entries.
    pub request_bodies: HashMap<String, Value>,
}

/// Converts a merge-applied YAML document into the shared
/// `serde_json::Value` representation, rejecting loudly what the
/// conversion would otherwise silently corrupt (review 002 OAI-12):
///
/// - **Duplicate keys** are rejected before conversion — the input
///   comes from an explicit `yaml_serde::Value` parse, whose `Mapping`
///   insertion rejects duplicates natively (with line/column) where the
///   direct `serde_json::Value` path silently last-wins.
/// - **Non-finite floats** (`yaml_serde::Number` carries
///   `.inf`/`-.inf`/`.nan`, `serde_json::Number` cannot) fail with the
///   value's JSON pointer instead of silently becoming `null`.
/// - **Non-string mapping keys** are stringified exactly as the YAML 1.2
///   core schema renders the scalar (`200:` → `"200"`, matching the JSON
///   path's `{"200": ...}`); keys with no round-trip-stable string form
///   (null keys, sequence/map keys) fail with the key's JSON pointer.
///
/// Recursion follows document structure (already bounded by
/// yaml_serde's parse-time recursion limit) and terminates because
/// YAML mappings are acyclic after alias expansion.
#[cfg(feature = "openapi")]
fn yaml_to_json_value(value: &YamlValue) -> Result<Value, String> {
    match value {
        YamlValue::Null => Ok(Value::Null),
        YamlValue::Bool(b) => Ok(Value::Bool(*b)),
        YamlValue::Number(n) => yaml_number_to_json(n),
        YamlValue::String(s) => Ok(Value::String(s.clone())),
        YamlValue::Tagged(tagged) => yaml_to_json_value(&tagged.value),
        YamlValue::Sequence(items) => {
            let mut out = Vec::with_capacity(items.len());
            for (index, item) in items.iter().enumerate() {
                out.push(
                    yaml_to_json_value(item)
                        .map_err(|detail| format!("/<sequence-element-{index}>: {detail}"))?,
                );
            }
            Ok(Value::Array(out))
        }
        YamlValue::Mapping(map) => {
            let mut out = serde_json::Map::new();
            for (key, val) in map {
                let ptr = yaml_key_pointer(key)?;
                let converted =
                    yaml_to_json_value(val).map_err(|detail| format!("{ptr}: {detail}"))?;
                out.insert(ptr, converted);
            }
            Ok(Value::Object(out))
        }
    }
}

/// Converts one YAML number into a `serde_json::Number`, rejecting
/// non-finite floats loudly (OAI-12): `Number::from_f64(∞)` is `None`,
/// so an unguarded conversion would advertise `null` where the document
/// declares `maximum: .inf`.
#[cfg(feature = "openapi")]
fn yaml_number_to_json(number: &yaml_serde::Number) -> Result<Value, String> {
    if let Some(integer) = number.as_i64() {
        return Ok(Value::Number(serde_json::Number::from(integer)));
    }
    if let Some(unsigned) = number.as_u64() {
        return Ok(Value::Number(serde_json::Number::from(unsigned)));
    }
    let float = number.as_f64().ok_or_else(|| {
        "number is out of range for JSON (neither i64, u64, nor a finite f64)".to_string()
    })?;
    let finite = serde_json::Number::from_f64(float)
        .ok_or_else(|| format!("{float} is not representable in JSON (.inf/.nan)"))?;
    Ok(Value::Number(finite))
}

/// Renders one YAML mapping key as its `serde_json::Map` string key,
/// preserving the YAML 1.2 core schema's scalar rendering so numeric
/// keys match what the JSON path requires (`200:` → `"200"`). Keys
/// without a round-trip-stable string form are rejected loudly:
/// nullish keys (`~`, empty) and collection keys (sequences, mappings).
#[cfg(feature = "openapi")]
fn yaml_key_pointer(key: &YamlValue) -> Result<String, String> {
    match key {
        YamlValue::String(s) => Ok(s.clone()),
        YamlValue::Bool(b) => Ok(b.to_string()),
        YamlValue::Number(n) => {
            if let Some(integer) = n.as_i64() {
                return Ok(integer.to_string());
            }
            if let Some(unsigned) = n.as_u64() {
                return Ok(unsigned.to_string());
            }
            match n.as_f64().and_then(serde_json::Number::from_f64) {
                Some(finite) => Ok(finite.to_string()),
                None => Err(format!(
                    "mapping key {n:?} is a non-finite number with no string form"
                )),
            }
        }
        YamlValue::Tagged(tagged) => yaml_key_pointer(&tagged.value),
        other => Err(format!(
            "mapping key {other:?} has no string form; only string, number, and boolean \
             keys can be represented in an OpenAPI document"
        )),
    }
}

fn index_component_map(raw: Option<&Value>) -> HashMap<String, Value> {
    let mut map = HashMap::new();
    if let Some(obj) = raw.and_then(|m| m.as_object()) {
        for (k, v) in obj {
            map.insert(k.clone(), v.clone());
        }
    }
    map
}

/// A parsed OpenAPI 3.x document: the typed model (`info`, `paths`,
/// `components`) plus the untouched `raw` document for `$ref`
/// resolution.
#[derive(Debug)]
pub struct OpenAPISpec {
    /// The parsed `info` block.
    pub info: OpenAPIInfo,
    /// The path items keyed by their literal path string (with
    /// placeholders).
    pub paths: BTreeMap<String, PathItem>,
    /// The `components` block, when the document declares one.
    pub components: Option<Components>,
    /// The full document as parsed — the lookup target for `$ref`
    /// resolution.
    pub raw: Value,
}

impl OpenAPISpec {
    /// Parse a JSON OpenAPI document.
    ///
    /// Fails with [`AdapterError::SchemaParse`] for malformed JSON or an
    /// invalid document structure (missing `info`/`paths`, unresolvable
    /// parameter `$ref`s).
    pub fn from_json(doc: &str) -> Result<Self, AdapterError> {
        let raw: Value = serde_json::from_str(doc).map_err(|e| AdapterError::SchemaParse {
            message: format!("invalid JSON: {e}"),
        })?;
        Self::from_value(raw)
    }

    /// Parse a YAML OpenAPI document.
    ///
    /// The caller has declared the format, so this does not attempt JSON
    /// first — whatever type interpretation the YAML parser's schema
    /// applies is what the caller gets (see ADR-051 §2). YAML is parsed
    /// to a `serde_json::Value` and then fed through
    /// [`from_value`](Self::from_value), so there is one internal
    /// `OpenAPISpec` representation shared with the JSON path.
    ///
    /// The parse runs in two steps, both bounded by `yaml_serde`'s own
    /// recursion/alias limits (OAI-12): an explicit
    /// `yaml_serde::Value` parse — so duplicate keys are rejected
    /// natively with line/column, instead of silently last-winning
    /// through the direct-to-`serde_json::Value` path — followed by
    /// [`apply_merge`](yaml_serde::Value::apply_merge) (YAML 1.1-style
    /// `<<: *anchor` merge keys are **applied**, matching the
    /// merge-key.html behavior users authoring YAML anchors expect; ADR-051
    /// declares YAML 1.2 core schema for scalars, and this is the one
    /// deliberate deviation), then a normalization pass into
    /// `serde_json::Value` that rejects loudly what `serde_json::Number`
    /// cannot represent: non-finite floats (`.inf`/`.nan` would silently
    /// null) and non-string mapping keys with no round-trip-stable
    /// string form. Every rejection names the JSON pointer of the
    /// offending value.
    #[cfg(feature = "openapi")]
    pub fn from_yaml(doc: &str) -> Result<Self, AdapterError> {
        let yaml: YamlValue = yaml_serde::from_str(doc).map_err(|e| AdapterError::SchemaParse {
            message: format!("invalid YAML: {e}"),
        })?;
        let mut yaml = yaml;
        yaml.apply_merge().map_err(|e| AdapterError::SchemaParse {
            message: format!("invalid YAML merge key: {e}"),
        })?;
        let raw = yaml_to_json_value(&yaml).map_err(|message| AdapterError::SchemaParse {
            message: format!("invalid YAML: {message}"),
        })?;
        Self::from_value(raw)
    }

    /// Parse a raw OpenAPI document of unknown format.
    ///
    /// Detection is **JSON-first, YAML-fallback** (ADR-051 §2). JSON's
    /// stricter grammar is immune to any YAML-specific type
    /// interpretation, so a JSON doc never reaches the YAML parser under
    /// `from_str`. This is a defensive default: `yaml_serde` 0.10.x
    /// implements the YAML 1.2 core schema (bare `yes`/`no`/`on`/`off`
    /// are strings, not booleans), so the coercion hazard is not present
    /// with this dependency version — but JSON-first locks the contract
    /// against a future YAML-parser swap (e.g., to a YAML 1.1 crate where
    /// those tokens coerce to booleans). A YAML-only document (no JSON
    /// braces) fails JSON parse immediately and goes to the YAML path.
    #[allow(
        clippy::should_implement_trait,
        reason = "ADR-051 §1 names this an inherent constructor `from_str`, not a FromStr impl"
    )]
    pub fn from_str(doc: &str) -> Result<Self, AdapterError> {
        match serde_json::from_str::<Value>(doc) {
            Ok(raw) => Self::from_value(raw),
            #[cfg(feature = "openapi")]
            Err(_) => Self::from_yaml(doc),
            #[cfg(not(feature = "openapi"))]
            Err(_) => Self::from_json(doc),
        }
    }

    /// Parse an already-deserialized OpenAPI document.
    ///
    /// Validation mirrors [`from_json`](Self::from_json): the object
    /// shape, `info`/`paths` presence, parameter `$ref` resolvability,
    /// and the OAI-06 loud-feature gates (`servers` overrides,
    /// non-default `style`/`explode`) all apply.
    pub fn from_value(raw: Value) -> Result<Self, AdapterError> {
        if !raw.is_object() {
            return Err(AdapterError::SchemaParse {
                message: "OpenAPI document must be a JSON object".into(),
            });
        }

        let info_obj = raw.get("info").ok_or_else(|| AdapterError::SchemaParse {
            message: "OpenAPI document missing `info`".into(),
        })?;
        let info = OpenAPIInfo {
            title: info_obj
                .get("title")
                .and_then(|v| v.as_str())
                .unwrap_or("")
                .to_string(),
            version: info_obj
                .get("version")
                .and_then(|v| v.as_str())
                .unwrap_or("1.0.0")
                .to_string(),
        };

        let paths_raw = raw.get("paths").ok_or_else(|| AdapterError::SchemaParse {
            message: "OpenAPI document missing `paths`".into(),
        })?;
        if !paths_raw.is_object() {
            return Err(AdapterError::SchemaParse {
                message: "`paths` must be a JSON object".into(),
            });
        }

        let provisional = Self {
            info: info.clone(),
            paths: BTreeMap::new(),
            components: Some(Components {
                schemas: index_component_map(raw.get("components").and_then(|c| c.get("schemas"))),
                parameters: index_component_map(
                    raw.get("components").and_then(|c| c.get("parameters")),
                ),
                request_bodies: index_component_map(
                    raw.get("components").and_then(|c| c.get("requestBodies")),
                ),
            }),
            raw: raw.clone(),
        };

        // OAI-06: `servers` anywhere in the document (doc root, path, or
        // operation level) would be a silent override of where forwarding
        // handlers send traffic — the adapter routes everything through
        // the single `base_url` configured at assembly time. Reject
        // loudly so the import names the feature and the remediation.
        let mut servers_locations: Vec<String> = Vec::new();
        if raw.get("servers").is_some() {
            servers_locations.push("document".to_string());
        }
        if raw.get("webhooks").is_some() {
            // OAI-13: `webhooks` are consumer-registered, server-initiated
            // callbacks — the inbound direction the single-endpoint HTTP
            // adapter does not model (no inbound route table). Silently
            // vanishing them (the pre-OAI-13 behavior) hides half the
            // document's declared surface; failing the mixed document
            // names the feature. Same philosophy for `callbacks` would
            // be a separate review item.
            return Err(AdapterError::SchemaParse {
                message: "the document declares top-level `webhooks`, which the HTTP \
                          adapter cannot import: webhooks are server-initiated \
                          callbacks (inbound), while the adapter registers outbound \
                          forwarding operations only — split the webhooks into their \
                          own service definition or remove the `webhooks` key \
                          (review 002 OAI-13)"
                    .into(),
            });
        }
        if let Some(paths_obj) = paths_raw.as_object() {
            for (path, item) in paths_obj {
                if item.as_object().is_some_and(|o| o.contains_key("servers")) {
                    servers_locations.push(format!("path {path}"));
                    continue;
                }
                for method in HTTP_METHODS {
                    if item
                        .get(method)
                        .and_then(|op| op.as_object())
                        .is_some_and(|op| op.contains_key("servers"))
                    {
                        servers_locations.push(format!("{method} {path}"));
                    }
                }
            }
        }
        if !servers_locations.is_empty() {
            return Err(AdapterError::SchemaParse {
                message: format!(
                    "the document declares `servers` override(s) at: {}. The HTTP adapter \
                     routes all operations of a service through the single `base_url` \
                     configured at assembly time and cannot honor per-location `servers` — \
                     remove the `servers` entries or split the service into one import per \
                     base URL (review 001 OAI-06)",
                    bounded_join(&servers_locations)
                ),
            });
        }

        let mut paths = BTreeMap::new();
        if let Some(paths_obj) = paths_raw.as_object() {
            for (path, item) in paths_obj {
                if !item.is_object() {
                    continue;
                }
                let mut operations = Vec::new();
                for method in HTTP_METHODS {
                    if let Some(op_raw) = item.get(*method) {
                        let locator = format!("{method} {path}");
                        match parse_operation(op_raw, &provisional, &locator) {
                            Ok(Some(op)) => operations.push((method.to_string(), op)),
                            Ok(None) => {
                                return Err(AdapterError::SchemaParse {
                                    message: format!(
                                        "unresolvable $ref or missing `name`/`in` in parameter of \
                                         {method} {path}, or an unresolvable/content-less \
                                         `requestBody` on the operation (review 001 OAI-04, \
                                         review 002 OAI-15)"
                                    ),
                                });
                            }
                            Err(style_error) => {
                                return Err(AdapterError::SchemaParse {
                                    message: format!(
                                        "parameter `{}` on {method} {path} {}: (review 001 OAI-06)",
                                        style_error.parameter, style_error.detail
                                    ),
                                });
                            }
                        }
                    }
                }
                if operations.is_empty() {
                    // OAI-06: `trace` is not in the supported method set;
                    // a path entry carrying only unsupported methods was
                    // previously skipped without a trace. Surface it. The
                    // fixed path-item keys (`parameters`, `servers`,
                    // `summary`, `description`) are inert at this level —
                    // either mirrored into each operation (`parameters`
                    // merged below, OAI-13) or deliberately unsupported
                    // (`servers` rejected earlier, OAI-06) — so they do
                    // not count as skipped features when no method is
                    // present to receive them.
                    let skipped: Vec<&str> = item
                        .as_object()
                        .map(|o| {
                            o.keys()
                                .map(|k| k.as_str())
                                .filter(|k| {
                                    !HTTP_METHODS.contains(k)
                                        && *k != "parameters"
                                        && *k != "servers"
                                        && *k != "summary"
                                        && *k != "description"
                                })
                                .collect()
                        })
                        .unwrap_or_default();
                    if !skipped.is_empty() {
                        tracing::warn!(
                            path = %path,
                            methods = %skipped.join(", "),
                            "path declares only unsupported HTTP methods; skipping it \
                             (review 001 OAI-06)"
                        );
                    }
                    continue;
                }
                let merged = ItemParameters::parse(item, &provisional).map_err(|style_error| {
                    AdapterError::SchemaParse {
                        message: format!(
                            "parameter `{}` on path item {path} {}: (review 001 OAI-06)",
                            style_error.parameter, style_error.detail
                        ),
                    }
                })?;
                paths.insert(
                    path.clone(),
                    PathItem {
                        operations,
                        parameters: merged,
                    },
                );
            }
        }

        let components = raw.get("components").map(|c| Components {
            schemas: index_component_map(c.get("schemas")),
            parameters: index_component_map(c.get("parameters")),
            request_bodies: index_component_map(c.get("requestBodies")),
        });

        Ok(Self {
            info,
            paths,
            components,
            raw,
        })
    }

    /// Import-time loud-feature gate for the *service import* path
    /// (`FromOpenAPI::import`), not the shared structural parse:
    /// `from_value` also re-validates the published gateway doc inside
    /// `to_openapi`, and that self-description legitimately carries
    /// `security` markers for its external HTTP clients. A *service*
    /// spec declaring the OAI-14 blocks would import silently-degraded
    /// operations, so the import refuses where the semantics would be
    /// lost; the gateway doc's own markers are inert here.
    #[cfg(all(feature = "client", feature = "openapi"))]
    pub(crate) fn validate_import_loud_features(&self) -> Result<(), AdapterError> {
        let mut callback_locations: Vec<String> = Vec::new();
        let mut security_locations: Vec<String> = Vec::new();
        if self.raw.get("callbacks").is_some() {
            callback_locations.push("document".to_string());
        }
        if self.raw.get("security").is_some() {
            security_locations.push("document".to_string());
        }
        if let Some(paths_obj) = self.raw.get("paths").and_then(|p| p.as_object()) {
            for (path, item) in paths_obj {
                let Some(item_obj) = item.as_object() else {
                    continue;
                };
                for method in HTTP_METHODS {
                    let Some(op) = item_obj.get(*method).and_then(|op| op.as_object()) else {
                        continue;
                    };
                    if op.contains_key("callbacks") {
                        callback_locations.push(format!("{method} {path}"));
                    }
                    if op.contains_key("security") {
                        security_locations.push(format!("{method} {path}"));
                    }
                }
            }
        }
        if !callback_locations.is_empty() {
            return Err(AdapterError::SchemaParse {
                message: format!(
                    "the document declares `callbacks` at: {}. Callbacks are \
                     server-initiated outbound calls (inbound to this service) that the \
                     single-endpoint HTTP adapter does not model — remove the \
                     `callbacks` entries or split those operations into their own \
                     service definition (review 002 OAI-14)",
                    bounded_join(&callback_locations)
                ),
            });
        }
        if !security_locations.is_empty() {
            return Err(AdapterError::SchemaParse {
                message: format!(
                    "the document declares `security` requirement(s) at: {}. The HTTP \
                     adapter injects credentials exclusively through Capabilities per \
                     the declared auth scheme (review 001 OAI-06 posture); OpenAPI \
                     security requirements would silently change nothing at call time — \
                     remove the `security` blocks or set the `auth` field on the service \
                     config instead (review 002 OAI-14)",
                    bounded_join(&security_locations)
                ),
            });
        }
        Ok(())
    }

    pub(crate) fn resolve_ref(&self, reference: &str) -> Result<Value, AdapterError> {
        let bounded = |r: &str| {
            if r.chars().count() > 128 {
                format!("{}…", r.chars().take(128).collect::<String>())
            } else {
                r.to_string()
            }
        };
        if !reference.starts_with("#/") {
            return Err(AdapterError::SchemaParse {
                message: format!("external $ref not supported: {}", bounded(reference)),
            });
        }
        let mut current: &Value = &self.raw;
        for part in reference.trim_start_matches("#/").split('/') {
            current = current.get(part).ok_or_else(|| AdapterError::SchemaParse {
                message: format!("cannot resolve $ref: {}", bounded(reference)),
            })?;
        }
        Ok(current.clone())
    }

    /// Resolve `$ref` pointers within `schema` against the raw document,
    /// returning a fully expanded copy.
    ///
    /// Recursion is bounded in both stack and total work: a visited set
    /// keyed on the JSON-pointer path rejects a `$ref` that is already
    /// being expanded on the current branch (a self/circular reference —
    /// trees, linked lists, cursor pagination), a depth budget rejects
    /// pathologically deep nesting, and a per-document memo of completed
    /// cycle-free `$ref` expansions ensures each distinct ref target is
    /// expanded once and reused by clone on every later hop (review 002
    /// OAI-11) — an acyclic shared-ref chain grows linearly instead of
    /// as an exponential tree. All four surface as
    /// [`AdapterError::SchemaParse`] at import instead of recursing to
    /// stack exhaustion or wedging without an error. Fully-expanded
    /// inlining of recursive schemas is deliberately not supported; specs
    /// that rely on it fail loudly here (review 001 OAI-01, review 002
    /// OAI-11). Memo entries are written only after a successful
    /// expansion, so a partial expansion under a cyclic branch is never
    /// cached and cycle detection semantics are unchanged.
    ///
    /// As the final bound (a memo alone cannot shrink the inlined output of
    /// an acyclic exponential shared-ref chain), a per-call node budget
    /// counts every materialized `Value` node; exceeding it fails import
    /// with a clean error naming the budget (OAI-11).
    #[cfg(all(feature = "client", feature = "openapi"))]
    pub(crate) fn resolve_refs_recursive(&self, schema: &Value) -> Result<Value, AdapterError> {
        self.resolve_refs_bounded(schema, &mut RefResolution::default(), 0, 0)
    }

    #[cfg(all(feature = "client", feature = "openapi"))]
    fn resolve_refs_bounded(
        &self,
        schema: &Value,
        state: &mut RefResolution,
        depth: usize,
        hops: usize,
    ) -> Result<Value, AdapterError> {
        if depth > MAX_REF_RESOLUTION_DEPTH {
            return Err(AdapterError::SchemaParse {
                message: format!(
                    "$ref resolution exceeded depth budget of {MAX_REF_RESOLUTION_DEPTH} \
                     (self-referential or pathologically nested schema)"
                ),
            });
        }
        state.nodes = state.nodes.saturating_add(1);
        if state.nodes > MAX_REF_EXPANSION_NODES {
            return Err(AdapterError::SchemaParse {
                message: format!(
                    "$ref expansion exceeded node budget of {MAX_REF_EXPANSION_NODES} \
                     (acyclic shared-$ref chain expanding exponentially; the schema is \
                     valid but its full inline expansion is too large to materialize)"
                ),
            });
        }
        match schema {
            Value::Object(obj) => {
                if let Some(Value::String(reference)) = obj.get("$ref") {
                    if let Some(resolved) = state.memo.get(reference) {
                        let nodes = count_nodes(resolved);
                        state.nodes = state.nodes.saturating_add(nodes);
                        if state.nodes > MAX_REF_EXPANSION_NODES {
                            return Err(AdapterError::SchemaParse {
                                message: format!(
                                    "$ref expansion exceeded node budget of \
                                     {MAX_REF_EXPANSION_NODES} \
                                     (acyclic shared-$ref chain expanding exponentially; \
                                     the schema is valid but its full inline expansion is \
                                     too large to materialize)"
                                ),
                            });
                        }
                        return Ok(resolved.clone());
                    }
                    if !state.resolving.insert(reference.clone()) {
                        return Err(AdapterError::SchemaParse {
                            message: format!(
                                "circular $ref detected at depth {depth}: {reference}"
                            ),
                        });
                    }
                    let resolved = self.resolve_ref(reference)?;
                    let hops = hops + 1;
                    if hops > MAX_REF_HOP_DEPTH {
                        return Err(AdapterError::SchemaParse {
                            message: format!(
                                "$ref resolution exceeded hop budget of {MAX_REF_HOP_DEPTH} \
                                 (runaway $ref chain)"
                            ),
                        });
                    }
                    let out = self.resolve_refs_bounded(&resolved, state, depth + 1, hops);
                    state.resolving.remove(reference);
                    let value = out?;
                    state.memo.insert(reference.clone(), value.clone());
                    return Ok(value);
                }
                if depth + 1 > MAX_REF_RESOLUTION_DEPTH {
                    return Err(AdapterError::SchemaParse {
                        message: format!(
                            "schema nesting exceeded depth budget of {MAX_REF_RESOLUTION_DEPTH} \
                             (self-referential or pathologically nested schema)"
                        ),
                    });
                }
                let mut out = serde_json::Map::new();
                for (k, v) in obj {
                    out.insert(
                        k.clone(),
                        self.resolve_refs_bounded(v, state, depth + 1, hops)?,
                    );
                }
                Ok(Value::Object(out))
            }
            Value::Array(arr) => {
                let mut out = Vec::with_capacity(arr.len());
                for v in arr {
                    out.push(self.resolve_refs_bounded(v, state, depth + 1, hops)?);
                }
                Ok(Value::Array(out))
            }
            other => Ok(other.clone()),
        }
    }
}

/// Cycle-scoped state for [`OpenAPISpec::resolve_refs_recursive`]: the
/// in-flight `$ref` chain (cycle detection), the memo of completed
/// cycle-free expansions (total-work bounding, review 002 OAI-11), and the
/// per-call node counter (the last-resort bound on inlined output size).
#[derive(Default)]
#[cfg(all(feature = "client", feature = "openapi"))]
struct RefResolution {
    resolving: HashSet<String>,
    memo: HashMap<String, Value>,
    nodes: usize,
}

#[cfg(all(feature = "client", feature = "openapi"))]
fn count_nodes(value: &Value) -> usize {
    match value {
        Value::Object(map) => 1 + map.values().map(count_nodes).sum::<usize>(),
        Value::Array(items) => 1 + items.iter().map(count_nodes).sum::<usize>(),
        _ => 1,
    }
}

/// Collects the schema-embedded keywords the adapter silently ignores
/// (review 002 OAI-14): `discriminator` (polymorphic serialization
/// headers the forwarder does not emit) and `xml` (wire-format
/// annotations for XML serialization the adapter never performs). Both
/// change what a conforming client would send or expect on the wire;
/// vanishing them silently lets a schema advertise a shape the calls
/// never honor. The walk visits only the *declared* schema (already
/// bounded by the resolver's budgets before this runs on resolved
/// output); it is linear in schema size.
#[cfg(all(feature = "client", feature = "openapi"))]
pub(crate) fn collect_ignored_schema_keys(value: &Value, found: &mut Vec<String>) {
    let mut stack = vec![value];
    while let Some(current) = stack.pop() {
        match current {
            Value::Object(map) => {
                for (k, v) in map {
                    if k == "discriminator" || k == "xml" {
                        found.push(k.clone());
                    }
                    stack.push(v);
                }
            }
            Value::Array(items) => {
                stack.extend(items.iter());
            }
            _ => {}
        }
    }
}

/// Warns once per offending `$ref` object about sibling keys left
/// beside the `$ref` (review 002 OAI-10): under OpenAPI 3.0 the
/// siblings are ignored, but 3.1 applies them alongside the reference —
/// so a document authored against 3.1 semantics would advertise
/// constraints (`minLength: 3`) through `/schema` that the adapter's
/// resolved schema (used at call time) does not carry. There is no
/// `openapi: 3.1` version gate; the import proceeds with the 3.0
/// reading while naming the dropped keys.
fn warn_ref_siblings(context: &str, holder: &Value) {
    if let Some(obj) = holder.as_object() {
        let siblings: Vec<&String> = obj.keys().filter(|k| *k != "$ref").collect();
        if !siblings.is_empty() {
            let names: Vec<String> = siblings.iter().map(|s| s.as_str().to_string()).collect();
            tracing::warn!(
                location = %context,
                siblings = %names.join(", "),
                "$ref carries sibling keys; OpenAPI 3.0 semantics apply — the \
                 siblings are ignored (not merged into the resolved target as \
                 3.1 would do), so constraints authored beside the $ref are \
                 not enforced at call time (review 002 OAI-10)"
            );
        }
    }
}

/// Parses one operation (OAI-04/OAI-15). Returns `Ok(None)` when the
/// operation cannot be modeled faithfully: an unresolvable parameter
/// `$ref`, a parameter missing `name`/`in`, an unresolvable
/// `requestBody` `$ref`, or a resolved `requestBody` that still carries
/// a top-level `$ref` or lacks `content` — a body-less op would
/// register silently and fail every call with `INVALID_INPUT` on
/// `body` (review 002 OAI-15).
fn parse_operation(
    raw: &Value,
    spec: &OpenAPISpec,
    locator: &str,
) -> Result<Option<Operation>, ParameterStyleError> {
    if !raw.is_object() {
        return Ok(None);
    }
    let operation_id = raw
        .get("operationId")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let mut parameters = Vec::new();
    if let Some(arr) = raw.get("parameters").and_then(|v| v.as_array()) {
        for (index, p) in arr.iter().enumerate() {
            let p = match p.get("$ref").and_then(|r| r.as_str()) {
                Some(reference) => {
                    warn_ref_siblings(&format!("parameter[{index}] $ref {reference}"), p);
                    match spec.resolve_ref(reference) {
                        Ok(resolved) => resolved,
                        Err(_) => return Ok(None),
                    }
                }
                None => p.clone(),
            };
            let Some(name) = p.get("name").and_then(|v| v.as_str()) else {
                return Ok(None);
            };
            let Some(in_) = p.get("in").and_then(|v| v.as_str()) else {
                return Ok(None);
            };
            check_parameter_style(name, in_, &p)?;
            let required = p.get("required").and_then(|v| v.as_bool()).unwrap_or(false);
            let schema = p.get("schema").cloned();
            parameters.push(Parameter {
                name: name.to_string(),
                in_: in_.to_string(),
                required,
                schema,
            });
        }
    }

    let request_body = match raw.get("requestBody") {
        Some(rb) => {
            let body = match rb.get("$ref").and_then(|r| r.as_str()) {
                Some(reference) => {
                    warn_ref_siblings(&format!("requestBody $ref {reference}"), rb);
                    match spec.resolve_ref(reference) {
                        Ok(resolved) => resolved,
                        Err(_) => return Ok(None),
                    }
                }
                None => rb.clone(),
            };
            if body.get("$ref").is_some() || !body.get("content").is_some_and(|c| c.is_object()) {
                return Ok(None);
            }
            // OAI-14: a requestBody shaped `{oneOf: [...]}` (the union form
            // some 3.1-era generators emit) has no `content` map, so the
            // media-type keyed body contract is unrepresentable — it must
            // not silently import as a body-less op.
            if body.get("oneOf").is_some() {
                return Err(ParameterStyleError {
                    parameter: "requestBody".to_string(),
                    detail: format!(
                        "on {locator}: uses a top-level `oneOf` requestBody (no \
                         `content` map), which the HTTP adapter cannot turn into the \
                         gateway's media-typed body contract — wrap each variant in a \
                         `content` entry (e.g. application/json) or split into separate \
                         operations (review 002 OAI-14)"
                    ),
                });
            }
            let Some(content_obj) = body.get("content").and_then(|v| v.as_object()) else {
                return Ok(None);
            };
            let mut content = BTreeMap::new();
            for (k, v) in content_obj {
                let schema = v.get("schema").cloned().unwrap_or(Value::Null);
                content.insert(k.clone(), schema);
            }
            Some(RequestBody { content })
        }
        None => None,
    };

    let mut responses = BTreeMap::new();
    if let Some(resp_obj) = raw.get("responses").and_then(|v| v.as_object()) {
        for (code, body) in resp_obj {
            let content_obj = body.get("content").and_then(|v| v.as_object());
            let mut content = BTreeMap::new();
            if let Some(content_obj) = content_obj {
                for (k, v) in content_obj {
                    let schema = v.get("schema").cloned().unwrap_or(Value::Null);
                    content.insert(k.clone(), schema);
                }
            }
            responses.insert(code.clone(), Response { content });
        }
    }

    Ok(Some(Operation {
        operation_id,
        parameters,
        request_body,
        responses,
    }))
}

/// Parses the path-item-level `parameters` array (review 002 OAI-13).
///
/// `$ref`ed parameters (`#/components/parameters/...`) resolve the same
/// way operation-level ones do; an unresolvable ref or a parameter
/// missing `name`/`in` fails import with the path named. `style`/
/// `explode` gates (OAI-06) apply at this level too — a shared
/// `deepObject` parameter would mis-serialize for every operation under
/// the path, so it is refused once, here.
struct ItemParameters;

impl ItemParameters {
    fn parse(item: &Value, spec: &OpenAPISpec) -> Result<Vec<Parameter>, ParameterStyleError> {
        let path_style_error = |detail: String| ParameterStyleError {
            parameter: "path-item parameters".to_string(),
            detail,
        };
        let mut out = Vec::new();
        let Some(arr) = item.get("parameters").and_then(|v| v.as_array()) else {
            return Ok(out);
        };
        for (index, p) in arr.iter().enumerate() {
            let p = match p.get("$ref").and_then(|r| r.as_str()) {
                Some(reference) => {
                    warn_ref_siblings(&format!("path-item parameter[{index}] $ref {reference}"), p);
                    spec.resolve_ref(reference)
                        .map_err(|_| path_style_error(format!("unresolvable $ref: {reference}")))?
                }
                None => p.clone(),
            };
            let Some(name) = p.get("name").and_then(|v| v.as_str()) else {
                return Err(path_style_error(
                    "path-item parameter is missing `name`".to_string(),
                ));
            };
            let Some(in_) = p.get("in").and_then(|v| v.as_str()) else {
                return Err(path_style_error(format!(
                    "path-item parameter `{name}` is missing `in`"
                )));
            };
            check_parameter_style(name, in_, &p)?;
            out.push(Parameter {
                name: name.to_string(),
                in_: in_.to_string(),
                required: p.get("required").and_then(|v| v.as_bool()).unwrap_or(false),
                schema: p.get("schema").cloned(),
            });
        }
        Ok(out)
    }
}

/// A parameter whose `style`/`explode` declaration the adapter cannot
/// serialize faithfully. Carries the parameter identity so the import
/// error names the feature (OAI-06 cookie-style loudness).
#[derive(Debug)]
pub(crate) struct ParameterStyleError {
    pub parameter: String,
    pub detail: String,
}

/// Rejects non-default `style`/`explode` parameter serializations
/// (OAI-06). Supported (wire-equivalent to the adapter's emitter):
/// `form` (the query/path default, explode on) and `simple` (the
/// header/path default, explode off). Everything else — including
/// `spaceDelimited`/`pipeDelimited`/`deepObject` and non-default
/// `explode` flips — would mis-serialize arrays and objects, so it is
/// refused.
fn check_parameter_style(
    name: &str,
    parameter_in: &str,
    p: &Value,
) -> Result<(), ParameterStyleError> {
    let _ = parameter_in;
    let unsupported = |detail: String| ParameterStyleError {
        parameter: name.to_string(),
        detail,
    };
    let style = p.get("style").and_then(|v| v.as_str());
    let explode = p.get("explode");
    match (style, explode) {
        (None, _) => Ok(()),
        (Some("form"), None | Some(Value::Bool(true))) => Ok(()),
        (Some("simple"), None | Some(Value::Bool(false))) => Ok(()),
        (Some("form"), Some(Value::Bool(false))) => Err(unsupported(
            "sets `style: form` with `explode: false`, which would comma-glue arrays \
             (`?a=1,2`); the adapter emits the exploded default (repeated keys) — remove \
             the `explode: false` or move the aggregation into the request body"
                .to_string(),
        )),
        (Some("simple"), Some(Value::Bool(true))) => Err(unsupported(
            "sets `style: simple` with `explode: true`; `simple` applies to headers and \
             path segments where `explode` has no meaning for the adapter's emitter — \
             remove the `explode: true`"
                .to_string(),
        )),
        (Some(other), _) => Err(unsupported(format!(
            "uses `style: {other}`, which the HTTP adapter does not serialize; the adapter \
             emits query/path parameters in the form default (repeated keys for arrays) — \
             drop the `style` declaration or serialize client-side"
        ))),
    }
}

#[cfg(all(test, feature = "client", feature = "openapi"))]
mod tests {
    use super::*;
    use crate::adapters::{FromOpenAPI, HttpServiceConfig};
    use crate::client::{HttpClientConfig, SharedHttpClient};
    use alkcall::client::OperationAdapter;
    use serde_json::json;
    use std::sync::Arc;

    fn wrap_spec(raw: Value) -> OpenAPISpec {
        OpenAPISpec::from_value(raw).expect("test spec is valid")
    }

    fn schema_test_spec(schema: Value) -> OpenAPISpec {
        wrap_spec(json!({
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/x": {"get": {"operationId": "x", "responses": {
                    "200": {"content": {"application/json": {"schema": {}}}
                }}}}
            },
            "components": {"schemas": schema}
        }))
    }

    fn nested_object(depth: usize) -> Value {
        let mut current = json!({"type": "string"});
        for _ in 0..depth {
            current = json!({"type": "object", "properties": {"child": current}});
        }
        current
    }

    #[test]
    fn parameter_ref_to_components_resolves_into_operation() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "components": {
                "parameters": {
                    "Id": {
                        "name": "id",
                        "in": "path",
                        "required": true,
                        "schema": {"type": "string", "pattern": "^[0-9]+$"}
                    },
                    "Q": {"name": "q", "in": "query", "schema": {"type": "boolean"}}
                }
            },
            "paths": {
                "/users/{id}": {"get": {
                    "operationId": "getUser",
                    "parameters": [
                        {"$ref": "#/components/parameters/Id"},
                        {"$ref": "#/components/parameters/Q"}
                    ],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).unwrap();
        let item = spec.paths.get("/users/{id}").expect("path present");
        let (_, op) = &item.operations[0];
        assert_eq!(op.operation_id.as_deref(), Some("getUser"));
        assert_eq!(op.parameters.len(), 2);
        assert_eq!(op.parameters[0].name, "id");
        assert_eq!(op.parameters[0].in_, "path");
        assert!(op.parameters[0].required);
        let schema = op.parameters[0].schema.as_ref().expect("schema present");
        assert_eq!(schema["pattern"], "^[0-9]+$");
        assert_eq!(op.parameters[1].name, "q");
        assert_eq!(op.parameters[1].in_, "query");
        assert!(!op.parameters[1].required);
    }

    #[test]
    fn request_body_ref_to_components_resolves() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "components": {
                "requestBodies": {
                    "WidgetInput": {
                        "content": {
                            "application/json": {
                                "schema": {"type": "object", "properties": {"name": {"type": "string"}}}
                            }
                        },
                        "required": true
                    }
                }
            },
            "paths": {
                "/widgets": {"post": {
                    "operationId": "createWidget",
                    "requestBody": {"$ref": "#/components/requestBodies/WidgetInput"},
                    "responses": {"201": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).unwrap();
        let item = spec.paths.get("/widgets").expect("path present");
        let (_, op) = &item.operations[0];
        let rb = op.request_body.as_ref().expect("requestBody resolved");
        let schema = rb.content.get("application/json").expect("json content");
        let props = schema.get("properties").expect("schema expanded");
        assert!(props.get("name").is_some());
    }

    /// The structural-reject arms at the very top of `from_value`
    /// (before any path walking): a non-object document, a
    /// missing-`info` object, and a non-object `paths` each fail with
    /// `SchemaParse` naming the missing/mistyped member.
    #[test]
    fn from_value_structural_rejects_name_the_missing_member() {
        for (raw, expected_fragment) in [
            (json!("just a string"), "must be a JSON object"),
            (json!([1, 2, 3]), "must be a JSON object"),
            (json!({"paths": {}}), "missing `info`"),
            (
                json!({"info": {"title": "T", "version": "1"}}),
                "missing `paths`",
            ),
            (
                json!({
                    "info": {"title": "T", "version": "1"},
                    "paths": ["/x"]
                }),
                "`paths` must be a JSON object",
            ),
        ] {
            match OpenAPISpec::from_value(raw) {
                Err(AdapterError::SchemaParse { message }) => {
                    assert!(
                        message.contains(expected_fragment),
                        "message `{message}` lacks `{expected_fragment}`"
                    );
                }
                Ok(_) => panic!("the malformed document must be rejected"),
                other => panic!("expected SchemaParse, got {other:?}"),
            }
        }
    }

    #[test]
    fn request_body_self_ref_fails_import_not_silent_bodyless_op() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/widgets": {"post": {
                    "operationId": "createWidget",
                    "requestBody": {"$ref": "#/paths/~1widgets/post/requestBody"},
                    "responses": {"201": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("requestBody"),
                    "the error must name the requestBody: {message}"
                );
                assert!(message.contains("OAI-15"), "message was: {message}");
            }
            Ok(spec) => {
                let body = &spec.paths["/widgets"].operations[0].1.request_body;
                assert!(
                    body.is_none(),
                    "a self-ref'd requestBody must not silently import as body-less (OAI-15)"
                );
                panic!("self-$ref'd requestBody must fail import loudly (OAI-15)");
            }
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn request_body_ref_to_missing_component_fails_import_loudly() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/widgets": {"post": {
                    "operationId": "createWidget",
                    "requestBody": {"$ref": "#/components/requestBodies/Missing"},
                    "responses": {"201": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("requestBody") || message.contains("unresolvable"),
                    "message was: {message}"
                );
                assert!(message.contains("post /widgets"), "message was: {message}");
            }
            Ok(_) => panic!("unresolvable requestBody $ref must fail import loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn content_less_request_body_fails_import_not_silent_bodyless_op() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "components": {
                "requestBodies": {
                    "DescriptionOnly": {"description": "no content map"}
                }
            },
            "paths": {
                "/widgets": {"post": {
                    "operationId": "createWidget",
                    "requestBody": {"$ref": "#/components/requestBodies/DescriptionOnly"},
                    "responses": {"201": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("requestBody") || message.contains("unresolvable"),
                    "message was: {message}"
                );
            }
            Ok(spec) => {
                let body = &spec.paths["/widgets"].operations[0].1.request_body;
                assert!(body.is_none(), "content-less body must not silently drop");
                panic!("content-less requestBody must fail import loudly (OAI-15)");
            }
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn parameter_ref_to_missing_component_fails_import_loudly() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/x": {"get": {
                    "operationId": "x",
                    "parameters": [{"$ref": "#/components/parameters/Missing"}],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc);
        match spec {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("unresolvable $ref"),
                    "message was: {message}"
                );
                assert!(message.contains("get /x"), "message was: {message}");
            }
            Ok(_) => panic!("expected unresolvable-$ref error, spec parsed happily"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn self_referential_ref_errors_instead_of_aborting() {
        let spec = schema_test_spec(json!({
            "Node": {
                "type": "object",
                "properties": {
                    "next": {"$ref": "#/components/schemas/Node"}
                }
            }
        }));
        let schema = spec
            .components
            .as_ref()
            .and_then(|c| c.schemas.get("Node"))
            .expect("test spec has Node")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("circular $ref"), "message was: {message}");
                assert!(message.contains("Node"), "message was: {message}");
            }
            other => panic!("expected circular-$ref SchemaParse error, got {other:?}"),
        }
    }

    #[test]
    fn mutually_recursive_refs_error_on_cycle() {
        let spec = schema_test_spec(json!({
            "A": {"properties": {"b": {"$ref": "#/components/schemas/B"}}},
            "B": {"properties": {"a": {"$ref": "#/components/schemas/A"}}}
        }));
        let schema = spec
            .components
            .as_ref()
            .and_then(|c| c.schemas.get("A"))
            .expect("test spec has A")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        assert!(matches!(result, Err(AdapterError::SchemaParse { .. })));
    }

    #[test]
    fn over_deep_non_circular_spec_errors_cleanly() {
        let depth = MAX_REF_RESOLUTION_DEPTH * 4;
        let spec = schema_test_spec(json!({"Deep": nested_object(depth)}));
        let schema = spec
            .components
            .as_ref()
            .and_then(|c| c.schemas.get("Deep"))
            .expect("test spec has Deep")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("depth budget"), "message was: {message}");
            }
            other => panic!("expected depth-budget SchemaParse error, got {other:?}"),
        }
    }

    #[test]
    fn shared_refs_to_common_schema_import_identically() {
        let spec = schema_test_spec(json!({
            "Money": {"type": "object", "properties": {"amount": {"type": "number"}}},
            "Order": {
                "type": "object",
                "properties": {"total": {"$ref": "#/components/schemas/Money"}}
            },
            "Refund": {
                "type": "object",
                "properties": {"amount": {"$ref": "#/components/schemas/Money"}}
            }
        }));
        let schemas = &spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas;
        for name in ["Order", "Refund"] {
            let schema = schemas.get(name).expect("test schema present").clone();
            let resolved = spec
                .resolve_refs_recursive(&schema)
                .expect("no false cycle");
            let money = &resolved["properties"][if name == "Order" { "total" } else { "amount" }];
            assert_eq!(money["type"], "object");
            assert_eq!(money["properties"]["amount"]["type"], "number");
        }
    }

    #[test]
    fn diamond_ref_reuse_within_one_schema_does_not_trip_cycle_guard() {
        let spec = schema_test_spec(json!({
            "Id": {"type": "string"},
            "Wrapper": {
                "type": "object",
                "properties": {
                    "a": {"$ref": "#/components/schemas/Id"},
                    "b": {"$ref": "#/components/schemas/Id"}
                }
            }
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Wrapper")
            .expect("test schema present")
            .clone();
        let resolved = spec
            .resolve_refs_recursive(&schema)
            .expect("no false cycle");
        assert_eq!(resolved["properties"]["a"]["type"], "string");
    }

    #[test]
    fn thirty_level_shared_chain_returns_bounded_with_clean_budget_error() {
        let levels = 32usize;
        let mut components = serde_json::Map::new();
        for i in 0..levels {
            let next_ref = if i + 1 < levels {
                json!({"$ref": format!("#/components/schemas/S{}", i + 1)})
            } else {
                json!({"type": "string"})
            };
            components.insert(
                format!("S{i}"),
                json!({"a": next_ref.clone(), "b": next_ref}),
            );
        }
        let spec = schema_test_spec(Value::Object(components));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("S0")
            .expect("test schema present")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("node budget"), "message was: {message}");
            }
            other => panic!("expected node-budget SchemaParse error, got {other:?}"),
        }
    }

    #[test]
    fn forty_level_single_chain_imports_fast_under_memoization() {
        let levels = 40usize;
        let mut components = serde_json::Map::new();
        for i in 0..levels {
            let next = if i + 1 < levels {
                json!({"$ref": format!("#/components/schemas/S{}", i + 1)})
            } else {
                json!({"type": "string"})
            };
            components.insert(format!("S{i}"), json!({"next": next}));
        }
        let spec = schema_test_spec(Value::Object(components));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("S0")
            .expect("test schema present")
            .clone();
        let resolved = spec
            .resolve_refs_recursive(&schema)
            .expect("acyclic chain resolves");
        let mut cursor = &resolved;
        for _ in 1..=levels {
            cursor = &cursor["next"];
        }
        assert_eq!(cursor["type"], "string", "innermost level fully expanded");
    }

    #[test]
    fn memoized_expansion_matches_pre_memoization_golden() {
        let spec = schema_test_spec(json!({
            "Id": {"type": "string", "maxLength": 4},
            "Stamp": {"type": "object", "required": ["at"]},
            "Chain": {
                "type": "object",
                "properties": {
                    "id": {"$ref": "#/components/schemas/Id"},
                    "next": {
                        "type": "object",
                        "properties": {
                            "id": {"$ref": "#/components/schemas/Id"},
                            "stamp": {"$ref": "#/components/schemas/Stamp"},
                            "again": {"$ref": "#/components/schemas/Id"}
                        }
                    },
                    "stamp": {"$ref": "#/components/schemas/Stamp"}
                }
            }
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Chain")
            .expect("test schema present")
            .clone();
        let resolved = spec
            .resolve_refs_recursive(&schema)
            .expect("expansion succeeds");
        let expected = json!({
            "type": "object",
            "properties": {
                "id": {"type": "string", "maxLength": 4},
                "next": {
                    "type": "object",
                    "properties": {
                        "id": {"type": "string", "maxLength": 4},
                        "stamp": {"type": "object", "required": ["at"]},
                        "again": {"type": "string", "maxLength": 4}
                    }
                },
                "stamp": {"type": "object", "required": ["at"]}
            }
        });
        assert_eq!(resolved, expected);
    }

    #[test]
    fn cycle_through_shared_node_still_errors() {
        let spec = schema_test_spec(json!({
            "Shared": {"properties": {
                "back": {"$ref": "#/components/schemas/Loop"}
            }},
            "Loop": {"properties": {
                "shared": {"$ref": "#/components/schemas/Shared"}
            }}
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Loop")
            .expect("test schema present")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("circular $ref"), "message was: {message}");
            }
            other => panic!("expected circular-$ref SchemaParse error, got {other:?}"),
        }
    }

    #[test]
    fn cycle_via_array_items_errors() {
        let spec = schema_test_spec(json!({
            "Node": {"type": "array", "items": {"$ref": "#/components/schemas/Node"}}
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Node")
            .expect("test schema present")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("circular $ref"), "message was: {message}");
                assert!(message.contains("Node"), "message was: {message}");
            }
            other => panic!("expected circular-$ref SchemaParse error, got {other:?}"),
        }
    }

    #[test]
    fn array_of_ref_resolves_each_item() {
        // The array branch of `resolve_refs_bounded` (the arm a coverage
        // pass initially mis-flagged): `$ref`s inside `items` resolve to
        // the component schema, not pass through verbatim.
        let spec = schema_test_spec(json!({
            "Tag": {"type": "string", "minLength": 1},
            "Tags": {"type": "array", "items": {"$ref": "#/components/schemas/Tag"}}
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Tags")
            .expect("test schema present")
            .clone();
        let resolved = spec
            .resolve_refs_recursive(&schema)
            .expect("array-of-$ref is acyclic and must resolve");
        assert_eq!(resolved["type"], "array");
        assert_eq!(
            resolved["items"],
            serde_json::json!({"type": "string", "minLength": 1}),
            "the items $ref must expand to the Tag component schema"
        );
        let resolved_twice = spec
            .resolve_refs_recursive(&schema)
            .expect("second resolution hits the memo");
        assert_eq!(resolved, resolved_twice);
    }

    #[test]
    fn cycle_via_all_of_errors() {
        let spec = schema_test_spec(json!({
            "Node": {"allOf": [{"$ref": "#/components/schemas/Node"}]}
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Node")
            .expect("test schema present")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("circular $ref"), "message was: {message}");
                assert!(message.contains("Node"), "message was: {message}");
            }
            other => panic!("expected circular-$ref SchemaParse error, got {other:?}"),
        }
    }

    #[test]
    fn cycle_via_additional_properties_errors() {
        let spec = schema_test_spec(json!({
            "Node": {"type": "object", "additionalProperties": {
                "$ref": "#/components/schemas/Node"
            }}
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Node")
            .expect("test schema present")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("circular $ref"), "message was: {message}");
                assert!(message.contains("Node"), "message was: {message}");
            }
            other => panic!("expected circular-$ref SchemaParse error, got {other:?}"),
        }
    }

    #[test]
    fn cycle_via_ref_sibling_errors() {
        let spec = schema_test_spec(json!({
            "Node": {
                "$ref": "#/components/schemas/Node",
                "minLength": 3
            }
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Node")
            .expect("test schema present")
            .clone();
        let result = spec.resolve_refs_recursive(&schema);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("circular $ref"), "message was: {message}");
                assert!(message.contains("Node"), "message was: {message}");
            }
            other => panic!("expected circular-$ref SchemaParse error, got {other:?}"),
        }
    }

    #[test]
    fn memo_hit_matches_fresh_expansion_for_acyclic_shared_refs() {
        let spec = schema_test_spec(json!({
            "Id": {"type": "string", "maxLength": 4},
            "Wrapper": {
                "type": "object",
                "properties": {
                    "a": {"$ref": "#/components/schemas/Id"},
                    "b": {"$ref": "#/components/schemas/Id"}
                }
            }
        }));
        let schema = spec
            .components
            .as_ref()
            .expect("test spec has schemas")
            .schemas
            .get("Wrapper")
            .expect("test schema present")
            .clone();
        let resolved = spec
            .resolve_refs_recursive(&schema)
            .expect("no false cycle");
        assert_eq!(resolved["properties"]["a"], resolved["properties"]["b"]);
        assert_eq!(resolved["properties"]["a"]["type"], "string");
        assert_eq!(resolved["properties"]["a"]["maxLength"], 4);
    }

    #[test]
    fn import_of_self_referential_spec_returns_error_not_abort() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "components": {"schemas": {
                "Node": {
                    "type": "object",
                    "properties": {"next": {"$ref": "#/components/schemas/Node"}}
                }
            }},
            "paths": {
                "/nodes": {"get": {"operationId": "listNodes", "responses": {
                    "200": {"content": {"application/json": {
                        "schema": {"$ref": "#/components/schemas/Node"}
                    }}}
                }}}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).unwrap();
        let client = SharedHttpClient::new(HttpClientConfig::default()).unwrap();
        let adapter = FromOpenAPI::new(
            spec,
            HttpServiceConfig {
                namespace: "svc".to_string(),
                base_url: "https://x".to_string(),
                auth: None,
                default_headers: HashMap::new(),
            },
            Arc::new(client),
        );
        let result = adapter.import();
        match futures::executor::block_on(result) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("circular $ref"), "message was: {message}");
            }
            Ok(bundles) => panic!(
                "expected import error for recursive spec, got {} bundles",
                bundles.len()
            ),
            Err(e) => panic!("expected circular-$ref SchemaParse, got {e}"),
        }
    }

    // --- OAI-06: loud unsupported-feature handling --------------------------

    #[test]
    fn non_default_style_parameter_fails_import_naming_the_feature() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/tags": {"get": {
                    "operationId": "listTags",
                    "parameters": [{
                        "name": "ids",
                        "in": "query",
                        "style": "spaceDelimited",
                        "schema": {"type": "array", "items": {"type": "integer"}}
                    }],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let result = OpenAPISpec::from_json(doc);
        match result {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("ids"), "message was: {message}");
                assert!(
                    message.contains("spaceDelimited"),
                    "the error must name the offending style: {message}"
                );
                assert!(message.contains("OAI-06"), "message was: {message}");
            }
            Ok(_) => panic!("non-default style must fail import loudly, got a spec"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn deep_object_style_is_rejected_like_the_other_non_default_forms() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/f": {"get": {
                    "operationId": "f",
                    "parameters": [{
                        "name": "filter",
                        "in": "query",
                        "style": "deepObject",
                        "schema": {"type": "object"}
                    }],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let result = OpenAPISpec::from_json(doc);
        assert!(matches!(result, Err(AdapterError::SchemaParse { .. })));
    }

    #[test]
    fn form_style_with_explode_false_is_rejected() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/ids": {"get": {
                    "operationId": "ids",
                    "parameters": [{
                        "name": "ids",
                        "in": "query",
                        "style": "form",
                        "explode": false,
                        "schema": {"type": "array", "items": {"type": "integer"}}
                    }],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("explode") && message.contains("form"),
                    "the error must name the form+explode conflict: {message}"
                );
                assert!(message.contains("ids"), "message was: {message}");
            }
            Ok(_) => panic!("form+explode=false mis-serializes arrays; must fail loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn simple_style_with_explode_true_is_rejected() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/f": {"get": {
                    "operationId": "f",
                    "parameters": [{
                        "name": "X-Id",
                        "in": "header",
                        "style": "simple",
                        "explode": true,
                        "schema": {"type": "string"}
                    }],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("simple") && message.contains("explode"),
                    "the error must name the simple+explode conflict: {message}"
                );
                assert!(message.contains("X-Id"), "message was: {message}");
                assert!(message.contains("OAI-06"), "message was: {message}");
            }
            Ok(_) => panic!("simple+explode=true has no wire meaning here; must fail loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn default_style_and_explode_forms_still_import() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/x": {"get": {
                    "operationId": "x",
                    "parameters": [
                        {"name": "q", "in": "query", "style": "form", "explode": true, "schema": {"type": "string"}},
                        {"name": "X-Trace", "in": "header", "style": "simple", "explode": false, "schema": {"type": "string"}}
                    ],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).expect("default style declarations import");
        let op = &spec.paths["/x"].operations[0].1;
        assert_eq!(op.parameters.len(), 2);
    }

    #[test]
    fn servers_override_at_document_level_fails_import() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "servers": [{"url": "https://api.example.com"}],
            "paths": {
                "/x": {"get": {"operationId": "x", "responses": {
                    "200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("servers"), "message was: {message}");
                assert!(message.contains("base_url"), "message was: {message}");
                assert!(message.contains("document"), "message was: {message}");
                assert!(message.contains("OAI-06"), "message was: {message}");
            }
            Ok(_) => panic!("document-level servers must fail import loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn servers_override_at_path_and_operation_level_fails_import() {
        let path_level = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/x": {
                    "servers": [{"url": "https://other.example.com"}],
                    "get": {"operationId": "x", "responses": {
                        "200": {"content": {"application/json": {"schema": {}}}}}
                    }
                }
            }
        }"##;
        match OpenAPISpec::from_json(path_level) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("path /x"), "message was: {message}");
            }
            Ok(_) => panic!("path-level servers must fail import loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }

        let op_level = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/y": {"get": {
                    "operationId": "y",
                    "servers": [{"url": "https://other.example.com"}],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        match OpenAPISpec::from_json(op_level) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("get /y"),
                    "the error must locate the operation-level override: {message}"
                );
            }
            Ok(_) => panic!("operation-level servers must fail import loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn servers_absent_baseline_still_imports() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/x": {"get": {"operationId": "x", "responses": {
                    "200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).expect("no servers means no conflict");
        assert_eq!(spec.paths.len(), 1);
    }

    #[test]
    fn trace_only_path_is_skipped_and_documented_inert() {
        // `trace` is not a supported method (openapi_spec::HTTP_METHODS);
        // a path carrying only `trace` is skipped — visibly, via the
        // module's warn log — and the rest of the document imports.
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/debug": {"trace": {"operationId": "debug", "responses": {
                    "200": {"content": {"application/json": {"schema": {}}}}}
                }},
                "/x": {"get": {"operationId": "x", "responses": {
                    "200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).expect("trace skip is not an error");
        assert!(
            !spec.paths.contains_key("/debug"),
            "the trace-only path is not imported"
        );
        assert!(
            spec.paths.contains_key("/x"),
            "the supported path still imports alongside the skipped one"
        );
    }

    // --- OAI-10: $ref sibling keys -------------------------------------------

    #[test]
    fn ref_sibling_keys_import_with_3_0_reading_and_warn() {
        let doc = r##"{
            "openapi": "3.0.3",
            "info": {"title": "T", "version": "1"},
            "components": {"parameters": {
                "Id": {"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}
            }},
            "paths": {
                "/users/{id}": {"get": {
                    "operationId": "getUser",
                    "parameters": [
                        {"$ref": "#/components/parameters/Id", "description": "the user id", "deprecated": false}
                    ],
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).expect("sibling keys do not fail the import");
        let item = spec.paths.get("/users/{id}").expect("path present");
        let param = &item.operations[0].1.parameters[0];
        assert_eq!(param.name, "id", "the resolved 3.0 reading wins");
        assert_eq!(
            param.in_, "path",
            "the resolved target's fields are what imports"
        );
    }

    // --- OAI-14: top-level ignored blocks ------------------------------------

    #[test]
    fn callbacks_at_operation_level_fail_import_naming_the_feature() {
        let doc = r#"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/orders": {"post": {
                    "operationId": "createOrder",
                    "callbacks": {
                        "orderEvent": {"{$request.body#/callbackUrl}": {"post": {
                            "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                        }}}
                    },
                    "responses": {"201": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"#;
        run_import_expect_oai14(doc, "callbacks", "post /orders");
    }

    #[test]
    fn security_requirements_fail_import_naming_the_remediation() {
        let doc_level = r#"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "security": [{"bearerAuth": []}],
            "paths": {"/x": {"get": {"operationId": "x", "responses": {
                "200": {"content": {"application/json": {"schema": {}}}}}
            }}}}
        "#;
        run_import_expect_oai14(doc_level, "security", "document");

        let op_level = r#"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {"/y": {"get": {
                "operationId": "y",
                "security": [{"apiKey": []}],
                "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
            }}}}
        "#;
        run_import_expect_oai14(op_level, "security", "get /y");
    }

    #[test]
    fn top_level_oneof_request_body_fails_import_naming_the_feature() {
        let doc = r#"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/x": {"post": {
                    "operationId": "x",
                    "requestBody": {
                        "oneOf": [
                            {"content": {"application/json": {"schema": {"type": "object"}}}},
                            {"content": {"text/plain": {"schema": {"type": "string"}}}}
                        ]
                    },
                    "responses": {"201": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"#;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("requestBody") && message.contains("unresolvable"),
                    "the oneOf body (no content map) fails via the OAI-15 arm: {message}"
                );
                assert!(message.contains("OAI-15"), "message was: {message}");
            }
            Ok(_) => panic!("top-level oneOf requestBody must fail import loudly (OAI-14/15)"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    fn run_import_expect_oai14(doc: &str, feature: &str, location: &str) {
        let spec = OpenAPISpec::from_json(doc).expect("structural parse passes");
        let client = SharedHttpClient::new(HttpClientConfig::default()).expect("client");
        let adapter = FromOpenAPI::new(
            spec,
            HttpServiceConfig {
                namespace: "svc".to_string(),
                base_url: "https://x".to_string(),
                auth: None,
                default_headers: HashMap::new(),
            },
            Arc::new(client),
        );
        match futures::executor::block_on(adapter.import()) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains(feature),
                    "the error must name {feature}: {message}"
                );
                assert!(
                    message.contains(location),
                    "the error must locate {location}: {message}"
                );
                assert!(message.contains("OAI-14"), "message was: {message}");
            }
            Ok(bundles) => panic!(
                "{feature} at {location} must fail import loudly (OAI-14), got {} bundles",
                bundles.len()
            ),
            Err(e) => panic!("expected SchemaParse, got {e}"),
        }
    }

    // --- OAI-17: bounded import error messages -------------------------------

    #[test]
    fn hundred_thousand_servers_overrides_produce_bounded_error_message() {
        let mut paths = String::from("{");
        for i in 0..100_000 {
            let entry = r#""/p0": {"servers": [{"url": "https://h.example.com"}], "get": {"operationId": "op0", "responses": {"200": {"content": {"application/json": {"schema": {}}}}}}},"#
                .replace("p0", &format!("p{i}"))
                .replace("h.example.com", &format!("h{i}.example.com"))
                .replace("op0", &format!("op{i}"));
            paths.push_str(&entry);
        }
        paths.push_str(r#""/final": {"servers": [{"url": "https://z.example.com"}]}}"#);
        let doc = format!(
            r#"{{"openapi": "3.0.0", "info": {{"title": "T", "version": "1"}}, "paths": {paths}}}"#
        );
        let started = std::time::Instant::now();
        match OpenAPISpec::from_json(&doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.len() < 4096,
                    "servers error must stay bounded (OAI-17), got {} bytes",
                    message.len()
                );
                assert!(
                    message.contains('+') && message.contains("more"),
                    "the bounded join must name the suppressed count: {message}"
                );
            }
            Ok(_) => panic!("100k servers overrides must fail import"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
        assert!(
            started.elapsed().as_secs() < 30,
            "the fixtures stay linear/bounded; this took {:?}",
            started.elapsed()
        );
    }

    #[test]
    fn bounded_join_truncates_both_count_and_width() {
        let many: Vec<String> = (0..50).map(|i| format!("item{i}")).collect();
        let joined = bounded_join(&many);
        assert!(
            joined.contains("item0") && joined.contains("item7"),
            "first 8 shown: {joined}"
        );
        assert!(!joined.contains("item8,"), "9th item suppressed: {joined}");
        assert!(joined.contains("+42 more"), "count named: {joined}");

        let wide = vec!["x".repeat(500)];
        let joined = bounded_join(&wide);
        assert!(
            joined.len() < 200,
            "each item truncated to the width cap: {} bytes",
            joined.len()
        );
        assert!(joined.ends_with('…'), "truncation marker: {joined}");

        let small = vec!["a".to_string(), "b".to_string()];
        assert_eq!(bounded_join(&small), "a, b", "under cap is unchanged");
    }

    // --- OAI-12: YAML input normalization -----------------------------------

    const OAI12_HEADER: &str = r#"
openapi: 3.0.0
info:
  title: T
  version: "1"
"#;

    #[test]
    fn from_yaml_duplicate_keys_fail_loudly_not_last_win() {
        let doc = r#"
openapi: 3.0.0
info:
  title: T
  version: "1"
  description: first
  description: second
paths:
  /x:
    get:
      operationId: x
      responses:
        "200":
          content:
            application/json:
              schema: {}
"#;
        match OpenAPISpec::from_yaml(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("duplicate"),
                    "the error must name the duplicate: {message}"
                );
                assert!(
                    message.contains("line") || message.contains("column"),
                    "the error must carry the document position: {message}"
                );
            }
            Ok(_) => panic!("duplicate YAML keys must fail loudly, not last-win"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn from_yaml_duplicate_keys_stricter_than_json_path() {
        let dup_json = r#"{"a":1,"a":2}"#;
        let json_last_wins = serde_json::from_str::<Value>(dup_json)
            .expect("serde_json's visit_map last-wins (verified against 1.0.151)");
        assert_eq!(
            json_last_wins["a"], 2,
            "the JSON path silently last-wins; this assertion documents the asymmetry \
             the YAML path refuses to reproduce"
        );
        let yaml_doc = "a: 1\na: 2";
        match OpenAPISpec::from_yaml(yaml_doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("duplicate"), "message was: {message}");
            }
            Ok(_) => panic!("YAML duplicate keys must fail loudly, not last-win"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn from_yaml_inf_maximum_fails_loudly_not_silent_null() {
        let doc = format!(
            r#"{OAI12_HEADER}
components:
  schemas:
    Price:
      type: object
      properties:
        cap:
          type: number
          maximum: .inf
"#
        );
        match OpenAPISpec::from_yaml(&doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains(".inf") || message.contains("inf"),
                    "the error must name the non-finite value: {message}"
                );
                assert!(
                    message.contains("maximum") || message.contains("schemas"),
                    "the error must carry the value's JSON pointer: {message}"
                );
            }
            Ok(spec) => {
                let maximum =
                    &spec.raw["components"]["schemas"]["Price"]["properties"]["cap"]["maximum"];
                assert_ne!(
                    *maximum,
                    Value::Null,
                    "maximum: .inf silently nulled — the corruption OAI-12 fixes"
                );
                panic!("non-finite float must fail loudly, not null");
            }
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn from_yaml_nan_value_fails_loudly() {
        let doc = format!(
            r#"{OAI12_HEADER}
components:
  schemas:
    Ratio:
      type: object
      properties:
        value:
          type: number
          example: .nan
"#
        );
        match OpenAPISpec::from_yaml(&doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains(".nan") || message.contains("NaN"),
                    "the error must name the non-finite value: {message}"
                );
            }
            Ok(_) => panic!(".nan must fail loudly, not null"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn from_yaml_merge_key_is_applied_not_advertised() {
        let doc = r#"
openapi: 3.0.0
info:
  title: T
  version: "1"
components:
  schemas:
    Base: &Base
      type: object
      required: [id]
      properties:
        id:
          type: string
    Widget:
      <<: *Base
      title: Widget
paths:
  /x:
    get:
      operationId: x
      responses:
        "200":
          content:
            application/json:
              schema: {}
"#;
        let spec = OpenAPISpec::from_yaml(doc).expect("merge keys apply");
        let widget = &spec.raw["components"]["schemas"]["Widget"];
        assert!(
            widget.get("<<").is_none(),
            "<< must never survive as a literal property"
        );
        assert_eq!(widget["type"], "object", "merged from Base");
        let required = widget["required"].as_array().expect("required merged");
        assert_eq!(required[0], "id");
        let props = widget["properties"].as_object().expect("props merged");
        assert_eq!(props["id"]["type"], "string", "base properties merged in");
        assert_eq!(
            widget["title"], "Widget",
            "the referencing mapping's own keys are kept"
        );
    }

    #[test]
    fn from_yaml_merge_key_local_override_wins_over_base() {
        let doc = format!(
            r#"{OAI12_HEADER}
components:
  schemas:
    Base: &Base
      type: object
      description: base description
      properties:
        id:
          type: string
    Widget:
      <<: *Base
      description: widget description
paths: {{}}
"#
        );
        let spec = OpenAPISpec::from_yaml(&doc).expect("merge keys apply");
        let widget = &spec.raw["components"]["schemas"]["Widget"];
        assert_eq!(widget["description"], "widget description");
        assert_eq!(
            widget["type"], "object",
            "keys the referencing mapping does not declare come from the merge"
        );
    }

    #[test]
    fn from_yaml_scalar_merge_value_fails_loudly() {
        let doc = format!(
            r#"{OAI12_HEADER}
components:
  schemas:
    Broken:
      <<: 5
paths: {{}}
"#
        );
        match OpenAPISpec::from_yaml(&doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("merge"),
                    "the error must name the merge-key failure: {message}"
                );
            }
            Ok(_) => panic!("`<<:` with a scalar value must fail loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn from_yaml_quoted_status_keys_survive_unchanged() {
        let doc = r#"
openapi: 3.0.0
info:
  title: T
  version: "1"
paths:
  /x:
    get:
      operationId: x
      responses:
        "200":
          description: ok
          content:
            application/json:
              schema: {}
        "404":
          description: missing
"#;
        let spec = OpenAPISpec::from_yaml(doc).expect("quoted keys unchanged");
        let responses = &spec.paths["/x"].operations[0].1.responses;
        assert!(responses.contains_key("200"));
        assert!(responses.contains_key("404"));
        assert_eq!(
            &spec.raw["paths"]["/x"]["get"]["responses"]["200"]["description"],
            "ok"
        );
    }

    #[test]
    fn from_yaml_unquoted_status_keys_match_json_path_shape() {
        let doc = format!(
            r#"{OAI12_HEADER}
paths:
  /x:
    get:
      operationId: x
      responses:
        200:
          description: ok
        404:
          description: missing
"#
        );
        let spec = OpenAPISpec::from_yaml(&doc).expect("bare numeric keys round-trip");
        let responses = &spec.paths["/x"].operations[0].1.responses;
        assert!(
            responses.contains_key("200") && responses.contains_key("404"),
            "unquoted response codes must mean the same thing as quoted/JSON ones"
        );
    }

    #[test]
    fn from_yaml_null_and_collection_keys_fail_loudly() {
        let doc = "~: 1";
        match OpenAPISpec::from_yaml(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("no string form") || message.contains("key"),
                    "the error must name the unusable key: {message}"
                );
            }
            Ok(_) => panic!("null mapping key must fail loudly, not stringily as \"~\""),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn from_yaml_float_key_preserves_rendering() {
        let doc = format!(
            r#"{OAI12_HEADER}
components:
  schemas:
    Mapped:
      type: object
      additionalProperties:
        type: string
      x-key-map:
        1.5: one-point-five
paths: {{}}
"#
        );
        let spec = OpenAPISpec::from_yaml(&doc).expect("finite float key stringifies");
        let key_map = &spec.raw["components"]["schemas"]["Mapped"]["x-key-map"];
        assert_eq!(key_map["1.5"], "one-point-five");
    }

    #[test]
    fn from_yaml_bool_key_stringifies() {
        let doc = format!(
            r#"{OAI12_HEADER}
components:
  schemas:
    Mapped:
      type: object
      x-flags:
        true: enabled
paths: {{}}
"#
        );
        let spec = OpenAPISpec::from_yaml(&doc).expect("bool key stringifies");
        assert_eq!(
            &spec.raw["components"]["schemas"]["Mapped"]["x-flags"]["true"],
            "enabled"
        );
    }

    #[test]
    fn from_yaml_plain_scalars_unaffected_by_normalization() {
        let doc = format!(
            r#"{OAI12_HEADER}
components:
  schemas:
    All:
      type: object
      properties:
        yes:
          type: string
          default: yes
        n:
          type: integer
          maximum: 9007199254740993
        f:
          type: number
          example: 1.5
        s:
          type: string
          example: "200"
paths: {{}}
"#
        );
        let spec = OpenAPISpec::from_yaml(&doc).expect("normal doc unaffected");
        let props = &spec.raw["components"]["schemas"]["All"]["properties"];
        assert_eq!(props["yes"]["default"], "yes");
        assert_eq!(
            props["n"]["maximum"], 9007199254740993i64,
            "i64 range survives exactly"
        );
        assert_eq!(props["f"]["example"], 1.5);
        assert_eq!(props["s"]["example"], "200");
    }

    #[test]
    fn from_yaml_untagged_bare_scalars_still_round_trip() {
        let doc = format!(
            r#"{OAI12_HEADER}
components:
  schemas:
    T:
      type: object
      properties:
        a:
          type: string
          default: !!str 200
paths: {{}}
"#
        );
        let spec = OpenAPISpec::from_yaml(&doc).expect("tagged scalar passes through");
        let props = &spec.raw["components"]["schemas"]["T"]["properties"];
        assert_eq!(props["a"]["default"], "200");
    }

    // --- OAI-13: path-item parameters, response wildcards, webhooks ---

    #[test]
    fn path_item_parameters_merge_into_operations() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/users/{id}/posts": {
                    "parameters": [
                        {"name": "id", "in": "path", "required": true,
                         "schema": {"type": "string", "pattern": "^u-"}},
                        {"name": "verbose", "in": "query", "schema": {"type": "boolean"}}
                    ],
                    "get": {
                        "operationId": "listPosts",
                        "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                    },
                    "post": {
                        "operationId": "createPost",
                        "requestBody": {"content": {"application/json": {"schema": {}}}},
                        "responses": {"201": {"content": {"application/json": {"schema": {}}}}}
                    }
                }
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).expect("shared path-item params import");
        let item = spec.paths.get("/users/{id}/posts").expect("path present");
        assert_eq!(item.parameters.len(), 2, "path-item params retained");
        assert_eq!(item.parameters[0].name, "id");
        assert_eq!(item.parameters[0].in_, "path");
        assert!(item.parameters[0].required);
        assert_eq!(item.operations.len(), 2);
    }

    #[test]
    fn path_item_parameter_refs_to_components_resolve() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "components": {
                "parameters": {
                    "Id": {"name": "id", "in": "path", "required": true,
                           "schema": {"type": "string"}}
                }
            },
            "paths": {
                "/users/{id}": {
                    "parameters": [{"$ref": "#/components/parameters/Id"}],
                    "get": {
                        "operationId": "getUser",
                        "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                    }
                }
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).expect("ref'd path-item params import");
        let item = spec.paths.get("/users/{id}").expect("path present");
        assert_eq!(item.parameters.len(), 1);
        assert_eq!(item.parameters[0].name, "id");
    }

    #[test]
    fn path_item_parameter_missing_in_fails_import_naming_the_cause() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/users/{id}": {
                    "parameters": [{"name": "id", "schema": {"type": "string"}}],
                    "get": {
                        "operationId": "getUser",
                        "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                    }
                }
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(
                    message.contains("path-item parameter"),
                    "the error must name the path-item parameter level: {message}"
                );
                assert!(message.contains("id"), "message was: {message}");
            }
            Ok(_) => panic!("path-item parameter missing `in` must fail loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn path_item_parameter_style_gate_applies() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/tags": {
                    "parameters": [{
                        "name": "ids", "in": "query", "style": "deepObject",
                        "schema": {"type": "object"}
                    }],
                    "get": {
                        "operationId": "listTags",
                        "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                    }
                }
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("deepObject"), "message was: {message}");
                assert!(message.contains("OAI-06"), "message was: {message}");
            }
            Ok(_) => panic!("path-item non-default style must fail loudly"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn webhooks_mixed_document_fails_import_naming_the_feature() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "webhooks": {
                "newPet": {"post": {
                    "operationId": "newPet",
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            },
            "paths": {
                "/pets": {"get": {
                    "operationId": "listPets",
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        match OpenAPISpec::from_json(doc) {
            Err(AdapterError::SchemaParse { message }) => {
                assert!(message.contains("webhooks"), "message was: {message}");
                assert!(message.contains("OAI-13"), "message was: {message}");
            }
            Ok(_) => panic!("mixed webhooks+paths doc must fail loudly (OAI-13)"),
            other => panic!("expected SchemaParse, got {other:?}"),
        }
    }

    #[test]
    fn webhooks_missing_document_still_imports() {
        let doc = r##"{
            "openapi": "3.0.0",
            "info": {"title": "T", "version": "1"},
            "paths": {
                "/pets": {"get": {
                    "operationId": "listPets",
                    "responses": {"200": {"content": {"application/json": {"schema": {}}}}}
                }}
            }
        }"##;
        let spec = OpenAPISpec::from_json(doc).expect("no webhooks key is the normal case");
        assert_eq!(spec.paths.len(), 1);
    }
}