hf2q 0.1.1

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
//! Per-model boundary-marker + tool-call registration (ADR-005 Decision #21,
//! Decision #6).
//!
//! Each supported model family registers the literal text markers its chat
//! template emits for:
//!   - **Reasoning boundaries** — open/close marker pair that delimits
//!     pre-answer reasoning traces. Tokens between the open and close markers
//!     go into `message.reasoning_content`; the rest goes into
//!     `message.content`. Streaming splits into `delta.reasoning_content`
//!     vs `delta.content` the same way. Per-family marker shapes vary:
//!     Qwen 3.5/3.6 emits the standard `<think>` / `</think>` HF convention;
//!     Gemma 4 emits its `<|channel>` / `<channel|>` channel-block convention
//!     (matches the chat-template `strip_thinking` macro and the
//!     tokenizer_config `x-regex` that spans `<|channel>thought\n…<channel|>`).
//!   - **Tool-call boundaries** — markers delimiting a grammar-constrained
//!     JSON tool-call fragment. Applied by the engine in a later iter when
//!     the grammar sampler is wired into the decode loop.
//!
//! Per ADR-005 Phase 2 refinement (2026-04-23), this is **registration, not
//! parsing**: the open/close markers drive a lightweight state machine over
//! the accumulated decoded text; they don't mine partial JSON out of
//! malformed output. Grammar-constrained decoding (Decision #6) guarantees
//! the JSON is well-formed between the markers.
//!
//! Day-one registered models: `gemma4`, `qwen35` (Qwen 3.5 / 3.6 family).
//! Additional models are added by calling `register(...)` at process start
//! or by editing this file.
//!
//! # Per-model wrapper grammar (ADR-005 Phase 2a T1.8 Option B, Wave 2 W-4)
//!
//! `ModelRegistration::tool_call_gbnf` emits a GBNF string that physically
//! constrains the model to emit a valid wrapper + valid arguments for the
//! named function. The caller (handlers.rs `compile_tool_grammar`) parses the
//! GBNF string with `grammar::parser::parse` and attaches the result to
//! `SamplingParams.grammar`.
//!
//! WHY per-model wrapper grammars instead of plain JSON:
//!   - **Gemma 4** — the chat template's `tool_call` macro emits
//!     `call:NAME{key:<|"|>val<|"|>,...}`, NOT JSON. The `<|"|>` string-quote
//!     markers are Gemma-specific (see `models/gemma4/chat_template.jinja:113`).
//!     If the grammar constrained plain `{"key":"val"}` the model would fight
//!     the constraint and produce degenerate outputs; the constraint must match
//!     the template's expected emission exactly.
//!   - **Qwen 3.5/3.6** — the chat template's tool-call block emits
//!     `<function=NAME><parameter=key>val</parameter>...</function>` XML.
//!     Same reason: the constraint must match the template's emission shape.
//!   - Plain JSON constraints (via json_schema::schema_to_gbnf) are correct
//!     for `response_format=json_schema` where no per-model wrapper exists.
//!     Tool-call wrappers are necessarily per-model, and their inner value
//!     grammar must mirror the wrapper's own quoting convention (Gemma uses
//!     `<|"|>` string markers; Qwen XML wraps raw values).

use std::collections::HashMap;
use std::sync::OnceLock;

/// Boundary markers + optional preamble string for a single model family.
///
/// ~15-30 LOC per model per ADR-005 Decision #21's target. Co-located with
/// chat-template entries conceptually; each field is independently optional
/// so models that don't emit reasoning traces (most base models) can leave
/// them as `None`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelRegistration {
    /// Opaque identifier for the model family. Matching is done against a
    /// prefix of the request's `model` id — e.g. an id like
    /// `gemma-4-26B-A4B-it-ara-abliterated-dwq` matches the `gemma4`
    /// registration via the `matches` function below.
    pub family: &'static str,

    /// Comma-separated substrings of the model id. Any match on a
    /// case-insensitive substring scan selects this registration. This is
    /// deliberately fuzzy — the set of exact model ids is unbounded, while
    /// the family identifier in ids (`gemma4`, `qwen3.5`, etc.) is stable.
    pub id_substrings: &'static [&'static str],

    /// Opening marker for a reasoning span. `None` = this model doesn't
    /// emit reasoning traces.
    pub reasoning_open: Option<&'static str>,
    /// Closing marker for a reasoning span. `None` = no reasoning.
    pub reasoning_close: Option<&'static str>,

    /// Opening marker for a tool-call block. `None` = no tool calls.
    ///
    /// # Marker-shape contract (ADR-005 Wave-2.5 D1 — Option B architecture)
    ///
    /// `tool_open` and `tool_close` MUST be byte sequences that the
    /// tokenizer's **special tokens** decode to.  They are NOT arbitrary
    /// strings — the engine feeds raw decoded bytes to `ToolCallSplitter`,
    /// which scans for these exact byte sequences to detect the open/close
    /// boundary.  If a marker string is set to something the tokenizer never
    /// emits as a special-token sequence, the splitter will never fire.
    ///
    /// Authoritative references:
    /// - **Gemma 4**: `tokenizer_config.json` declares `stc_token` (start of
    ///   tool call) = `<|tool_call>` and the paired close token
    ///   `<tool_call|>`.  These are the byte strings the model emits when
    ///   invoking a tool.  Confirmed from chat_template.jinja lines 192/203:
    ///   `{{- '<|tool_call>call:...<tool_call|>' }}`.
    /// - **Qwen 3.5/3.6**: token ids 248058 (`<tool_call>`) and 248059
    ///   (`</tool_call>`).  The chat_template emits
    ///   `<tool_call>\n<function=NAME>…</function>\n</tool_call>` so the
    ///   outer `<tool_call>` / `</tool_call>` pair are the registered markers.
    ///
    /// WHY this matters: using the *prompt-side* thinking-mode hint (`<|think|>`)
    /// instead of the *runtime-emission* boundary (`<|channel>`) caused the
    /// reasoning splitter to be permanently dead for Gemma 4 until iter B-2
    /// corrected the registration.  Any future model addition must audit the
    /// tokenizer_config and chat_template before setting these fields.
    pub tool_open: Option<&'static str>,
    /// Closing marker for a tool-call block. `None` = no tool calls.
    /// See `tool_open` for the marker-shape contract.
    pub tool_close: Option<&'static str>,

    /// Optional free-text preamble injected before the chat history when
    /// tools are present. Gives the model a hint like
    /// `"You have access to the following tools: ..."`. `None` = no preamble.
    pub tool_preamble: Option<&'static str>,
}

impl ModelRegistration {
    /// Does this registration match the supplied model id?
    /// Case-insensitive substring scan over `id_substrings`.
    pub fn matches(&self, model_id: &str) -> bool {
        let lower = model_id.to_ascii_lowercase();
        self.id_substrings
            .iter()
            .any(|s| lower.contains(&s.to_ascii_lowercase()))
    }

    /// Returns `true` if this registration has a usable reasoning span.
    pub fn has_reasoning(&self) -> bool {
        self.reasoning_open.is_some() && self.reasoning_close.is_some()
    }

    /// Returns `true` if this registration has a usable tool-call span.
    pub fn has_tools(&self) -> bool {
        self.tool_open.is_some() && self.tool_close.is_some()
    }

    /// Emit a GBNF string that physically constrains the model output to a
    /// well-formed tool-call wrapper for function `fn_name` with parameters
    /// matching `params_schema` (a JSON Schema object).
    ///
    /// `shape` selects the root rule's overall structure (Wave 2.7 W-η):
    ///
    ///   * `GrammarShape::SingleBody` — root accepts ONLY the body
    ///     (e.g. Gemma `call:NAME{...}`, Qwen `<function=NAME>...</function>`).
    ///     Open/close markers are NOT in the grammar; the caller relies on
    ///     `ToolCallSplitter` to swallow them and on `awaiting_trigger`-gated
    ///     lazy enforcement (`GrammarKind::ToolCallBodyAuto`) so the runtime
    ///     only kicks in after the open marker is observed.  Pre-W-η
    ///     behaviour, preserved for forward-looking AUTO support.
    ///
    ///   * `GrammarShape::OneOrMoreCalls { parallel }` — root accepts the
    ///     FULL CALL: `marker_open + body + marker_close` (Gemma 4),
    ///     `\n<tool_call>\n<function=NAME>\n...\n</function>\n</tool_call>`
    ///     (Qwen 3.5/3.6), with `min_calls = 1` so at least one call is
    ///     produced.  When `parallel = true`, the root accepts repetition
    ///     (Gemma: bare `(call)+`; Qwen: `call ("\n" call)*`).  Used by
    ///     `compile_tool_grammar` for `tool_choice = required / function`
    ///     paired with `GrammarKind::ToolCallBodyRequired` for eager
    ///     enforcement from token 0.  Mirrors llama.cpp
    ///     `p.repeat(call, min=1, max=parallel?-1:1)` at
    ///     `/opt/llama.cpp/common/chat.cpp:898-902, 1177-1181, 1399-1404`.
    ///
    /// Returns `Err(String)` when the family is unknown or when `params_schema`
    /// contains a feature the per-model emitter doesn't support yet. The error
    /// string is forwarded as a 400 `grammar_error` to the caller.
    ///
    /// WHY the return type is `String` (not `Grammar`):
    /// registry.rs intentionally has no dependency on `grammar::parser` to
    /// keep the module's concern narrow (marker registration + body parsing).
    /// The caller in handlers.rs already imports the grammar module and calls
    /// `grammar::parser::parse` on the returned string — the same pattern used
    /// by `compile_response_format`.
    pub fn tool_call_gbnf(
        &self,
        fn_name: &str,
        params_schema: &serde_json::Value,
        shape: GrammarShape,
    ) -> Result<String, String> {
        match self.family {
            "gemma4" => {
                gemma4_tool_call_gbnf(fn_name, params_schema, shape).map_err(|e| e.to_string())
            }
            "qwen35" => {
                qwen35_tool_call_gbnf(fn_name, params_schema, shape).map_err(|e| e.to_string())
            }
            "deepseek4" => {
                deepseek4_tool_call_gbnf(fn_name, params_schema, shape).map_err(|e| e.to_string())
            }
            other => Err(format!(
                "tool_call_gbnf: no per-model grammar emitter for family '{}'",
                other
            )),
        }
    }

    /// Per-family separator that appears between calls 2+ in a parallel
    /// tool-call sequence.  Returned for the multi-function combiner case
    /// (`combine_function_grammars`) so the alternated-across-functions
    /// repetition uses the family-correct chat-template form.
    ///
    /// * Gemma 4: empty string — chat_template.jinja:189-205 emits calls
    ///   back-to-back with no separator (`<|tool_call>...<tool_call|>`
    ///   immediately followed by the next call's `<|tool_call>`).
    /// * Qwen 3.5/3.6: `"\n"` — tokenizer_config.json:285+ chat_template's
    ///   loop "else" branch prepends `\n` to calls 2+.
    /// * Unknown families: empty string (no separator) is the safe
    ///   default; the per-family emitter rejects unknown families before
    ///   this method is called from `combine_function_grammars`.
    pub fn parallel_call_separator(&self) -> &'static str {
        match self.family {
            "gemma4" => "",
            "qwen35" => "\n",
            "deepseek4" => "\n",
            _ => "",
        }
    }

    /// Wave 3.5 HIGH-1 — Auto-lazy multi-function parallel inter-call
    /// sequence.  Used by `combine_function_grammars` when wiring up
    /// `tool_choice = auto` with multiple registered functions and
    /// `parallel_tool_calls = true`.
    ///
    /// Unlike `parallel_call_separator()`, this string includes the
    /// **open marker** because the per-function alts under Auto-lazy
    /// are body-only (`OneOrMoreCallsBodyOnly { parallel: false }` =
    /// `body close`).  Inserting the open marker as part of the
    /// inter-call sequence reconstructs the correct chat-template
    /// emission shape WITHOUT requiring the FIRST open marker (which
    /// the splitter consumes via the awaiting_trigger gate before the
    /// grammar is engaged).
    ///
    /// * Gemma 4: `"<|tool_call>"` — no whitespace, just the open
    ///   marker (chat_template.jinja:189-205 emits calls back-to-back
    ///   with the next call's `<|tool_call>` immediately after the
    ///   previous `<tool_call|>`).
    /// * Qwen 3.5/3.6: `"\n<tool_call>\n"` — `\n` separator + open
    ///   marker + `\n` (mirrors the chat_template loop's
    ///   `\n<tool_call>\n...\n</tool_call>` per-call pattern; the
    ///   trailing `\n</tool_call>` is provided by the per-fn body-only
    ///   shape).
    /// * Unknown families: empty string (combiner rejects unknown
    ///   families before this method is called).
    pub fn auto_lazy_multi_fn_inter_call(&self) -> &'static str {
        match self.family {
            "gemma4" => "<|tool_call>",
            "qwen35" => "\n<tool_call>\n",
            // DeepSeek puts multiple invokes inside one outer block. The
            // dedicated emitter carries that repetition; multi-function
            // combination uses a newline between body alternatives.
            "deepseek4" => "\n",
            _ => "",
        }
    }
}

/// Root-rule shape selector for `tool_call_gbnf`.
///
/// Wave 2.7 W-η Q-A + Q-B: unified emitter API for the eager-grammar
/// (REQUIRED/Function) and forward-looking lazy-grammar (AUTO) paths.
///
/// See `ModelRegistration::tool_call_gbnf` for the per-variant semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GrammarShape {
    /// Body-only root.  Open/close markers handled by the splitter; the
    /// runtime is expected to be `awaiting_trigger`-gated by the caller
    /// (`GrammarKind::ToolCallBodyAuto`).  Pre-Wave 2.7 behaviour.
    SingleBody,
    /// Full-call root (`marker_open + body + marker_close`, repeated
    /// `min=1`, `max=parallel?∞:1`).  Open/close markers ARE in the
    /// grammar; the runtime is expected to be EAGER from token 0
    /// (`GrammarKind::ToolCallBodyRequired`).
    ///
    /// `parallel = true` accepts repetition (Wave 2.7 W-η Q-B):
    ///   * Gemma 4: bare back-to-back `(call)+` (no separator —
    ///     chat_template.jinja:189-205 emits calls with no inter-call
    ///     bytes).
    ///   * Qwen 3.5/3.6: `call ("\n" call)*` (template separates calls
    ///     2+ with literal `\n`; tokenizer_config.json:285+).
    OneOrMoreCalls { parallel: bool },
    /// Wave 3.5 HIGH-1 — body-only multi-call root with the **first** open
    /// marker stripped.  Used exclusively by `tool_choice = auto` paired
    /// with `GrammarKind::ToolCallBodyAuto` (lazy / awaiting_trigger).
    ///
    /// Production-order rationale (audit
    /// /tmp/cfa-cfa-20260427-adr005-wave3/codex-review-last.txt divergence
    /// "W-B2 Auto lazy grammar production correctness"):  the engine's
    /// decode loop calls `runtime.accept_bytes(token_bytes)` on every
    /// sampled token BEFORE the splitter's marker boundary fires.  While
    /// `awaiting_trigger=true` (Auto-lazy), `accept_bytes` is a no-op.
    /// The splitter then sees the per-model open marker as a special
    /// single-token emission (see the marker-shape contract on
    /// `tool_open` / `tool_close` above), fires `ToolCallOpen`, and the
    /// engine calls `runtime.trigger()` flipping the gate false.  The
    /// FIRST open marker has already been consumed (as no-op) at this
    /// point — replaying it into the now-eager grammar would distort
    /// the byte stream.
    ///
    /// Required/Function uses `OneOrMoreCalls` because no splitter
    /// precedes the eager grammar; the marker IS part of the body
    /// grammar from byte 0.  Auto uses this variant because the FIRST
    /// open marker is consumed by the awaiting_trigger gate before the
    /// grammar is engaged.  Subsequent markers (close marker after this
    /// call's body, AND any inter-call open markers under
    /// `parallel = true`) ARE in the grammar — those bytes flow through
    /// `accept_bytes` while the runtime is eager.
    ///
    /// Concrete shape:
    ///   * `parallel = false`:
    ///       Gemma 4: `body close_marker space`
    ///       Qwen 3.5/3.6: `body \n close_marker space` (mirrors the
    ///         chat_template's `\n</tool_call>` close form)
    ///   * `parallel = true`:
    ///       Gemma 4: `body close_marker ( open_marker body close_marker )* space`
    ///       Qwen 3.5/3.6: `body \n close_marker ( \n open_marker \n body \n close_marker )* space`
    ///
    /// Audit recommendation reference (research-report.md §Q1+§Q2): the
    /// canonical Wave 2.6 architecture is "grammar = body validator;
    /// splitter = boundary detector".  For Auto-lazy the FIRST marker is
    /// the splitter's responsibility (it's what triggers the grammar);
    /// thereafter the grammar accepts everything including any closing
    /// and re-opening markers.
    OneOrMoreCallsBodyOnly { parallel: bool },
}

// ---------------------------------------------------------------------------
// Built-in registrations (day-one models)
// ---------------------------------------------------------------------------

/// Gemma 4 (26B / A4B / variants). Uses `<|channel>` / `<channel|>` for
/// reasoning spans — the asymmetric channel-block convention emitted by the
/// model whenever it produces a thinking trace
/// (`<|channel>thought\n…<channel|>`; see `models/gemma-4-26B-A4B-it-ara-abliterated-dwq/chat_template.jinja:141-151`'s
/// `strip_thinking` macro and `tokenizer_config.json` `x-regex`
/// `\<\|channel\>thought\n(?P<thinking>.*?)\<channel\|\>`). Tool calling
/// uses the parallel `<|tool_call>` / `<tool_call|>` shape — note the
/// asymmetric pipe placement on both pairs (see chat_template lines 189-203).
///
/// **Marker shape audit (2026-04-26 W66 iter-133 Iter B-2):** the tool-call
/// pair was previously declared as `<tool_call>` / `</tool_call>` (the Qwen
/// convention). The gemma-4 GGUF chat template actually emits
/// `<|tool_call>call:NAME{...}<tool_call|>`, not `<tool_call>...</tool_call>`.
/// Real-model fixture `tests/fixtures/openwebui_multiturn/scenario2_tool_call_chunks.txt`
/// (W65 iter-133 Iter B) confirmed the literal mismatch. Iter B-2 fixed
/// the registration to match the in-template strings so the engine's
/// `ToolCallSplitter` actually detects what the model emits.
///
/// **Reasoning marker audit (2026-04-26 W67 iter-133 Iter D):** same
/// bug-class as the iter-B-2 tool-call fix. The reasoning pair was
/// previously declared as `<|think|>` / `</think|>` — both wrong. The
/// `<|think|>` literal is the system-block thinking-hint emitted only when
/// `enable_thinking=true` is passed to the chat template (chat_template:162);
/// it is not the runtime reasoning-emission boundary. The actual emission
/// pair (consulted authoritatively by `strip_thinking` and the
/// tokenizer_config `x-regex`) is `<|channel>` (open; aliased `soc_token`
/// in tokenizer_config:87) / `<channel|>` (close; aliased `eoc_token` in
/// tokenizer_config:8,28). This iter corrects the registration so the
/// engine's `ReasoningSplitter` detects what the model emits during decode
/// (any `<|channel>thought\n…<channel|>` block the model produces gets
/// routed to `delta.reasoning_content`; the literal `thought\n` channel
/// identifier remains visible inside the routed reasoning text by design,
/// mirroring `strip_thinking`'s scope).
pub const GEMMA4: ModelRegistration = ModelRegistration {
    family: "gemma4",
    id_substrings: &["gemma-4", "gemma4"],
    reasoning_open: Some("<|channel>"),
    reasoning_close: Some("<channel|>"),
    tool_open: Some("<|tool_call>"),
    tool_close: Some("<tool_call|>"),
    tool_preamble: None,
};

/// Qwen 3.5 / 3.6 family. Uses `<think>` / `</think>` — the Qwen convention
/// (no pipe in the closer; distinct from Gemma's). Tool calling also uses
/// `<tool_call>` / `</tool_call>` (Qwen standard).
pub const QWEN35: ModelRegistration = ModelRegistration {
    family: "qwen35",
    id_substrings: &["qwen3.5", "qwen3.6", "qwen35", "qwen36"],
    reasoning_open: Some("<think>"),
    reasoning_close: Some("</think>"),
    tool_open: Some("<tool_call>"),
    tool_close: Some("</tool_call>"),
    tool_preamble: None,
};

/// DeepSeek-V4-Flash-0731. Tool calls use one outer DSML block containing
/// one or more invoke elements; the body parser therefore returns a vector
/// rather than assuming one marker pair equals one function call.
pub const DEEPSEEK4: ModelRegistration = ModelRegistration {
    family: "deepseek4",
    id_substrings: &["deepseek-v4", "deepseek v4", "deepseek4", "deepseek_v4"],
    reasoning_open: Some("<think>"),
    reasoning_close: Some("</think>"),
    tool_open: Some("<|DSML|tool_calls>"),
    tool_close: Some("</|DSML|tool_calls>"),
    tool_preamble: None,
};

/// All built-in registrations in priority order. Later entries override
/// earlier ones when substrings overlap — but day-one substrings are
/// disjoint.
pub const BUILTIN_REGISTRATIONS: &[ModelRegistration] = &[GEMMA4, QWEN35, DEEPSEEK4];

// ---------------------------------------------------------------------------
// Registry (process-global)
// ---------------------------------------------------------------------------

/// Dynamic registry, seeded with `BUILTIN_REGISTRATIONS` plus any runtime
/// additions via `register`.
static REGISTRY: OnceLock<std::sync::RwLock<Vec<ModelRegistration>>> = OnceLock::new();

fn reg() -> &'static std::sync::RwLock<Vec<ModelRegistration>> {
    REGISTRY.get_or_init(|| std::sync::RwLock::new(BUILTIN_REGISTRATIONS.to_vec()))
}

/// Find a registration matching `model_id`, or `None` if no family matches.
/// Matches on case-insensitive substring per `ModelRegistration::matches`.
pub fn find_for(model_id: &str) -> Option<ModelRegistration> {
    let guard = reg().read().unwrap();
    for r in guard.iter() {
        if r.matches(model_id) {
            return Some(r.clone());
        }
    }
    None
}

/// List all registered model families. Useful for `/v1/models` extension
/// fields + debug diagnostics.
pub fn list_families() -> Vec<String> {
    let guard = reg().read().unwrap();
    guard.iter().map(|r| r.family.to_string()).collect()
}

/// Register an additional model family at runtime (e.g. for downstream
/// applications embedding hf2q as a library). Later registrations take
/// precedence on overlapping substrings.
pub fn register(entry: ModelRegistration) {
    reg().write().unwrap().push(entry);
}

// ---------------------------------------------------------------------------
// Reasoning-boundary state machine (Decision #21)
// ---------------------------------------------------------------------------

/// Tracks position inside a reasoning span while decoded text accumulates.
/// Engine creates one per generation, feeds decoded fragments in, and gets
/// back per-fragment classification (`DeltaKind::Reasoning` or
/// `DeltaKind::Content`).
///
/// The state machine is simple: a single `in_reasoning` flag that flips on
/// `reasoning_open` and off on `reasoning_close`. Markers are detected by
/// substring scan over the most-recent accumulated text — the engine holds
/// a **tail buffer** of the last `max(open.len, close.len)` bytes to avoid
/// missing markers that span fragment boundaries.
#[derive(Debug, Clone)]
pub struct ReasoningSplitter {
    open_marker: &'static str,
    close_marker: &'static str,
    in_reasoning: bool,
    /// Sliding tail of decoded text — long enough to see either marker span
    /// across token boundaries.
    tail_buf: String,
    tail_cap: usize,
}

impl ReasoningSplitter {
    /// Build from a registration. If the registration has no reasoning
    /// markers, returns `None` — callers route all text to `Content`.
    ///
    /// Starts OUTSIDE reasoning. Engine paths must construct through
    /// [`make_reasoning_splitter`] instead so the ADR-005 iter-230
    /// forced-open seed is never dropped (grep-pinned by
    /// `iter230_b2_factory_only_construction`).
    pub fn from_registration(reg: &ModelRegistration) -> Option<Self> {
        Self::from_registration_forced(reg, false)
    }

    /// Build from a registration with an explicit initial reasoning
    /// state (ADR-005 iter-230 B). `forced_open = true` when the
    /// rendered prompt ends inside an open reasoning block (e.g. the
    /// Qwen 3.6 template seeds `<think>\n` at the end of the generation
    /// prompt with thinking on) — the completion then begins INSIDE
    /// reasoning and the model never re-emits the open marker, so an
    /// unseeded splitter would leak the whole reasoning span plus the
    /// close marker into `content`. A redundant model-emitted open
    /// marker while seeded open is reasoning TEXT (today's nested-open
    /// behavior), not swallowed.
    pub fn from_registration_forced(reg: &ModelRegistration, forced_open: bool) -> Option<Self> {
        let (open, close) = match (reg.reasoning_open, reg.reasoning_close) {
            (Some(o), Some(c)) if !o.is_empty() && !c.is_empty() => (o, c),
            _ => return None,
        };
        let cap = open.len().max(close.len()).max(1);
        Some(Self {
            open_marker: open,
            close_marker: close,
            in_reasoning: forced_open,
            tail_buf: String::with_capacity(cap * 2),
            tail_cap: cap,
        })
    }

    /// Accept a fragment of decoded text. Returns a `Vec<(Slot, String)>`
    /// describing how the fragment should be routed. A fragment may produce
    /// multiple slots if a marker boundary falls inside it.
    ///
    /// Markers themselves are **swallowed** — they don't appear in either
    /// output slot. This matches the OpenAI-o1 convention: the user sees
    /// `reasoning_content` as clean text, `content` as clean text, and the
    /// marker delimiters are hidden.
    pub fn feed(&mut self, fragment: &str) -> Vec<(SplitSlot, String)> {
        let mut out: Vec<(SplitSlot, String)> = Vec::new();
        // Prepend the sliding tail so markers that span fragment boundaries
        // are still detected. The tail was *held back* from prior emission
        // (not already emitted), so scan + emit from offset 0.
        let mut scan = std::mem::take(&mut self.tail_buf);
        scan.push_str(fragment);

        let mut scan_cursor = 0usize;
        let mut out_cursor = 0usize;

        loop {
            let active_marker = if self.in_reasoning {
                self.close_marker
            } else {
                self.open_marker
            };
            match scan[scan_cursor..].find(active_marker) {
                Some(rel) => {
                    let marker_start = scan_cursor + rel;
                    // Emit text [out_cursor..marker_start] to the current slot.
                    let slot = if self.in_reasoning {
                        SplitSlot::Reasoning
                    } else {
                        SplitSlot::Content
                    };
                    if marker_start > out_cursor {
                        out.push((slot, scan[out_cursor..marker_start].to_string()));
                    }
                    // Flip state + skip past marker.
                    self.in_reasoning = !self.in_reasoning;
                    scan_cursor = marker_start + active_marker.len();
                    out_cursor = scan_cursor;
                }
                None => {
                    // No more markers in the remainder. Commit the tail
                    // portion that's still sitting after out_cursor, minus
                    // the last `tail_cap` bytes which we hold back in case
                    // they're the start of a next-fragment marker.
                    let total_len = scan.len();
                    let emit_end = total_len.saturating_sub(self.tail_cap);
                    if emit_end > out_cursor {
                        // Align emit_end to a char boundary so we never split
                        // a UTF-8 code point.
                        let emit_end = snap_down_char_boundary(&scan, emit_end);
                        if emit_end > out_cursor {
                            let slot = if self.in_reasoning {
                                SplitSlot::Reasoning
                            } else {
                                SplitSlot::Content
                            };
                            out.push((slot, scan[out_cursor..emit_end].to_string()));
                            out_cursor = emit_end;
                        }
                    }
                    // Stash the remainder as the new tail.
                    self.tail_buf = scan[out_cursor..].to_string();
                    break;
                }
            }
        }
        out
    }

    /// Drain any buffered tail into an output slot at generation end. Called
    /// by the engine when decode finishes, so tail-stashed text isn't lost.
    pub fn finish(&mut self) -> Option<(SplitSlot, String)> {
        if self.tail_buf.is_empty() {
            return None;
        }
        let slot = if self.in_reasoning {
            SplitSlot::Reasoning
        } else {
            SplitSlot::Content
        };
        let text = std::mem::take(&mut self.tail_buf);
        Some((slot, text))
    }

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

fn snap_down_char_boundary(s: &str, mut idx: usize) -> usize {
    // Snap idx DOWN to the nearest char boundary so we don't split a UTF-8
    // code point when slicing out a contiguous run.
    while idx > 0 && !s.is_char_boundary(idx) {
        idx -= 1;
    }
    idx
}

/// Which OpenAI delta slot a fragment belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitSlot {
    /// `delta.content` / `message.content`.
    Content,
    /// `delta.reasoning_content` / `message.reasoning_content`.
    Reasoning,
}

// ---------------------------------------------------------------------------
// Tool-call boundary state machine (Decision #21 sibling, iter-133 Iter B-2)
// ---------------------------------------------------------------------------

/// Output emitted by `ToolCallSplitter::feed`. The splitter classifies each
/// decoded fragment into one of:
///   - **`Content(text)`** — outside any tool-call span; route to
///     `delta.content` (or further classify via `ReasoningSplitter`).
///   - **`ToolCallOpen`** — a tool-call open marker has just been observed;
///     emitted exactly once per call. The producer should:
///       1. Synthesize a `tool_call_id` (`call_<rand>`).
///       2. Buffer subsequent `ToolCallText` fragments until `ToolCallClose`.
///   - **`ToolCallText(text)`** — accumulated raw text inside the open/close
///     markers (including the `call:NAME{...}` Gemma 4 syntax). The marker
///     literals themselves are swallowed; the text run is the model's verbatim
///     argument syntax.
///   - **`ToolCallClose`** — the close marker has been observed; the
///     accumulated tool-call body is complete and the producer can parse +
///     emit the structured `delta.tool_calls.function.{name,arguments}` chunk.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolCallEvent {
    Content(String),
    ToolCallOpen,
    ToolCallText(String),
    ToolCallClose,
}

/// Tracks position inside a tool-call span while decoded text accumulates.
/// Sibling to `ReasoningSplitter` — same tail-buffer pattern, same
/// boundary-marker semantics, different output enum because tool-call
/// downstream wiring (`GenerationEvent::ToolCallDelta`) carries more
/// structure than `Reasoning` vs `Content`.
///
/// **Marker shape (per-model registration, not parsing):** the splitter
/// detects the literal open/close markers from `ModelRegistration.tool_open`
/// / `tool_close` (e.g. Gemma 4: `<|tool_call>` / `<tool_call|>`; Qwen 3.5/3.6:
/// `<tool_call>` / `</tool_call>`). The text run between them — the `call:NAME{kv-list}`
/// Gemma syntax or the `<function=NAME><parameter=...>...</function>` Qwen
/// syntax — is parsed by a per-model parser at `ToolCallClose` emission, not
/// by this splitter.
///
/// **Composition with `ReasoningSplitter`:** the engine runs
/// `ReasoningSplitter` first (reasoning is always outside tool calls); the
/// `Content`-classified fragments then flow into `ToolCallSplitter`. The
/// same tail-buffer discipline guarantees markers spanning fragment
/// boundaries are still detected.
/// Per-family in-call resync markers. When `ToolCallSplitter::feed` sees
/// any of these literals while `in_tool_call=true`, the current call body
/// is aborted (synthetic `ToolCallClose` emitted with the partial body)
/// rather than absorbing the marker bytes into `ToolCallText`. iter-219c
/// 2026-05-01 — closes the iter-218 LIVE-bug class structurally at the
/// splitter level instead of relying on downstream defensive scrubbing.
///
/// Marker selection mirrors the registered family special-tokens that
/// MUST NOT appear inside a tool-call body per the chat-template
/// `tokenizer_config.json`'s regex: for Gemma 4, the call body is
/// `<\|tool_call>(.*?)<tool_call\|>` — anything else (channel / turn /
/// tool_response) is OUT-of-call. Seeing one of those mid-call indicates
/// the model went off-template and the call MUST be aborted defensively.
fn family_resync_markers(open_marker: &str) -> &'static [&'static str] {
    match open_marker {
        "<|tool_call>" => &[
            // Gemma 4 family.
            "<|tool_response>",
            "<tool_response|>",
            "<|channel>",
            "<channel|>",
            "<|turn>",
            "<turn|>",
        ],
        "<tool_call>" => &[
            // Qwen 3.5/3.6 family.
            "<think>", "</think>",
        ],
        _ => &[],
    }
}

#[derive(Debug, Clone)]
pub struct ToolCallSplitter {
    open_marker: &'static str,
    close_marker: &'static str,
    /// iter-219c (2026-05-01): markers that, when observed inside a
    /// tool-call body (`in_tool_call=true`), trigger a synthetic
    /// `ToolCallClose` (abort). Derived from `family_resync_markers` at
    /// construction.
    in_call_resync: &'static [&'static str],
    in_tool_call: bool,
    /// Sliding tail of decoded text — long enough to see either marker span
    /// across token boundaries. See `ReasoningSplitter::tail_buf` for the
    /// identical mechanism. iter-219c: tail_cap now must accommodate the
    /// LONGEST resync marker too.
    tail_buf: String,
    tail_cap: usize,
}

impl ToolCallSplitter {
    /// Build from a registration. If the registration has no tool markers,
    /// returns `None` — callers route all text to `Content`.
    pub fn from_registration(reg: &ModelRegistration) -> Option<Self> {
        let (open, close) = match (reg.tool_open, reg.tool_close) {
            (Some(o), Some(c)) if !o.is_empty() && !c.is_empty() => (o, c),
            _ => return None,
        };
        let in_call_resync = family_resync_markers(open);
        // tail_cap must accommodate the longest of: open, close, any resync
        // marker — so all marker types are detectable across token boundaries.
        let mut cap = open.len().max(close.len()).max(1);
        for m in in_call_resync {
            cap = cap.max(m.len());
        }
        Some(Self {
            open_marker: open,
            close_marker: close,
            in_call_resync,
            in_tool_call: false,
            tail_buf: String::with_capacity(cap * 2),
            tail_cap: cap,
        })
    }

    /// Accept a fragment of decoded text. Returns a sequence of
    /// `ToolCallEvent`s describing how the fragment should be routed. A
    /// fragment may produce multiple events if a marker boundary falls
    /// inside it (e.g. `pre <|tool_call>call:f{}<tool_call|> post` →
    /// `[Content("pre "), ToolCallOpen, ToolCallText("call:f{}"),
    /// ToolCallClose, Content(" post")]`).
    ///
    /// Markers themselves are **swallowed** — they don't appear in any
    /// emitted text event. This matches the OpenAI spec: `delta.content`
    /// gets natural-language text only; `delta.tool_calls.function.{name,
    /// arguments}` gets the parsed call syntax (parsed by the engine after
    /// observing `ToolCallClose`).
    pub fn feed(&mut self, fragment: &str) -> Vec<ToolCallEvent> {
        let mut out: Vec<ToolCallEvent> = Vec::new();
        // Prepend the sliding tail so markers that span fragment boundaries
        // are still detected (same mechanism as ReasoningSplitter).
        let mut scan = std::mem::take(&mut self.tail_buf);
        scan.push_str(fragment);

        let mut scan_cursor = 0usize;
        let mut out_cursor = 0usize;

        loop {
            // iter-219c (2026-05-01): in BOTH states, scan for the
            // active state-flip marker AND any stray family markers
            // that should be swallowed.
            //
            //   in_tool_call=true:
            //     - close_marker → state-flip (ToolCallClose)
            //     - resync markers (`<|tool_response>`, `<|channel>`, `<|turn>`)
            //       → state-flip (synthetic ToolCallClose, call aborted) +
            //       swallow the marker bytes
            //   in_tool_call=false:
            //     - open_marker → state-flip (ToolCallOpen)
            //     - close_marker (stray) → swallow (no event; just advance)
            //     - resync markers (stray) → swallow (no event; just advance)
            //
            // The "swallow stray" path keeps registered family markers
            // out of `delta.content` even when they appear in unexpected
            // positions (e.g. post-abort tail bytes after iter-219c
            // synthesizes a ToolCallClose). Without this, a `<tool_call|>`
            // following an aborted call would bleed into Content.
            #[derive(Clone, Copy)]
            enum Hit {
                StateFlip(&'static str),
                Swallow(&'static str),
            }
            let hit: Option<(usize, Hit)> = if self.in_tool_call {
                let mut best: Option<(usize, Hit)> = scan[scan_cursor..]
                    .find(self.close_marker)
                    .map(|r| (r, Hit::StateFlip(self.close_marker)));
                for &resync in self.in_call_resync {
                    if let Some(r) = scan[scan_cursor..].find(resync) {
                        match best {
                            None => best = Some((r, Hit::StateFlip(resync))),
                            Some((b, _)) if r < b => best = Some((r, Hit::StateFlip(resync))),
                            _ => {}
                        }
                    }
                }
                best
            } else {
                let mut best: Option<(usize, Hit)> = scan[scan_cursor..]
                    .find(self.open_marker)
                    .map(|r| (r, Hit::StateFlip(self.open_marker)));
                // Stray close_marker outside a call → swallow.
                if let Some(r) = scan[scan_cursor..].find(self.close_marker) {
                    match best {
                        None => best = Some((r, Hit::Swallow(self.close_marker))),
                        Some((b, _)) if r < b => best = Some((r, Hit::Swallow(self.close_marker))),
                        _ => {}
                    }
                }
                // Stray in-call markers outside a call → swallow.
                for &resync in self.in_call_resync {
                    if let Some(r) = scan[scan_cursor..].find(resync) {
                        match best {
                            None => best = Some((r, Hit::Swallow(resync))),
                            Some((b, _)) if r < b => best = Some((r, Hit::Swallow(resync))),
                            _ => {}
                        }
                    }
                }
                best
            };
            match hit {
                Some((rel, kind)) => {
                    let marker_start = scan_cursor + rel;
                    let marker = match kind {
                        Hit::StateFlip(m) | Hit::Swallow(m) => m,
                    };
                    // Emit text [out_cursor..marker_start] as the current slot.
                    if marker_start > out_cursor {
                        let text = scan[out_cursor..marker_start].to_string();
                        if self.in_tool_call {
                            out.push(ToolCallEvent::ToolCallText(text));
                        } else {
                            out.push(ToolCallEvent::Content(text));
                        }
                    }
                    match kind {
                        Hit::StateFlip(_) => {
                            // Emit the open/close synthetic event + flip state.
                            if self.in_tool_call {
                                out.push(ToolCallEvent::ToolCallClose);
                            } else {
                                out.push(ToolCallEvent::ToolCallOpen);
                            }
                            self.in_tool_call = !self.in_tool_call;
                        }
                        Hit::Swallow(_) => {
                            // Marker swallowed — no event, no state change.
                        }
                    }
                    scan_cursor = marker_start + marker.len();
                    out_cursor = scan_cursor;
                }
                None => {
                    // No more markers in the remainder. Emit the portion that's
                    // still after out_cursor MINUS the last `tail_cap` bytes,
                    // which we hold back in case they're the start of a
                    // next-fragment marker.
                    let total_len = scan.len();
                    let emit_end = total_len.saturating_sub(self.tail_cap);
                    if emit_end > out_cursor {
                        let emit_end = snap_down_char_boundary(&scan, emit_end);
                        if emit_end > out_cursor {
                            let text = scan[out_cursor..emit_end].to_string();
                            if self.in_tool_call {
                                out.push(ToolCallEvent::ToolCallText(text));
                            } else {
                                out.push(ToolCallEvent::Content(text));
                            }
                            out_cursor = emit_end;
                        }
                    }
                    self.tail_buf = scan[out_cursor..].to_string();
                    break;
                }
            }
        }
        out
    }

    /// Drain any buffered tail at generation end. Called by the engine when
    /// decode finishes so tail-stashed text isn't lost. Note: if generation
    /// ends mid-tool-call (e.g. EOS while `in_tool_call=true`) the tail goes
    /// into `ToolCallText`; the caller is responsible for deciding what to
    /// do with an unterminated call (typical: emit a synthetic
    /// `ToolCallClose` and finalize anyway, OR drop the partial call).
    pub fn finish(&mut self) -> Option<ToolCallEvent> {
        if self.tail_buf.is_empty() {
            return None;
        }
        let text = std::mem::take(&mut self.tail_buf);
        if self.in_tool_call {
            Some(ToolCallEvent::ToolCallText(text))
        } else {
            Some(ToolCallEvent::Content(text))
        }
    }

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

// ---------------------------------------------------------------------------
// Tool-call body parser (Gemma 4 + Qwen 3.5/3.6 syntaxes)
// ---------------------------------------------------------------------------

/// Parsed shape of a single tool-call body, ready to populate the
/// OpenAI `delta.tool_calls.function.{name, arguments}` chunk fields.
///
/// `arguments` is a JSON-encoded string per the OpenAI streaming spec —
/// clients accumulate it across deltas and `JSON.parse` at the end.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedToolCall {
    pub name: String,
    /// JSON-encoded arguments (e.g. `{"location":"Paris"}`).
    pub arguments_json: String,
}

/// Every registered in-call special-token marker across all supported
/// families. Mirrors `BUILTIN_REGISTRATIONS` and the `LEAK_MARKERS` array
/// in `tests/openwebui_multiturn.rs:115-138`. Used by the Auto-policy
/// content-fallback scrubber so a malformed-body emit cannot leak any of
/// these tokens into `delta.content`.
const ALL_FAMILY_LEAK_MARKERS: &[&str] = &[
    // Gemma 4 reasoning + tool + turn
    "<|channel>",
    "<channel|>",
    "<|tool_call>",
    "<tool_call|>",
    "<|tool_response>",
    "<tool_response|>",
    "<|turn>",
    "<turn|>",
    // Qwen 3.5 / 3.6 reasoning + tool
    "<think>",
    "</think>",
    "<tool_call>",
    "</tool_call>",
    // DeepSeek-V4 DSML tool block + inner records
    "<|DSML|tool_calls>",
    "</|DSML|tool_calls>",
    "<|DSML|invoke",
    "</|DSML|invoke>",
    "<|DSML|parameter",
    "</|DSML|parameter>",
];

/// Scrub all registered family special-token markers from `body` so they
/// cannot leak into `delta.content` via the Auto-policy content-fallback
/// path (`emit_streaming_tool_call_close` on parse failure). Returns the
/// body with markers replaced by the empty string.
///
/// **iter-219b (2026-05-01)**: when the validity gate (`is_valid_tool_name`)
/// rejects a polluted tool-call name, `emit_streaming_tool_call_close`
/// under `ToolCallPolicy::Auto` falls back to emitting the raw body as
/// `Content`. Without scrubbing, the body's special-token literals
/// (e.g. `<|tool_response>` decoded from token id 50) reach the OpenAI
/// client verbatim — re-introducing the iter-217-class leak that the
/// `tests/openwebui_multiturn.rs::assert_no_leaked_special_tokens` gate is
/// supposed to make loud at LIVE-test time. Strip every registered
/// in-call marker so the fallback path stays content-correct regardless
/// of which family registered the request.
pub fn scrub_special_tokens(body: &str) -> String {
    let mut out = body.to_string();
    for m in ALL_FAMILY_LEAK_MARKERS {
        if out.contains(m) {
            out = out.replace(m, "");
        }
    }
    out
}

/// Validate an OpenAI-spec function name. Tool names are required to match
/// `^[a-zA-Z0-9_-]+$` per the OpenAI tool-spec — no special-token bytes,
/// no whitespace, no nested call/colon syntax.
///
/// **iter-219b (2026-05-01)**: this gate exists because the model can emit
/// known special-token literals (`<|tool_response>`, `<|channel>`, etc.)
/// MID-tool-call-body; the splitter — which only knows the tool-call
/// open/close marker pair — concatenates those literals into the body
/// buffer verbatim. Without name validation, `extract_gemma4_name_prefix`
/// (engine.rs) and `parse_gemma4_tool_call` / `parse_qwen35_tool_call`
/// below cheerfully return polluted names like
/// `get_current<|tool_response>call:get_current_weather` to the SSE
/// encoder, which proxies them straight to OpenAI clients as
/// `delta.tool_calls.function.name` — surfaced in iter-218 LIVE testing
/// as the malformed `get_currentcall:get_current_weather`. Returning
/// `None`/false from the validity check triggers the existing Auto-policy
/// content-fallback path, which is the OpenAI-spec-correct behavior for
/// an unparseable tool-call body.
pub fn is_valid_tool_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
}

/// Parse a tool-call body emitted between the open/close markers.
///
/// Day-one supports two per-family syntaxes:
///
/// * **Gemma 4** — `call:NAME{key1:<|"|>val1<|"|>,key2:<|"|>val2<|"|>}` (string
///   args wrapped in `<|"|>` quote-markers; numeric/boolean args bare). See
///   `models/gemma4/chat_template.jinja:113-200`.
/// * **Qwen 3.5/3.6** — `\n<function=NAME>\n<parameter=key>\nval\n</parameter>\n...\n</function>\n`.
///   See the Qwen 3.6 GGUF tokenizer_config.json `chat_template` field.
///
/// Returns `None` when the body is unparseable (logged at the call site so
/// the engine can degrade gracefully — emit a `Content(raw_body)` fragment
/// rather than a malformed tool-call delta).
pub fn parse_tool_call_body(reg: &ModelRegistration, body: &str) -> Option<ParsedToolCall> {
    parse_tool_call_bodies(reg, body)?.into_iter().next()
}

/// Parse all function calls represented by one registered outer tool block.
/// Gemma/Qwen marker pairs each contain one call; DeepSeek DSML deliberately
/// permits multiple invokes inside a single pair.
pub fn parse_tool_call_bodies(reg: &ModelRegistration, body: &str) -> Option<Vec<ParsedToolCall>> {
    match reg.family {
        "gemma4" => parse_gemma4_tool_call(body).map(|call| vec![call]),
        "qwen35" => parse_qwen35_tool_call(body).map(|call| vec![call]),
        "deepseek4" => crate::core::deepseek_v4_encoding::parse_tool_calls_body(body)
            .ok()
            .map(|calls| {
                calls
                    .into_iter()
                    .map(|call| ParsedToolCall {
                        name: call.function.name,
                        arguments_json: call.function.arguments,
                    })
                    .collect()
            }),
        _ => None,
    }
}

/// Parse Gemma 4's `call:NAME{kv-list}` body. Whitespace-tolerant.
///
/// String values are wrapped in `<|"|>...<|"|>` markers (the Gemma quote
/// convention; see `models/gemma4/chat_template.jinja:113`). Bare values
/// (no surrounding quote-markers) are treated as JSON-literals (numbers,
/// booleans). Keys are bare identifiers.
fn parse_gemma4_tool_call(body: &str) -> Option<ParsedToolCall> {
    let body = body.trim();
    // Expect `call:NAME{...}`. The open marker has been swallowed by the
    // splitter; the close marker has too. So we start with `call:`.
    let rest = body.strip_prefix("call:")?;
    let brace_start = rest.find('{')?;
    let name = rest[..brace_start].trim().to_string();
    // iter-219b (2026-05-01): reject names that contain special-token
    // bytes the splitter couldn't trim (e.g. `<|tool_response>` emitted
    // mid-call). OpenAI spec requires `[a-zA-Z0-9_-]+`. Returning None
    // triggers the existing content-fallback path.
    if !is_valid_tool_name(&name) {
        return None;
    }
    // Match braces — body of args ends at the LAST `}` (Gemma can have
    // nested args via the `<|"|>` quote-markers, but the outer brace is
    // the call boundary).
    let after_open = &rest[brace_start + 1..];
    let close_idx = after_open.rfind('}')?;
    let kv_str = &after_open[..close_idx];

    // iter-231b: split on top-level commas (depth-aware — commas inside
    // nested `{...}`/`[...]` values do NOT split), then decode each value
    // recursively so structured arguments survive as JSON objects/arrays
    // in `arguments_json` instead of being mangled into string fields.
    let kvs = split_gemma4_top_level(kv_str);
    let mut args = serde_json::Map::new();
    for kv in kvs {
        let (k, v) = split_gemma4_kv_once(kv)?;
        let key = k.trim().to_string();
        if key.is_empty() {
            return None;
        }
        args.insert(key, gemma4_value_to_json(v.trim()));
    }
    let arguments_json = serde_json::to_string(&serde_json::Value::Object(args)).ok()?;
    Some(ParsedToolCall {
        name,
        arguments_json,
    })
}

/// Split a Gemma 4 kv-list / value-list on TOP-LEVEL commas — commas NOT
/// inside a `<|"|>...<|"|>` string-quote span AND not nested inside
/// `{...}`/`[...]` containers (iter-231b: the template's `format_argument`
/// macro renders structured arguments, so the parser must be
/// depth-aware; the pre-iter-231b string-only tracker mangled any nested
/// value containing a comma).
fn split_gemma4_top_level(s: &str) -> Vec<&str> {
    let mut out = Vec::new();
    let mut start = 0usize;
    let mut in_str = false;
    let mut depth: usize = 0;
    let bytes = s.as_bytes();
    let mut i = 0usize;
    while i < bytes.len() {
        // Detect `<|"|>` (5 bytes) at byte i (toggles string state).
        if bytes[i..].starts_with(b"<|\"|>") {
            in_str = !in_str;
            i += 5;
            continue;
        }
        if !in_str {
            match bytes[i] {
                b'{' | b'[' => depth += 1,
                b'}' | b']' => depth = depth.saturating_sub(1),
                b',' if depth == 0 => {
                    out.push(&s[start..i]);
                    start = i + 1;
                }
                _ => {}
            }
        }
        i += 1;
    }
    if start < s.len() {
        out.push(&s[start..]);
    }
    out
}

/// Split a Gemma 4 kv pair on its TOP-LEVEL `:` — the first colon that is
/// neither inside a `<|"|>...<|"|>` string span nor inside nested
/// `{...}`/`[...]` containers.  (Keys are bare identifiers, but a naive
/// `split_once(':')` is still correct for them; this scanner exists so a
/// STRING value containing `:` — e.g. a URL — can never confuse the
/// boundary when the caller is reused on nested pairs whose values lead
/// with a container.)
fn split_gemma4_kv_once(s: &str) -> Option<(&str, &str)> {
    let mut in_str = false;
    let mut depth: usize = 0;
    let bytes = s.as_bytes();
    let mut i = 0usize;
    while i < bytes.len() {
        if bytes[i..].starts_with(b"<|\"|>") {
            in_str = !in_str;
            i += 5;
            continue;
        }
        if !in_str {
            match bytes[i] {
                b'{' | b'[' => depth += 1,
                b'}' | b']' => depth = depth.saturating_sub(1),
                b':' if depth == 0 => return Some((&s[..i], &s[i + 1..])),
                _ => {}
            }
        }
        i += 1;
    }
    None
}

/// Recursively decode a Gemma 4 `format_argument`-rendered value into a
/// `serde_json::Value` (iter-231b).
///
///   * `<|"|>...<|"|>`            → `Value::String`
///   * `{k:v,...}`                → `Value::Object` (bare keys, recursive values)
///   * `[v,...]`                  → `Value::Array` (recursive items)
///   * integer / float / bool / null literals → corresponding `Value`
///   * anything else              → `Value::String` fallback (forward the
///     model's intent rather than dropping the field — pre-iter-231b
///     contract for bare unknown values).
fn gemma4_value_to_json(v: &str) -> serde_json::Value {
    let v = v.trim();
    if let Some(stripped) = v
        .strip_prefix("<|\"|>")
        .and_then(|s| s.strip_suffix("<|\"|>"))
    {
        return serde_json::Value::String(stripped.to_string());
    }
    if v.len() >= 2 && v.starts_with('{') && v.ends_with('}') {
        let inner = &v[1..v.len() - 1];
        let mut map = serde_json::Map::new();
        if !inner.trim().is_empty() {
            for kv in split_gemma4_top_level(inner) {
                match split_gemma4_kv_once(kv) {
                    Some((k, val)) => {
                        let key = k.trim();
                        if key.is_empty() {
                            return serde_json::Value::String(v.to_string());
                        }
                        map.insert(key.to_string(), gemma4_value_to_json(val));
                    }
                    // Malformed pair (no colon): preserve the raw text
                    // rather than dropping the field (fallback contract).
                    None => return serde_json::Value::String(v.to_string()),
                }
            }
        }
        return serde_json::Value::Object(map);
    }
    if v.len() >= 2 && v.starts_with('[') && v.ends_with(']') {
        let inner = &v[1..v.len() - 1];
        if inner.trim().is_empty() {
            return serde_json::Value::Array(Vec::new());
        }
        return serde_json::Value::Array(
            split_gemma4_top_level(inner)
                .into_iter()
                .map(gemma4_value_to_json)
                .collect(),
        );
    }
    if let Ok(num) = v.parse::<i64>() {
        return serde_json::Value::from(num);
    }
    if let Ok(num) = v.parse::<f64>() {
        return serde_json::Value::from(num);
    }
    match v {
        "true" => serde_json::Value::Bool(true),
        "false" => serde_json::Value::Bool(false),
        "null" => serde_json::Value::Null,
        // Fallback: treat unquoted bare-value as a string. Better to
        // forward the model's intent than to drop the field.
        _ => serde_json::Value::String(v.to_string()),
    }
}

/// Parse Qwen 3.5/3.6's `<function=NAME>\n<parameter=key>\nval\n</parameter>\n...\n</function>` body.
///
/// Whitespace-tolerant; `<parameter=key>...</parameter>` blocks become args.
fn parse_qwen35_tool_call(body: &str) -> Option<ParsedToolCall> {
    let body = body.trim();
    // Expect `<function=NAME>...</function>`.
    let after_func = body.strip_prefix("<function=")?;
    let name_end = after_func.find('>')?;
    let name = after_func[..name_end].trim().to_string();
    // iter-219b (2026-05-01): reject special-token-polluted names. See the
    // gemma4 sibling for the failure-mode rationale; same OpenAI-spec
    // identifier contract applies to qwen35's `<function=NAME>` extraction.
    if !is_valid_tool_name(&name) {
        return None;
    }
    let after_name_close = &after_func[name_end + 1..];
    let func_close = after_name_close.rfind("</function>")?;
    let inner = after_name_close[..func_close].trim();

    // Walk `<parameter=KEY>VAL</parameter>` blocks.
    let mut args = serde_json::Map::new();
    let mut cursor = 0usize;
    while cursor < inner.len() {
        let Some(rel_open) = inner[cursor..].find("<parameter=") else {
            break;
        };
        let p_open = cursor + rel_open;
        let key_start = p_open + "<parameter=".len();
        let Some(rel_gt) = inner[key_start..].find('>') else {
            break;
        };
        let key_end = key_start + rel_gt;
        let key = inner[key_start..key_end].trim().to_string();
        let val_start = key_end + 1;
        let Some(rel_close) = inner[val_start..].find("</parameter>") else {
            break;
        };
        let val_end = val_start + rel_close;
        let val_raw = inner[val_start..val_end].trim();
        // Try JSON-literal parse first (for numbers/booleans/objects);
        // fall back to plain string. Qwen's template recommends `tojson` on
        // the value, so well-formed JSON is the common case.
        let json_val: serde_json::Value = match serde_json::from_str(val_raw) {
            Ok(v) => v,
            Err(_) => serde_json::Value::String(val_raw.to_string()),
        };
        args.insert(key, json_val);
        cursor = val_end + "</parameter>".len();
    }
    let arguments_json = serde_json::to_string(&serde_json::Value::Object(args)).ok()?;
    Some(ParsedToolCall {
        name,
        arguments_json,
    })
}

// ---------------------------------------------------------------------------
// Reasoning-pair assembly (for non-streaming responses)
// ---------------------------------------------------------------------------

/// Helper: run a `ReasoningSplitter` over the full generated text and
/// return the two split strings. Used by the non-streaming path to populate
/// `message.content` + `message.reasoning_content` on the final response.
/// THE factory for engine-path `ReasoningSplitter` construction
/// (ADR-005 iter-230 B, gate-1 #10). Every generate/stream/embed path
/// builds its splitter here, passing the request's
/// `SamplingParams.reasoning_forced_open`, so a construction site can't
/// silently drop the forced-open seed. Direct
/// `ReasoningSplitter::from_registration*` calls outside registry.rs
/// are grep-pinned away by `iter230_b2_factory_only_construction`.
pub fn make_reasoning_splitter(
    reg: &ModelRegistration,
    forced_open: bool,
) -> Option<ReasoningSplitter> {
    ReasoningSplitter::from_registration_forced(reg, forced_open)
}

/// Does the rendered chat prompt end inside an OPEN reasoning block
/// (ADR-005 iter-230 B decision 1)?
///
/// Rule: the trimmed prompt ends with the registration's reasoning-open
/// marker. The chat template always appends the generation prompt AFTER
/// user content, so the tail is template-controlled — not client-
/// spoofable. Truth table (pinned in tests):
///   * qwen thinking-on  → ends `<think>`      → TRUE
///   * qwen thinking-off → ends `</think>` + ws → FALSE (suppressor)
///   * Gemma thinking-on → ends `<|turn>model`  → FALSE (model emits its
///     own open marker in the completion)
///   * Gemma thinking-off → ends `<channel|>`   → FALSE (closed seed)
pub fn prompt_seeds_reasoning_open(rendered: &str, reg: &ModelRegistration) -> bool {
    match reg.reasoning_open {
        // Both sides trimmed: markers may carry a trailing newline
        // (Gemma's `<|channel>thought\n`), which `trim_end()` on the
        // prompt side would otherwise make unmatchable.
        Some(open) if !open.trim_end().is_empty() => rendered.trim_end().ends_with(open.trim_end()),
        _ => false,
    }
}

pub fn split_full_output(reg: &ModelRegistration, full_text: &str) -> (String, Option<String>) {
    split_full_output_forced(reg, full_text, false)
}

/// `split_full_output` with the iter-230 forced-open seed. The
/// non-streaming assembly path passes the request's
/// `reasoning_forced_open` so a prompt-seeded reasoning span lands in
/// `reasoning_content` instead of leaking (with its close marker) into
/// `content`.
pub fn split_full_output_forced(
    reg: &ModelRegistration,
    full_text: &str,
    forced_open: bool,
) -> (String, Option<String>) {
    let mut splitter = match make_reasoning_splitter(reg, forced_open) {
        Some(s) => s,
        None => return (full_text.to_string(), None),
    };
    let mut content = String::new();
    let mut reasoning = String::new();
    for (slot, frag) in splitter.feed(full_text) {
        match slot {
            SplitSlot::Content => content.push_str(&frag),
            SplitSlot::Reasoning => reasoning.push_str(&frag),
        }
    }
    if let Some((slot, frag)) = splitter.finish() {
        match slot {
            SplitSlot::Content => content.push_str(&frag),
            SplitSlot::Reasoning => reasoning.push_str(&frag),
        }
    }
    (
        content,
        if reasoning.is_empty() {
            None
        } else {
            Some(reasoning)
        },
    )
}

// ---------------------------------------------------------------------------
// Per-model GBNF emitters (T1.8 Option B, ADR-005 Wave 2 W-4)
// ---------------------------------------------------------------------------

// ---------------------------------------------------------------------------
// Emitter error type (Wave 2.5 B1 / B3)
// ---------------------------------------------------------------------------

/// Structured error type returned by the per-model GBNF emitters.
///
/// The `Display` impl produces the human-readable 400-response message that
/// `handlers.rs::compile_tool_grammar` forwards to the API caller.  The
/// `tool_call_gbnf` public entry-point converts this to `String` so the
/// public API surface (`Result<String, String>`) is unchanged.
///
/// Variants:
/// - `TooManyRequiredKeys` — schema's `required` array exceeds the 8-key
///   cap; the O(2^N) permutation grammar would be unreasonably large.
/// - `UnsupportedSchemaFeature` — a nested schema uses a feature the
///   iter-231b recursive compiler cannot enforce (`allOf`, `$ref`/`$defs`,
///   `pattern`, `not`, tuple-form `items`, container `enum` values,
///   depth > 32).  The 400 names the feature and the dot-path.
///
/// # ADR-005 Wave-2.7 design note
/// The 8-key cap is the SOTA hard bound established by json_schema.rs
/// (ANY_ORDER_MAX_REQUIRED = 8, 256 rules worst-case — practical and fast).
/// The previous 16-key cap in this file was misaligned: json_schema.rs
/// hard-errors at >8, so a tool with 9–16 required keys would slip through
/// registry.rs and be silently exposed to O(2^N) grammar growth before
/// json_schema.rs caught it.  Both caps are now 8 — Q3 audit finding fixed.
///
/// # iter-231a/3.7 note
/// The wave-2.5 `UnsupportedSchema` variant (B3 — hard rejection of
/// `array`/`object` parameter types) is REMOVED: structured parameters
/// compile to recursive value rules (iter-231a permissive free-form,
/// iter-231b full-fidelity declared structure) instead of failing the
/// entire request with HTTP 400.  Deleted as a unit per the no-fallback
/// mantra — no call site may re-introduce a scalar-only gate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EmitterError {
    /// `required` array length exceeds `MAX_REQUIRED_KEYS` (8).
    TooManyRequiredKeys { fn_name: String, count: usize },
    /// Nested schema feature the iter-231b recursive compiler cannot
    /// enforce — see variant docs above.
    UnsupportedSchemaFeature {
        fn_name: String,
        param_path: String,
        feature: String,
    },
}

/// Hard cap on the number of required keys for the permutation grammar.
/// Aligned with json_schema.rs ANY_ORDER_MAX_REQUIRED = 8 (ADR-005 W-ζ).
/// Larger schemas return `EmitterError::TooManyRequiredKeys`.
const MAX_REQUIRED_KEYS: usize = 8;

/// iter-231b — recursion depth cap for nested parameter schemas.  JSON
/// Schema cannot self-reference without `$ref` (rejected as an
/// unsupported feature), so nesting is finite; this cap bounds the
/// emitted grammar size against pathological deep schemas.
const MAX_NESTED_DEPTH: usize = 32;

/// iter-231b — property-count cap per nested object, mirroring
/// json_schema.rs's 32-property bound (its `build_unified_inner` has the
/// same shape).  Larger objects return
/// `EmitterError::UnsupportedSchemaFeature`.
const MAX_NESTED_PROPERTIES: usize = 32;

impl std::fmt::Display for EmitterError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EmitterError::TooManyRequiredKeys { fn_name, count } => write!(
                f,
                "function '{}' has {} required parameters; ADR-005 wave-2.7 \
                 limits required keys to {} (SOTA bound: O(2^N) permutation \
                 grammar, 256 rules worst-case); reduce the required set or \
                 split the tool",
                fn_name, count, MAX_REQUIRED_KEYS
            ),
            EmitterError::UnsupportedSchemaFeature {
                fn_name,
                param_path,
                feature,
            } => write!(
                f,
                "function '{}' parameter '{}' uses unsupported schema feature \
                 '{}'; the iter-231b nested compiler supports scalars, enums, \
                 type-unions, anyOf/oneOf, object (properties/required<=8/\
                 additionalProperties) and array (single-schema items); \
                 rewrite the parameter schema or drop the feature",
                fn_name, param_path, feature
            ),
        }
    }
}

/// Escape a literal string for embedding in a GBNF rule — wraps in double
/// quotes and escapes special characters.  Mirrors
/// `grammar::json_schema::format_literal` without importing the grammar crate.
///
/// WHY inlined here: registry.rs has no grammar module dependency by design
/// (it's a registration + parsing module, not a grammar emission module).
/// Duplicating the trivial 10-line escape is preferable to introducing a
/// circular import path.
fn gbnf_literal(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('"');
    for c in s.chars() {
        match c {
            '\r' => out.push_str("\\r"),
            '\n' => out.push_str("\\n"),
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            _ => out.push(c),
        }
    }
    out.push('"');
    out
}

/// Map a JSON Schema type string to the GBNF value rule appropriate for
/// **Gemma 4's kv-list syntax**.
///
/// Gemma 4 string values use the `<|"|>...<|"|>` quote-marker convention
/// (see `models/gemma4/chat_template.jinja:113`): the model never emits a
/// plain JSON `"..."` string inside a tool call — it wraps every string arg
/// in `<|"|>` open + close tokens.  Non-string scalars (numbers, booleans,
/// null) are emitted bare (no JSON quotes) exactly as in standard JSON values.
///
/// WHY NOT reuse json_schema primitives here:
/// json_schema::schema_to_gbnf emits a grammar that matches `"quoted JSON
/// strings"` (double quotes with JSON escape sequences).  Gemma 4's template
/// never emits those — it always uses `<|"|>` markers — so reusing the JSON
/// string grammar would make valid Gemma 4 outputs fail the mask check.
///
/// iter-231a (B3 supersession): `array` and `object` types compile via the
/// iter-231b recursive nested-schema converter (`gemma4_nested_value_rule`).
/// The wave-2.5 B3 hard rejection (`EmitterError::UnsupportedSchema` →
/// HTTP 400) made every tools-bearing request fail against tool schemas
/// with free-form object parameters (MCP servers, nested schemas).
fn gemma4_value_gbnf(
    fn_name: &str,
    param_name: &str,
    schema: &serde_json::Value,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
) -> Result<String, EmitterError> {
    let obj = match schema.as_object() {
        Some(o) => o,
        None => {
            // Untyped / unknown → accept any Gemma value (string, bare
            // scalar, or structured kv-list value).
            return Ok(GEMMA4_TOP_ANY_VAL.to_string());
        }
    };

    // enum (string values only in Gemma 4's canonical use) → literal alternation.
    if let Some(serde_json::Value::Array(values)) = obj.get("enum") {
        let alts: Vec<String> = values
            .iter()
            .filter_map(|v| v.as_str())
            .map(|s| {
                format!(
                    "{} {} {}",
                    gbnf_literal("<|\"|>"),
                    gbnf_literal(s),
                    gbnf_literal("<|\"|>")
                )
            })
            .collect();
        if !alts.is_empty() {
            return Ok(format!("( {} )", alts.join(" | ")));
        }
    }

    let schema_type = obj.get("type").and_then(|t| t.as_str()).unwrap_or("");
    match schema_type {
        "string" => {
            // Gemma 4 string: `<|"|>` + zero-or-more non-marker chars + `<|"|>`.
            // We approximate "non-marker chars" as any char that is not the
            // start of the 5-byte `<|"|>` marker — in practice the grammar
            // sampler enforces this token-by-token; the grammar just needs to
            // be wide enough to accept valid outputs.
            //
            // Rule body: `"<|\"|>" gemma4-str-char* "<|\"|>"`
            // where gemma4-str-char matches any Unicode scalar that is not `<`
            // (the marker opening byte).  This is conservative but correct:
            // string values in Gemma 4 tool calls never contain `<` per the
            // chat template's jinja escape of `<` in string args.
            //
            // iter-231c: `pattern` replaces the generic char* body with the
            // compiled regex between the markers.
            match compile_pattern(
                fn_name,
                &format!("/{}", param_name),
                obj.get("pattern"),
                crate::serve::api::grammar::regex_gbnf::Surface::GemmaMarkerString,
            )? {
                Some(body) => Ok(format!(
                    "{} {} {}",
                    gbnf_literal("<|\"|>"),
                    body,
                    gbnf_literal("<|\"|>")
                )),
                None => Ok("gemma4-str-val".to_string()),
            }
        }
        "integer" => Ok("gemma4-int-val".to_string()),
        "number" => Ok("gemma4-num-val".to_string()),
        "boolean" => Ok("gemma4-bool-val".to_string()),
        "null" => Ok("gemma4-null-val".to_string()),
        // iter-231b: structured types → full-fidelity recursive compiler.
        "array" | "object" => gemma4_nested_value_rule(
            fn_name,
            &format!("/{}", param_name),
            schema,
            rules,
            rule_counter,
            1,
        ),
        _ => {
            // Unrecognised type string — accept any value (conservative).
            Ok(GEMMA4_TOP_ANY_VAL.to_string())
        }
    }
}

/// Top-level value body for untyped / unknown-typed Gemma parameters:
/// the template's `format_argument` renders strings (`<|"|>…<|"|>`),
/// bare scalars, AND structured kv-list values, so all are accepted.
const GEMMA4_TOP_ANY_VAL: &str = "( gemma4-any-val | gemma4-json-obj | gemma4-json-arr )";

/// iter-231b — recursive nested-schema compiler for Gemma 4 tool
/// parameters (`format_argument` kv surface: strings `<|"|>…<|"|>`, bare
/// keys at every nesting level via `escape_keys=False`, comma-separated,
/// no whitespace).
///
/// Same contract as `qwen35_nested_value_rule` — constrain everything the
/// schema DECLARES, stay open where the schema is open:
///
///   * scalars / enums / type-unions / anyOf / oneOf — exact bodies.
///   * `object` with `properties` — declared keys with per-key value
///     grammars; `required` (≤8) enforced any-order via permutation;
///     optional keys follow in a Kleene suffix (top-level contract).
///     `additionalProperties:false` closes the key set; unset/true adds
///     a wildcard kv tail.
///   * `object`/`array` with NO declared shape → the permissive
///     recursive `gemma4-json-obj` / `gemma4-json-arr` rules.
///   * `array` with `items` → typed item grammar; absent → permissive.
///
/// Same `EmitterError::UnsupportedSchemaFeature` rejection set and the
/// same rejection-strength contract as the Qwen compiler (required keys
/// + closed objects are strictly enforced; open objects carry the
/// wildcard extra-kv caveat — see `qwen35_nested_value_rule`).
fn gemma4_nested_value_rule(
    fn_name: &str,
    path: &str,
    schema: &serde_json::Value,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
    depth: usize,
) -> Result<String, EmitterError> {
    if depth > MAX_NESTED_DEPTH {
        return Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: format!("nesting depth > {}", MAX_NESTED_DEPTH),
        });
    }
    let obj = match schema.as_object() {
        Some(o) => o,
        None => return Ok("gemma4-json-val".to_string()),
    };

    for feat in [
        "allOf",
        "$ref",
        "$defs",
        "not",
        "if",
        "then",
        "else",
        "dependentSchemas",
        "patternProperties",
        "propertyNames",
        "contains",
    ] {
        if obj.contains_key(feat) {
            return Err(EmitterError::UnsupportedSchemaFeature {
                fn_name: fn_name.to_string(),
                param_path: path.to_string(),
                feature: feat.to_string(),
            });
        }
    }

    for comb in ["anyOf", "oneOf"] {
        if let Some(serde_json::Value::Array(subs)) = obj.get(comb) {
            if subs.is_empty() {
                return Err(EmitterError::UnsupportedSchemaFeature {
                    fn_name: fn_name.to_string(),
                    param_path: path.to_string(),
                    feature: format!("empty {}", comb),
                });
            }
            let mut alts: Vec<String> = Vec::with_capacity(subs.len());
            for (i, s) in subs.iter().enumerate() {
                alts.push(gemma4_nested_value_rule(
                    fn_name,
                    &format!("{}/{}/{}", path, comb, i),
                    s,
                    rules,
                    rule_counter,
                    depth + 1,
                )?);
            }
            return Ok(format!("( {} )", alts.join(" | ")));
        }
    }

    // enum → literal alternation.  Strings render as `<|"|>s<|"|>`
    // (format_argument string branch); non-string scalars render bare
    // (`1`, `true`, `null` — format_argument's else branch).  Container
    // enum values are rejected (json_schema.rs parity).
    if let Some(serde_json::Value::Array(values)) = obj.get("enum") {
        if values.is_empty() {
            return Err(EmitterError::UnsupportedSchemaFeature {
                fn_name: fn_name.to_string(),
                param_path: path.to_string(),
                feature: "empty enum".to_string(),
            });
        }
        let mut alts: Vec<String> = Vec::with_capacity(values.len());
        for v in values {
            match v {
                serde_json::Value::String(s) => alts.push(format!(
                    "{} {} {}",
                    gbnf_literal("<|\"|>"),
                    gbnf_literal(s),
                    gbnf_literal("<|\"|>")
                )),
                serde_json::Value::Number(_) | serde_json::Value::Bool(_) => {
                    let text = serde_json::to_string(v).map_err(|e| {
                        EmitterError::UnsupportedSchemaFeature {
                            fn_name: fn_name.to_string(),
                            param_path: path.to_string(),
                            feature: format!("enum serialize: {}", e),
                        }
                    })?;
                    alts.push(gbnf_literal(&text));
                }
                serde_json::Value::Null => alts.push(gbnf_literal("null")),
                _ => {
                    return Err(EmitterError::UnsupportedSchemaFeature {
                        fn_name: fn_name.to_string(),
                        param_path: path.to_string(),
                        feature: "container enum value".to_string(),
                    });
                }
            }
        }
        return Ok(format!("( {} )", alts.join(" | ")));
    }

    match obj.get("type") {
        None => Ok("gemma4-json-val".to_string()),
        Some(serde_json::Value::Array(types)) => {
            let mut alts: Vec<String> = Vec::with_capacity(types.len());
            for (i, t) in types.iter().enumerate() {
                let Some(tstr) = t.as_str() else {
                    return Err(EmitterError::UnsupportedSchemaFeature {
                        fn_name: fn_name.to_string(),
                        param_path: path.to_string(),
                        feature: "non-string type union entry".to_string(),
                    });
                };
                let mut stub = serde_json::Map::new();
                stub.insert("type".into(), serde_json::Value::String(tstr.into()));
                alts.push(gemma4_nested_value_rule(
                    fn_name,
                    &format!("{}/type/{}", path, i),
                    &serde_json::Value::Object(stub),
                    rules,
                    rule_counter,
                    depth + 1,
                )?);
            }
            Ok(format!("( {} )", alts.join(" | ")))
        }
        Some(serde_json::Value::String(t)) => match t.as_str() {
            "string" => {
                // iter-231c: `pattern` constrains the marker-string content.
                match compile_pattern(
                    fn_name,
                    path,
                    obj.get("pattern"),
                    crate::serve::api::grammar::regex_gbnf::Surface::GemmaMarkerString,
                )? {
                    Some(body) => Ok(format!(
                        "{} {} {}",
                        gbnf_literal("<|\"|>"),
                        body,
                        gbnf_literal("<|\"|>")
                    )),
                    None => Ok("gemma4-str-val".to_string()),
                }
            }
            "integer" => Ok("gemma4-int-val".to_string()),
            "number" => Ok("gemma4-num-val".to_string()),
            "boolean" => Ok("gemma4-bool-val".to_string()),
            "null" => Ok("gemma4-null-val".to_string()),
            "object" => gemma4_nested_object(fn_name, path, obj, rules, rule_counter, depth),
            "array" => gemma4_nested_array(fn_name, path, obj, rules, rule_counter, depth),
            other => Err(EmitterError::UnsupportedSchemaFeature {
                fn_name: fn_name.to_string(),
                param_path: path.to_string(),
                feature: format!("type '{}'", other),
            }),
        },
        Some(_) => Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: "non-string type".to_string(),
        }),
    }
}

/// iter-231b — nested `object` compiler (Gemma kv surface).  Keys are
/// BARE literals (the template invokes `format_argument` with
/// `escape_keys=False` recursively at every nesting level).
fn gemma4_nested_object(
    fn_name: &str,
    path: &str,
    obj: &serde_json::Map<String, serde_json::Value>,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
    depth: usize,
) -> Result<String, EmitterError> {
    let properties = obj.get("properties").and_then(|p| p.as_object());
    let additional_closed = matches!(
        obj.get("additionalProperties"),
        Some(serde_json::Value::Bool(false))
    );

    let props = match properties {
        Some(p) if !p.is_empty() => p,
        _ => {
            return Ok(if additional_closed {
                r#""{" "}""#.to_string()
            } else {
                "gemma4-json-obj".to_string()
            });
        }
    };

    let required_set: std::collections::HashSet<&str> = obj
        .get("required")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
        .unwrap_or_default();

    if required_set.len() > MAX_REQUIRED_KEYS {
        return Err(EmitterError::TooManyRequiredKeys {
            fn_name: format!("{} (nested {})", fn_name, path),
            count: required_set.len(),
        });
    }
    if props.len() > MAX_NESTED_PROPERTIES {
        return Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: format!("> {} properties", MAX_NESTED_PROPERTIES),
        });
    }

    let mut req_kv: Vec<String> = Vec::new();
    let mut opt_kv: Vec<String> = Vec::new();
    let mut sorted_keys: Vec<&String> = props.keys().collect();
    sorted_keys.sort();
    for key in sorted_keys {
        let val_body = gemma4_nested_value_rule(
            fn_name,
            &format!("{}/properties/{}", path, key),
            &props[key],
            rules,
            rule_counter,
            depth + 1,
        )?;
        *rule_counter += 1;
        let kv_name = format!("g4n-{}-kv", *rule_counter);
        rules.push((
            kv_name.clone(),
            format!("{} \":\" {}", gbnf_literal(key), val_body),
        ));
        if required_set.contains(key.as_str()) {
            req_kv.push(kv_name);
        } else {
            opt_kv.push(kv_name);
        }
    }

    // Wildcard kv for open objects: bare key + any structured value.
    let extra_kv: Option<String> = if additional_closed {
        None
    } else {
        Some(r#"gemma4-json-key ":" gemma4-json-val"#.to_string())
    };

    build_nested_obj_body("g4n", req_kv, opt_kv, extra_kv, rules, rule_counter)
        .map(|inner| format!(r#""{{" {} "}}""#, inner))
}

/// iter-231b — nested `array` compiler (Gemma kv surface).
fn gemma4_nested_array(
    fn_name: &str,
    path: &str,
    obj: &serde_json::Map<String, serde_json::Value>,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
    depth: usize,
) -> Result<String, EmitterError> {
    match obj.get("items") {
        None => Ok("gemma4-json-arr".to_string()),
        Some(serde_json::Value::Object(_)) => {
            let item_rule = gemma4_nested_value_rule(
                fn_name,
                &format!("{}/items", path),
                obj.get("items").expect("items checked above"),
                rules,
                rule_counter,
                depth + 1,
            )?;
            Ok(format!(r#""[" ( {0} ("," {0})* )? "]""#, item_rule))
        }
        Some(serde_json::Value::Array(_)) => Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: "tuple-form items".to_string(),
        }),
        Some(_) => Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: "non-object items".to_string(),
        }),
    }
}

/// Emit a GBNF grammar string constraining output to Gemma 4's
/// `call:NAME{key:val,...}` tool-call wrapper for the given function and
/// parameters schema.
///
/// The Gemma 4 chat template's `tool_call` macro (jinja:113-200) emits:
///   `call:FUNCTION_NAME{param_name:<|"|>string_val<|"|>,count:42,...}`
///
/// So the grammar has three structural layers:
///   1. A fixed prefix: the literal `call:NAME{`
///   2. A kv-list body: comma-separated `KEY:VALUE` pairs (required in any
///      order; optional may appear after; duplicates structurally rejected by
///      the required-permutation grammar).
///   3. A fixed suffix: `}`
///
/// # Required parameter enforcement (Wave 2.5 B1)
///
/// If `params_schema` has a `required` array those keys are enforced via a
/// permutation grammar: required keys MUST all appear in any order; omitting
/// one causes the grammar stack to die.  Optional keys follow in a
/// Kleene-star suffix.  Hard cap `MAX_REQUIRED_KEYS` (8) prevents O(2^N)
/// grammar blowup.
///
/// # Structured parameters (iter-231a, supersedes Wave 2.5 B3)
///
/// Parameters typed `array` or `object` compile to the permissive
/// recursive `gemma4-json-arr` / `gemma4-json-obj` rules — contents
/// unconstrained, structure constrained.  (Wave 2.5 B3 rejected these
/// with `EmitterError::UnsupportedSchema` → HTTP 400; that gate broke
/// every tool schema carrying free-form object params, e.g. MCP tools.)
fn gemma4_tool_call_gbnf(
    fn_name: &str,
    params_schema: &serde_json::Value,
    shape: GrammarShape,
) -> Result<String, EmitterError> {
    let mut rules: Vec<(String, String)> = Vec::new();
    let mut rule_counter: u32 = 0;

    // Gemma 4 primitive rules (shared across all function grammars).
    //
    // String: `<|"|>` any-safe-char* `<|"|>`. We define gemma4-str-char as
    // any character that is NOT `<` (the first byte of the 5-byte marker
    // `<|"|>`). This is conservative but safe — Gemma 4's jinja template
    // HTML-escapes `<` in string args so valid model outputs never contain
    // bare `<` inside string values.
    rules.push((
        "gemma4-str-char".to_string(),
        r#"[^<\\] | [\\] [^\x00-\x1F]"#.to_string(),
    ));
    rules.push((
        "gemma4-str-val".to_string(),
        format!(
            "{} gemma4-str-char* {}",
            gbnf_literal("<|\"|>"),
            gbnf_literal("<|\"|>")
        ),
    ));
    rules.push((
        "gemma4-int-val".to_string(),
        r#""-"? ([0] | [1-9] [0-9]{0,15})"#.to_string(),
    ));
    rules.push((
        "gemma4-num-val".to_string(),
        r#""-"? ([0] | [1-9] [0-9]{0,15}) ("." [0-9]{1,16})? ([eE] [-+]? [0-9]{1,16})?"#
            .to_string(),
    ));
    rules.push((
        "gemma4-bool-val".to_string(),
        r#""true" | "false""#.to_string(),
    ));
    rules.push(("gemma4-null-val".to_string(), r#""null""#.to_string()));
    rules.push((
        "gemma4-any-val".to_string(),
        r#"gemma4-str-val | gemma4-num-val | gemma4-bool-val | gemma4-null-val"#.to_string(),
    ));

    // iter-231a (B3 supersession): permissive recursive kv-list rules for
    // `object` / `array` parameters.  The chat template's
    // `format_argument(value, escape_keys=False)` macro
    // (test_fixtures/gemma4-apex-embedded-chat-template.jinja:111-140,
    // invoked from :198 with `escape_keys=False` propagated recursively)
    // renders structured args as:
    //   * object  → `{key:val,...}`   — keys BARE at every nesting level
    //   * array   → `[val,...]`
    //   * string  → `<|"|>s<|"|>`     (= gemma4-str-val)
    //   * bool/num/null → bare        (= existing scalar rules)
    //
    // `gemma4-json-key` matches bare keys: any run of chars that cannot
    // collide with the kv-list structure (`,` `:` `{` `}` `[` `]`) or the
    // `<tool_call|>` close marker (`<`) — same conservative-charset
    // contract as `gemma4-str-char`.
    //
    // Same supersession rationale as the Qwen emitter: the grammar still
    // constrains call structure (function name, declared param keys,
    // kv-list layout, scalar types) but treats the CONTENTS of
    // object/array parameters as "any well-formed kv-list value", ending
    // the wave-2.5 `EmitterError::UnsupportedSchema` → HTTP 400 hard
    // failure on real-world tool schemas (MCP free-form objects).
    rules.push((
        "gemma4-json-key".to_string(),
        r#"[^,:{}\[\]<]+"#.to_string(),
    ));
    rules.push((
        "gemma4-json-obj".to_string(),
        r#""{" ("}" | gemma4-json-key ":" gemma4-json-val ("," gemma4-json-key ":" gemma4-json-val)* "}")"#.to_string(),
    ));
    rules.push((
        "gemma4-json-arr".to_string(),
        r#""[" ("]" | gemma4-json-val ("," gemma4-json-val)* "]")"#.to_string(),
    ));
    rules.push((
        "gemma4-json-val".to_string(),
        "gemma4-str-val | gemma4-num-val | gemma4-bool-val | gemma4-null-val | gemma4-json-obj | gemma4-json-arr".to_string(),
    ));

    // Extract `required` set (Wave 2.5 B1).
    let required_set: std::collections::HashSet<String> = params_schema
        .as_object()
        .and_then(|o| o.get("required"))
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    if required_set.len() > MAX_REQUIRED_KEYS {
        return Err(EmitterError::TooManyRequiredKeys {
            fn_name: fn_name.to_string(),
            count: required_set.len(),
        });
    }

    let properties = params_schema
        .as_object()
        .and_then(|o| o.get("properties"))
        .and_then(|p| p.as_object());

    let prefix_lit = gbnf_literal(&format!("call:{}", fn_name));
    let open_lit = gbnf_literal("{");
    let close_lit = gbnf_literal("}");
    let comma_lit = gbnf_literal(",");

    // Build the per-call body (shape-independent).  The `single_body`
    // string is the GBNF expression that matches exactly one Gemma 4
    // tool-call body (`call:NAME{kv-list}`), with no enclosing markers.
    // The shape selector below wraps it in either the body-only
    // (SingleBody) or marker-wrapped + repeat (OneOrMoreCalls) shape.
    let single_body: String = if let Some(props) = properties {
        if props.is_empty() {
            format!("{} {} {}", prefix_lit, open_lit, close_lit)
        } else {
            let mut required_kv_names: Vec<String> = Vec::new();
            let mut optional_kv_names: Vec<String> = Vec::new();
            let mut sorted_keys: Vec<&String> = props.keys().collect();
            sorted_keys.sort();
            for key in &sorted_keys {
                let val_schema = &props[*key];
                // iter-231a: array/object map to permissive json rules.
                let val_rule = gemma4_value_gbnf(
                    fn_name,
                    key.as_str(),
                    val_schema,
                    &mut rules,
                    &mut rule_counter,
                )?;
                let key_lit = gbnf_literal(key.as_str());
                let kv_body = format!("{} {} {}", key_lit, gbnf_literal(":"), val_rule);
                let kv_name = format!("gemma4-kv-{}", sanitize_rule_name_local(key));
                rules.push((kv_name.clone(), kv_body));
                if required_set.contains(*key) {
                    required_kv_names.push(kv_name);
                } else {
                    optional_kv_names.push(kv_name);
                }
            }

            // Build kv-list body.
            //
            // Case A (no required): pure Kleene-star over all kv items.
            // Case B (required):  permutation grammar for required keys,
            //   followed by optional Kleene-star for optional keys.
            //
            // WHY permutation for required: parse_gemma4_tool_call is
            // order-agnostic, so enforcing a fixed required order would reject
            // valid model outputs that sequence required keys differently.
            let kv_body_rule = if required_kv_names.is_empty() {
                // Case A.
                let all_names: Vec<String> = optional_kv_names.clone();
                let alts = all_names.join(" | ");
                let kv_item_rule = "gemma4-kv-item".to_string();
                rules.push((kv_item_rule.clone(), format!("( {} )", alts)));
                let kv_list_rule = "gemma4-kv-list".to_string();
                rules.push((
                    kv_list_rule.clone(),
                    format!("{} ( {} {} )*", kv_item_rule, comma_lit, kv_item_rule),
                ));
                kv_list_rule
            } else {
                // Case B.
                let req_top = build_gemma4_required_permutation(
                    fn_name,
                    &required_kv_names,
                    &comma_lit,
                    &mut rules,
                );
                if optional_kv_names.is_empty() {
                    req_top
                } else {
                    let alts = optional_kv_names.join(" | ");
                    let opt_item_rule = "gemma4-opt-item".to_string();
                    rules.push((opt_item_rule.clone(), format!("( {} )", alts)));
                    let kv_list_rule = "gemma4-kv-list".to_string();
                    rules.push((
                        kv_list_rule.clone(),
                        format!("{} ( {} {} )*", req_top, comma_lit, opt_item_rule),
                    ));
                    kv_list_rule
                }
            };

            format!("{} {} {} {}", prefix_lit, open_lit, kv_body_rule, close_lit)
        }
    } else {
        rules.push(("gemma4-any-kv-char".to_string(), r#"[^}]"#.to_string()));
        format!(
            "{} {} gemma4-any-kv-char* {}",
            prefix_lit, open_lit, close_lit
        )
    };

    // Wave 2.7 W-η + Wave 3.5 HIGH-1: select root rule per `shape`.
    //
    //   * `SingleBody`                       → body-only root (single
    //     call, no markers; legacy lazy path).
    //   * `OneOrMoreCalls{p}`                → wrap body with Gemma 4
    //     marker pair `<|tool_call>` / `<tool_call|>` (verbatim from
    //     models/gemma4/chat_template.jinja:189-205) and repeat per
    //     `parallel`.  No separator: chat_template emits calls 2+
    //     immediately after the previous call's close marker.
    //   * `OneOrMoreCallsBodyOnly{p}`        → Wave 3.5 HIGH-1 Auto-lazy
    //     variant.  Strips the FIRST open marker (consumed by the
    //     awaiting_trigger no-op gate before the grammar is engaged).
    //     Single: `body close_marker`; parallel:
    //     `body close_marker ( open_marker body close_marker )* space`.
    //     See `GrammarShape::OneOrMoreCallsBodyOnly` doc-comment for the
    //     production-order rationale.
    // iter-219b grammar-exhaust fix (2026-05-01): drop trailing ` space`
    // from all root_body shapes. The `space` rule
    // (`| " " | "\n"{1,2} [ \t]{0,20}`) was inherited from llama.cpp's
    // SPACE_RULE convention for JSON Schema grammars where it terminates
    // value rules. For tool-call grammars it served as a trailing-
    // whitespace allowance after the close marker — but its empty-alt +
    // `[ \t]{0,20}` (min 0) tail kept `is_dead` from ever flipping
    // post-close (Agent C audit 2026-05-01,
    // `docs/research/iter219b-grammar-exhaust-audit-2026-05-01.md`),
    // breaking iter-218's claimed "natural grammar-exhaust" termination.
    // Without the trailing `space`, the grammar exhausts cleanly on the
    // close marker; the engine's `is_dead`-break path at engine.rs:5045-5059
    // then fires on the next sampled byte. Per chat-template inspection
    // (regex at tokenizer_config.json: `<|tool_call>...<tool_call|><turn|>?`),
    // the model is trained to emit `<turn|>` (which is in eos_token_ids)
    // immediately after `<tool_call|>` with no separating whitespace, so
    // the trailing-whitespace allowance was never load-bearing for the
    // happy path.
    let root_body = match shape {
        GrammarShape::SingleBody => single_body.clone(),
        GrammarShape::OneOrMoreCalls { parallel } => {
            let open_marker = gbnf_literal("<|tool_call>");
            let close_marker = gbnf_literal("<tool_call|>");
            let g4_call_rule = "gemma4-call".to_string();
            rules.push((
                g4_call_rule.clone(),
                format!("{} {} {}", open_marker, single_body, close_marker),
            ));
            // `(call)+` GBNF idiom: `call call*` — at least one, optional
            // repeat.  Mirrors llama.cpp `p.repeat(call, 1, parallel?-1:1)`
            // at common/chat.cpp:898-902, 1177-1181.
            if parallel {
                format!("{} {}*", g4_call_rule, g4_call_rule)
            } else {
                g4_call_rule
            }
        }
        GrammarShape::OneOrMoreCallsBodyOnly { parallel } => {
            // Wave 3.5 HIGH-1: leading open marker is stripped (consumed
            // by the awaiting_trigger gate before the grammar fires).
            // The trailing close marker IS in the grammar — those bytes
            // flow through `accept_bytes` once the runtime is eager.
            let open_marker = gbnf_literal("<|tool_call>");
            let close_marker = gbnf_literal("<tool_call|>");
            if parallel {
                // First call: body close — no leading open.  Subsequent
                // calls: full open+body+close, no inter-call separator
                // (chat_template.jinja:189-205 emits calls back-to-back).
                let g4_call_rule = "gemma4-call".to_string();
                rules.push((
                    g4_call_rule.clone(),
                    format!("{} {} {}", open_marker, single_body, close_marker),
                ));
                format!("{} {} {}*", single_body, close_marker, g4_call_rule)
            } else {
                format!("{} {}", single_body, close_marker)
            }
        }
    };
    rules.push(("root".to_string(), root_body));

    let mut out = String::new();
    for (name, body) in &rules {
        if name == "root" {
            out.push_str(&format!("root ::= {}\n", body));
            break;
        }
    }
    for (name, body) in &rules {
        if name != "root" {
            out.push_str(&format!("{} ::= {}\n", name, body));
        }
    }
    Ok(out)
}

/// Build the any-order permutation grammar for a non-empty set of required
/// Gemma kv-rule names. Returns the name of the top-level permutation rule.
///
/// Mirrors `json_schema::build_required_permutation` but uses Gemma's bare
/// comma separator.  Rule names encode the sorted kv names so each distinct
/// subset is emitted exactly once (memoized via the rules vec).
fn build_gemma4_required_permutation(
    slug: &str,
    required_kv_names: &[String],
    comma_lit: &str,
    rules: &mut Vec<(String, String)>,
) -> String {
    let mut sorted = required_kv_names.to_vec();
    sorted.sort();

    let name_parts: Vec<String> = sorted
        .iter()
        .map(|n| n.trim_start_matches("gemma4-kv-").to_string())
        .collect();
    // Truncate the rule name to avoid hitting GBNF parser limits for large
    // key sets; the sorted join is unique enough within a single function.
    let rule_name = format!(
        "g4req-{}-{}",
        sanitize_rule_name_local(slug),
        name_parts.join("-")
    );

    if rules.iter().any(|(n, _)| n == &rule_name) {
        return rule_name;
    }

    if sorted.len() == 1 {
        rules.push((rule_name.clone(), sorted[0].clone()));
        return rule_name;
    }

    // Insert placeholder to allow memoization check in recursive calls.
    rules.push((rule_name.clone(), String::new()));

    let mut alts: Vec<String> = Vec::new();
    for (i, kv_name) in sorted.iter().enumerate() {
        let remaining: Vec<String> = sorted
            .iter()
            .enumerate()
            .filter(|(j, _)| *j != i)
            .map(|(_, s)| s.clone())
            .collect();
        let rest = build_gemma4_required_permutation(slug, &remaining, comma_lit, rules);
        alts.push(format!("{} {} {}", kv_name, comma_lit, rest));
    }
    let body = alts.join(" | ");
    for (n, b) in rules.iter_mut() {
        if n == &rule_name {
            *b = body;
            break;
        }
    }
    rule_name
}

/// Emit a GBNF grammar string constraining output to Qwen 3.5/3.6's
/// `<function=NAME><parameter=key>val</parameter>...</function>` wrapper.
///
/// The Qwen 3.5/3.6 chat template emits tool calls as (verified against
/// `tokenizer_config.json` `chat_template` field 2026-04-26):
///   `<function=NAME>\n<parameter=KEY>\nVAL\n</parameter>\n...</function>`
///
/// Every `</parameter>` is followed by a newline — including the last one
/// before `</function>`.  The grammar enforces this exactly.
///
/// # Required parameter enforcement (Wave 2.5 B1)
///
/// Same as Gemma 4: required keys enforced via permutation grammar; optional
/// keys in Kleene-star suffix.  Hard cap `MAX_REQUIRED_KEYS` (8).
///
/// # Structured parameters (iter-231a, supersedes Wave 2.5 B3)
///
/// Parameters typed `array` or `object` compile to the permissive
/// recursive `qwen35-json-arr` / `qwen35-json-obj` rules — contents
/// unconstrained, structure constrained.  (Wave 2.5 B3 rejected these
/// with `EmitterError::UnsupportedSchema` → HTTP 400; that gate broke
/// every tool schema carrying free-form object params, e.g. MCP tools.)
fn qwen35_tool_call_gbnf(
    fn_name: &str,
    params_schema: &serde_json::Value,
    shape: GrammarShape,
) -> Result<String, EmitterError> {
    let mut rules: Vec<(String, String)> = Vec::new();

    // Qwen 3.5/3.6 value primitives — values sit between XML tags, raw text
    // (no JSON quoting for strings).  Numbers/booleans are JSON-serialized
    // (the `tojson` Jinja filter is used in the template).
    rules.push((
        "qwen35-str-char".to_string(),
        // Any char that is not `<` (first byte of `</parameter>`).
        // Conservative but correct: template HTML-escapes `<` in string values.
        r#"[^<\\] | [\\] [^\x00-\x1F]"#.to_string(),
    ));
    rules.push(("qwen35-str-val".to_string(), "qwen35-str-char*".to_string()));
    rules.push((
        "qwen35-int-val".to_string(),
        r#""-"? ([0] | [1-9] [0-9]{0,15})"#.to_string(),
    ));
    rules.push((
        "qwen35-num-val".to_string(),
        r#""-"? ([0] | [1-9] [0-9]{0,15}) ("." [0-9]{1,16})? ([eE] [-+]? [0-9]{1,16})?"#
            .to_string(),
    ));
    rules.push((
        "qwen35-bool-val".to_string(),
        r#""true" | "false""#.to_string(),
    ));
    rules.push(("qwen35-null-val".to_string(), r#""null""#.to_string()));
    rules.push((
        "qwen35-any-val".to_string(),
        r#"qwen35-str-val | qwen35-num-val | qwen35-bool-val | qwen35-null-val"#.to_string(),
    ));

    // iter-231a (B3 supersession): permissive recursive JSON rules for
    // `object` / `array` parameters.  The chat template renders every
    // non-string argument via the `tojson` filter
    // (`serde_json::to_string` — compact, NO whitespace, `<` NOT escaped;
    // src/serve/mod.rs `build_chat_template_env`), so the value grammar is
    // compact-JSON-shaped:
    //
    //   * `qwen35-json-char` excludes `<` for the same reason
    //     `qwen35-str-char` does: a string value must never be able to
    //     swallow the `</parameter>` close tag.  The model can always
    //     `\<` escape a literal `<` if it truly needs one.
    //   * `qwen35-json-obj` / `qwen35-json-arr` are mutually recursive
    //     with `qwen35-json-val` (GBNF supports recursion — same idiom as
    //     json_schema.rs's `value`/`object`/`array` primitives).
    //   * Object keys are JSON strings (serde emits them quoted).
    //   * Numbers reuse `qwen35-num-val` (covers ints + floats).
    //
    // These rules are a deliberate SUPERSET of any nested schema: the
    // grammar constrains the call structure (function name, parameter
    // keys, tag layout, scalar types) but treats the CONTENTS of
    // object/array parameters as "any well-formed JSON".  Real-world
    // tool schemas (e.g. MCP servers exposing free-form `config` /
    // `arguments` objects) previously hard-failed the entire request
    // with `EmitterError::UnsupportedSchema` → HTTP 400.
    rules.push((
        "qwen35-json-char".to_string(),
        r#"[^<"\\\x00-\x1F] | [\\] (["\\/bfnrt] | [u] [0-9a-fA-F]{4})"#.to_string(),
    ));
    rules.push((
        "qwen35-json-str".to_string(),
        r#""\"" qwen35-json-char* "\"""#.to_string(),
    ));
    rules.push((
        "qwen35-json-obj".to_string(),
        r#""{" ("}" | qwen35-json-str ":" qwen35-json-val ("," qwen35-json-str ":" qwen35-json-val)* "}")"#.to_string(),
    ));
    rules.push((
        "qwen35-json-arr".to_string(),
        r#""[" ("]" | qwen35-json-val ("," qwen35-json-val)* "]")"#.to_string(),
    ));
    rules.push((
        "qwen35-json-val".to_string(),
        "qwen35-json-str | qwen35-num-val | qwen35-bool-val | qwen35-null-val | qwen35-json-obj | qwen35-json-arr".to_string(),
    ));

    // Extract `required` set (Wave 2.5 B1).
    let required_set: std::collections::HashSet<String> = params_schema
        .as_object()
        .and_then(|o| o.get("required"))
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    if required_set.len() > MAX_REQUIRED_KEYS {
        return Err(EmitterError::TooManyRequiredKeys {
            fn_name: fn_name.to_string(),
            count: required_set.len(),
        });
    }

    let properties = params_schema
        .as_object()
        .and_then(|o| o.get("properties"))
        .and_then(|p| p.as_object());

    let func_open_lit = gbnf_literal(&format!("<function={}>", fn_name));
    let func_close_lit = gbnf_literal("</function>");
    let newline_lit = gbnf_literal("\n");

    // Build the per-call body (shape-independent).  `single_body` is the
    // GBNF expression for exactly one Qwen 3.5/3.6 tool-call body
    // (`<function=NAME>...\n</function>`).  The shape selector below
    // wraps it in either the body-only (SingleBody) or marker-wrapped +
    // repeat (OneOrMoreCalls) shape.
    let single_body: String = if let Some(props) = properties {
        if props.is_empty() {
            format!("{} {}", func_open_lit, func_close_lit)
        } else {
            let mut required_block_names: Vec<String> = Vec::new();
            let mut optional_block_names: Vec<String> = Vec::new();
            let mut rule_counter: u32 = 0;
            let mut sorted_keys: Vec<&String> = props.keys().collect();
            sorted_keys.sort();
            for key in &sorted_keys {
                let val_schema = &props[*key];
                // iter-231b: array/object compile via the recursive
                // nested-schema converter (full declared-structure
                // fidelity; free-form shapes stay permissive).
                let val_rule = qwen35_value_rule(
                    fn_name,
                    key.as_str(),
                    val_schema,
                    &mut rules,
                    &mut rule_counter,
                )?;
                let param_open_lit = gbnf_literal(&format!("<parameter={}>", key));
                let param_close_lit = gbnf_literal("</parameter>");
                // Block form confirmed against tokenizer_config.json chat_template:
                //   `<parameter=KEY>\nVAL\n</parameter>\n`
                // Every </parameter> — including the last before </function> —
                // is followed by \n.  The template loop emits
                //   `{{- '\n</parameter>\n' }}` unconditionally.
                let block_body = format!(
                    "{} {} {} {} {} {}",
                    param_open_lit,
                    newline_lit,
                    val_rule,
                    newline_lit,
                    param_close_lit,
                    newline_lit
                );
                let block_name = format!("qwen35-param-{}", sanitize_rule_name_local(key));
                rules.push((block_name.clone(), block_body));
                if required_set.contains(*key) {
                    required_block_names.push(block_name);
                } else {
                    optional_block_names.push(block_name);
                }
            }

            // Build parameter sequence with B1 required enforcement.
            // Same two-case logic as Gemma 4: permutation for required, then
            // Kleene-star for optional.
            let param_body_rule = if required_block_names.is_empty() {
                // Case A: pure optional Kleene-star.
                let alts = optional_block_names.join(" | ");
                let param_item_rule = "qwen35-param-item".to_string();
                rules.push((param_item_rule.clone(), format!("( {} )", alts)));
                let param_list_rule = "qwen35-param-list".to_string();
                rules.push((param_list_rule.clone(), format!("{}*", param_item_rule)));
                param_list_rule
            } else {
                // Case B: required permutation + optional suffix.
                let req_top =
                    build_qwen35_required_permutation(fn_name, &required_block_names, &mut rules);
                if optional_block_names.is_empty() {
                    req_top
                } else {
                    let alts = optional_block_names.join(" | ");
                    let opt_item_rule = "qwen35-opt-item".to_string();
                    rules.push((opt_item_rule.clone(), format!("( {} )", alts)));
                    let param_list_rule = "qwen35-param-list".to_string();
                    rules.push((
                        param_list_rule.clone(),
                        format!("{} {}*", req_top, opt_item_rule),
                    ));
                    param_list_rule
                }
            };

            // Body: `<function=NAME>\n` + param sequence + `</function>`.
            // The newline after `<function=NAME>` is part of the template
            // emission pattern (verified from tokenizer_config.json).
            format!(
                "{} {} {} {}",
                func_open_lit, newline_lit, param_body_rule, func_close_lit
            )
        }
    } else {
        rules.push((
            "qwen35-inner-char".to_string(),
            r#"[^<\\] | [\\] [^\x00-\x1F]"#.to_string(),
        ));
        format!("{} qwen35-inner-char* {}", func_open_lit, func_close_lit)
    };

    // Wave 2.7 W-η + Wave 3.5 HIGH-1: select root rule per `shape`.
    //
    //   * `SingleBody`                       → body-only root (single
    //     call, no markers; legacy lazy path).
    //   * `OneOrMoreCalls{p}`                → wrap body with Qwen
    //     3.5/3.6 marker pair `<tool_call>\n` / `\n</tool_call>`
    //     (verbatim from
    //     models/qwen3.6-27b-dwq46/tokenizer_config.json:285+) and
    //     repeat per `parallel`.  Calls 2+ are separated by a literal
    //     `\n` per the chat_template's `{%- else %}{{- '\n<tool_call>\n...
    //     ' }}` branch.
    //   * `OneOrMoreCallsBodyOnly{p}`        → Wave 3.5 HIGH-1 Auto-lazy
    //     variant.  Strips the FIRST open marker (consumed by the
    //     awaiting_trigger no-op gate before the grammar is engaged).
    //     Single: `body \n close_marker`; parallel:
    //     `body \n close_marker ( \n open_marker \n body \n close_marker )* space`.
    //     See `GrammarShape::OneOrMoreCallsBodyOnly` doc-comment for the
    //     production-order rationale.
    // iter-219b grammar-exhaust fix (2026-05-01): drop trailing ` space`
    // from all root_body shapes (sibling to the gemma4 emitter above; see
    // its block-comment for full rationale + Agent C audit citation).
    let root_body = match shape {
        GrammarShape::SingleBody => single_body.clone(),
        GrammarShape::OneOrMoreCalls { parallel } => {
            let open_marker = gbnf_literal("<tool_call>");
            let close_marker = gbnf_literal("</tool_call>");
            let qwen_call_rule = "qwen35-call".to_string();
            // Full call shape per chat_template:
            //   `<tool_call>\n<function=NAME>\n...\n</function>\n</tool_call>`
            // (single_body already starts with `<function=NAME>\n` and ends
            // with `</function>` — we add the surrounding `<tool_call>\n` and
            // `\n</tool_call>`).
            rules.push((
                qwen_call_rule.clone(),
                format!(
                    "{} {} {} {} {}",
                    open_marker, newline_lit, single_body, newline_lit, close_marker
                ),
            ));
            if parallel {
                // `call ("\n" call)*` — Qwen separates calls 2+ with literal `\n`
                // (template's loop "else" branch — see citation above).
                format!("{} ( {} {} )*", qwen_call_rule, newline_lit, qwen_call_rule)
            } else {
                qwen_call_rule
            }
        }
        GrammarShape::OneOrMoreCallsBodyOnly { parallel } => {
            // Wave 3.5 HIGH-1: leading open marker is stripped (consumed
            // by the awaiting_trigger gate before the grammar fires).
            // The trailing close marker IS in the grammar — those bytes
            // flow through `accept_bytes` once the runtime is eager.
            let open_marker = gbnf_literal("<tool_call>");
            let close_marker = gbnf_literal("</tool_call>");
            if parallel {
                // First call: `body \n close_marker` (no leading
                // `<tool_call>\n`).  Subsequent calls: full
                // `\n <tool_call> \n body \n </tool_call>` (matches the
                // chat_template loop's `\n<tool_call>\n...\n</tool_call>`
                // separator pattern).
                let qwen_call_rule = "qwen35-call".to_string();
                rules.push((
                    qwen_call_rule.clone(),
                    format!(
                        "{} {} {} {} {}",
                        open_marker, newline_lit, single_body, newline_lit, close_marker
                    ),
                ));
                format!(
                    "{} {} {} ( {} {} )*",
                    single_body, newline_lit, close_marker, newline_lit, qwen_call_rule
                )
            } else {
                // Single call: body + `\n</tool_call>` (close marker
                // preceded by `\n` per the template emission pattern).
                format!("{} {} {}", single_body, newline_lit, close_marker)
            }
        }
    };
    rules.push(("root".to_string(), root_body));

    let mut out = String::new();
    for (name, body) in &rules {
        if name == "root" {
            out.push_str(&format!("root ::= {}\n", body));
            break;
        }
    }
    for (name, body) in &rules {
        if name != "root" {
            out.push_str(&format!("{} ::= {}\n", name, body));
        }
    }
    Ok(out)
}

/// Emit DeepSeek-V4's native DSML tool-call syntax. The outer marker pair
/// contains one or more invoke elements; parameter names are restricted to
/// the declared schema and non-string values are constrained to valid JSON.
fn deepseek4_tool_call_gbnf(
    fn_name: &str,
    params_schema: &serde_json::Value,
    shape: GrammarShape,
) -> Result<String, EmitterError> {
    let mut rules: Vec<(String, String)> = vec![
        (
            "dsml-json-char".into(),
            r#"[^"\\\x00-\x1F] | [\\] (["\\/bfnrt] | "u" [0-9a-fA-F]{4})"#.into(),
        ),
        (
            "dsml-json-str".into(),
            r#""\"" dsml-json-char* "\"""#.into(),
        ),
        (
            "dsml-json-num".into(),
            r#""-"? ([0] | [1-9] [0-9]{0,15}) ("." [0-9]{1,16})? ([eE] [-+]? [0-9]{1,16})?"#.into(),
        ),
        (
            "dsml-json-obj".into(),
            r#""{" ("}" | dsml-json-str ":" dsml-json-val ("," dsml-json-str ":" dsml-json-val)* "}")"#.into(),
        ),
        (
            "dsml-json-arr".into(),
            r#""[" ("]" | dsml-json-val ("," dsml-json-val)* "]")"#.into(),
        ),
        (
            "dsml-json-val".into(),
            r#"dsml-json-str | dsml-json-num | "true" | "false" | "null" | dsml-json-obj | dsml-json-arr"#.into(),
        ),
        (
            "dsml-string-char".into(),
            // `<` begins the closing DSML parameter tag. Backslash escapes
            // remain allowed so ordinary source-code/path arguments work.
            r#"[^<\\] | [\\] [^\x00-\x1F]"#.into(),
        ),
        ("dsml-string-val".into(), "dsml-string-char*".into()),
    ];

    let newline = gbnf_literal("\n");
    let parameter_close = gbnf_literal("</|DSML|parameter>");
    let required_set: std::collections::HashSet<String> = params_schema
        .as_object()
        .and_then(|object| object.get("required"))
        .and_then(serde_json::Value::as_array)
        .map(|items| {
            items
                .iter()
                .filter_map(serde_json::Value::as_str)
                .map(ToOwned::to_owned)
                .collect()
        })
        .unwrap_or_default();
    if required_set.len() > MAX_REQUIRED_KEYS {
        return Err(EmitterError::TooManyRequiredKeys {
            fn_name: fn_name.to_string(),
            count: required_set.len(),
        });
    }

    let mut required_parameter_rules = Vec::new();
    let mut optional_parameter_rules = Vec::new();
    if let Some(properties) = params_schema
        .as_object()
        .and_then(|object| object.get("properties"))
        .and_then(serde_json::Value::as_object)
    {
        let mut keys = properties.keys().collect::<Vec<_>>();
        keys.sort();
        for key in keys {
            let schema = &properties[key];
            let is_string = schema
                .get("type")
                .and_then(serde_json::Value::as_str)
                .is_some_and(|kind| kind == "string");
            let value_rule = if is_string {
                "dsml-string-val"
            } else {
                "dsml-json-val"
            };
            let open = gbnf_literal(&format!(
                "<|DSML|parameter name=\"{}\" string=\"{}\">",
                key,
                if is_string { "true" } else { "false" }
            ));
            let rule_name = format!("dsml-param-{}", sanitize_rule_name_local(key));
            rules.push((
                rule_name.clone(),
                format!("{} {} {} {}", open, value_rule, parameter_close, newline),
            ));
            if required_set.contains(key.as_str()) {
                required_parameter_rules.push(rule_name);
            } else {
                optional_parameter_rules.push(rule_name);
            }
        }
    }
    let parameter_sequence =
        if required_parameter_rules.is_empty() && optional_parameter_rules.is_empty() {
            None
        } else if required_parameter_rules.is_empty() {
            let item = "dsml-optional-param".to_string();
            rules.push((
                item.clone(),
                format!("( {} )", optional_parameter_rules.join(" | ")),
            ));
            let list = "dsml-param-list".to_string();
            rules.push((list.clone(), format!("{}*", item)));
            Some(list)
        } else {
            let required =
                build_dsml_required_permutation(fn_name, &required_parameter_rules, &mut rules);
            if optional_parameter_rules.is_empty() {
                Some(required)
            } else {
                let item = "dsml-optional-param".to_string();
                rules.push((
                    item.clone(),
                    format!("( {} )", optional_parameter_rules.join(" | ")),
                ));
                let list = "dsml-param-list".to_string();
                rules.push((list.clone(), format!("{} {}*", required, item)));
                Some(list)
            }
        };

    let invoke_open = gbnf_literal(&format!("<|DSML|invoke name=\"{}\">", fn_name));
    let invoke_close = gbnf_literal("</|DSML|invoke>");
    let invoke = if let Some(parameters) = parameter_sequence {
        format!(
            "{} {} {} {}",
            invoke_open, newline, parameters, invoke_close
        )
    } else {
        // The official formatter emits one blank line for an empty argument
        // map: `<invoke>\n\n</invoke>`.
        format!("{} {} {} {}", invoke_open, newline, newline, invoke_close)
    };
    rules.push(("dsml-invoke".into(), invoke));

    let open = gbnf_literal("<|DSML|tool_calls>");
    let close = gbnf_literal("</|DSML|tool_calls>");
    let full_body = match shape {
        GrammarShape::SingleBody => "dsml-invoke".to_string(),
        GrammarShape::OneOrMoreCalls { parallel } => {
            let invokes = if parallel {
                format!("dsml-invoke ( {} dsml-invoke )*", newline)
            } else {
                "dsml-invoke".to_string()
            };
            format!("{} {} {} {} {}", open, newline, invokes, newline, close)
        }
        GrammarShape::OneOrMoreCallsBodyOnly { parallel } => {
            let invokes = if parallel {
                format!("dsml-invoke ( {} dsml-invoke )*", newline)
            } else {
                "dsml-invoke".to_string()
            };
            // The lazy splitter consumed only the outer open marker. The
            // leading newline, invoke body, and outer close remain constrained.
            format!("{} {} {} {}", newline, invokes, newline, close)
        }
    };
    rules.push(("root".into(), full_body));

    let mut output = String::new();
    output.push_str(&format!("root ::= {}\n", rules.last().unwrap().1));
    for (name, body) in rules.into_iter().filter(|(name, _)| name != "root") {
        output.push_str(&format!("{} ::= {}\n", name, body));
    }
    Ok(output)
}

/// Required DSML parameter blocks may appear in any order, but each must be
/// present exactly once. The recursive subset grammar matches the existing
/// Gemma/Qwen required-key contract and is bounded by `MAX_REQUIRED_KEYS`.
fn build_dsml_required_permutation(
    fn_name: &str,
    required: &[String],
    rules: &mut Vec<(String, String)>,
) -> String {
    let mut sorted = required.to_vec();
    sorted.sort();
    if sorted.len() == 1 {
        return sorted[0].clone();
    }
    let suffix = sorted
        .iter()
        .map(|name| name.trim_start_matches("dsml-param-"))
        .collect::<Vec<_>>()
        .join("-");
    let rule_name = format!(
        "dsml-required-{}-{}",
        sanitize_rule_name_local(fn_name),
        suffix
    );
    if rules.iter().any(|(name, _)| name == &rule_name) {
        return rule_name;
    }
    rules.push((rule_name.clone(), String::new()));
    let alternatives = sorted
        .iter()
        .enumerate()
        .map(|(index, item)| {
            let remainder = sorted
                .iter()
                .enumerate()
                .filter(|(candidate, _)| *candidate != index)
                .map(|(_, value)| value.clone())
                .collect::<Vec<_>>();
            let tail = build_dsml_required_permutation(fn_name, &remainder, rules);
            format!("{} {}", item, tail)
        })
        .collect::<Vec<_>>()
        .join(" | ");
    let (_, body) = rules
        .iter_mut()
        .find(|(name, _)| name == &rule_name)
        .expect("inserted DSML permutation rule");
    *body = alternatives;
    rule_name
}

/// Build the any-order permutation grammar for a non-empty set of required
/// Qwen parameter-block rule names.  Mirror of `build_gemma4_required_permutation`
/// but without comma separators (Qwen blocks are self-delimiting XML tags).
fn build_qwen35_required_permutation(
    slug: &str,
    required_block_names: &[String],
    rules: &mut Vec<(String, String)>,
) -> String {
    let mut sorted = required_block_names.to_vec();
    sorted.sort();

    let name_parts: Vec<String> = sorted
        .iter()
        .map(|n| n.trim_start_matches("qwen35-param-").to_string())
        .collect();
    let rule_name = format!(
        "q35req-{}-{}",
        sanitize_rule_name_local(slug),
        name_parts.join("-")
    );

    if rules.iter().any(|(n, _)| n == &rule_name) {
        return rule_name;
    }

    if sorted.len() == 1 {
        rules.push((rule_name.clone(), sorted[0].clone()));
        return rule_name;
    }

    rules.push((rule_name.clone(), String::new()));

    let mut alts: Vec<String> = Vec::new();
    for (i, block_name) in sorted.iter().enumerate() {
        let remaining: Vec<String> = sorted
            .iter()
            .enumerate()
            .filter(|(j, _)| *j != i)
            .map(|(_, s)| s.clone())
            .collect();
        let rest = build_qwen35_required_permutation(slug, &remaining, rules);
        // Qwen blocks are self-delimiting (each ends with `\n`), so no
        // explicit separator between them.
        alts.push(format!("{} {}", block_name, rest));
    }
    let body = alts.join(" | ");
    for (n, b) in rules.iter_mut() {
        if n == &rule_name {
            *b = body;
            break;
        }
    }
    rule_name
}

/// Map a JSON Schema value to the Qwen 3.5 value rule name.
///
/// iter-231a (B3 supersession): `array` and `object` types compile via the
/// iter-231b recursive nested-schema converter (`qwen35_nested_value_rule`).
fn qwen35_value_rule(
    fn_name: &str,
    param_name: &str,
    schema: &serde_json::Value,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
) -> Result<String, EmitterError> {
    let obj = match schema.as_object() {
        Some(o) => o,
        None => return Ok(QWEN35_TOP_ANY_VAL.to_string()),
    };
    // enum → accept only the declared string literals.  TOP-LEVEL string
    // values are RAW text between the parameter tags (the template only
    // `tojson`s NON-string values), so enum literals stay unquoted here.
    if let Some(serde_json::Value::Array(values)) = obj.get("enum") {
        let alts: Vec<String> = values
            .iter()
            .filter_map(|v| v.as_str())
            .map(|s| gbnf_literal(s))
            .collect();
        if !alts.is_empty() {
            return Ok(format!("( {} )", alts.join(" | ")));
        }
    }
    let schema_type = obj.get("type").and_then(|t| t.as_str()).unwrap_or("");
    match schema_type {
        "string" => {
            // iter-231c: `pattern` constrains the RAW string text.
            match compile_pattern(
                fn_name,
                &format!("/{}", param_name),
                obj.get("pattern"),
                crate::serve::api::grammar::regex_gbnf::Surface::QwenRawString,
            )? {
                Some(body) => Ok(body),
                None => Ok("qwen35-str-val".to_string()),
            }
        }
        "integer" => Ok("qwen35-int-val".to_string()),
        "number" => Ok("qwen35-num-val".to_string()),
        "boolean" => Ok("qwen35-bool-val".to_string()),
        "null" => Ok("qwen35-null-val".to_string()),
        // iter-231b: structured types → full-fidelity recursive compiler.
        "array" | "object" => qwen35_nested_value_rule(
            fn_name,
            &format!("/{}", param_name),
            schema,
            rules,
            rule_counter,
            1,
        ),
        _ => Ok(QWEN35_TOP_ANY_VAL.to_string()),
    }
}

/// Top-level value body for untyped / unknown-typed parameters: the
/// template renders string args RAW and non-string args via `tojson`, so
/// any scalar (raw) or any structured JSON value is accepted.
const QWEN35_TOP_ANY_VAL: &str = "( qwen35-any-val | qwen35-json-obj | qwen35-json-arr )";

/// iter-231c — compile a JSON Schema `pattern` keyword for the given
/// string surface via `grammar::regex_gbnf`.  Returns `Ok(None)` when
/// the schema carries no (string) `pattern`; `Err` for non-regular or
/// out-of-subset regex features (honest `UnsupportedSchemaFeature` —
/// never a silent permissive downgrade).
///
/// WHY the grammar-module dependency here: registry.rs previously had a
/// "no grammar module dependency" note (to avoid a circular import for a
/// trivial 10-line escape fn).  `regex_gbnf` has NO registry dependency,
/// so the dependency is one-directional and the original concern does
/// not apply.
fn compile_pattern(
    fn_name: &str,
    path: &str,
    pattern: Option<&serde_json::Value>,
    surface: crate::serve::api::grammar::regex_gbnf::Surface,
) -> Result<Option<String>, EmitterError> {
    let Some(pat) = pattern.and_then(|p| p.as_str()) else {
        return Ok(None);
    };
    match crate::serve::api::grammar::regex_gbnf::regex_to_gbnf_body(pat, surface) {
        Ok(body) => Ok(Some(body)),
        Err(e) => Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: format!("pattern {:?}: {}", pat, e.0),
        }),
    }
}

/// iter-231b — recursive nested-schema compiler for Qwen 3.5/3.6 tool
/// parameters (`tojson` = compact JSON surface, `serde_json::to_string`).
///
/// Constrains everything the schema DECLARES and stays open only where
/// the schema itself is open:
///
///   * scalars / enums / type-unions / anyOf / oneOf — exact bodies.
///   * `object` with `properties` — declared keys with per-key value
///     grammars; `required` (≤8) enforced any-order via permutation;
///     optional keys follow in a Kleene suffix (SAME contract as the
///     top-level parameter grammar: required keys in any order, then
///     optional keys in any order; optional duplicates are accepted the
///     same way top-level duplicates are).  `additionalProperties:false`
///     closes the key set; unset/true adds a wildcard kv tail.
///   * `object`/`array` with NO declared shape → the permissive
///     recursive `qwen35-json-obj` / `qwen35-json-arr` rules (any
///     well-formed compact JSON — the free-form MCP case).
///   * `array` with `items` → typed item grammar; absent → permissive.
///
/// `pattern` (regex) is COMPILED into the value grammar via
/// `grammar::regex_gbnf` (iter-231c); non-regular regex features
/// (backreferences, look-around, \p{...}, bounds > 2000) are rejected.
///
/// Rejected with `EmitterError::UnsupportedSchemaFeature` (→ HTTP 400
/// naming the feature + dot-path): `allOf`, `$ref`/`$defs`,
/// `not`/`if`/`then`/`else`, `dependentSchemas`, tuple-form `items`,
/// container `enum` values, >32 properties per object, depth > 32.
/// Constraint keywords the grammar cannot enforce (`minLength`,
/// `minimum`, `minItems`, `format`, …) are IGNORED, mirroring
/// json_schema.rs's deferred-feature list.
///
/// # Rejection-strength contract (CFG limitation, SOTA parity)
///
/// A REQUIRED key's value is always constrained by its declared grammar
/// (the permutation position cannot be filled by the wildcard extra-kv
/// branch), and a CLOSED object (`additionalProperties: false`) rejects
/// any key/value mismatch.  For OPEN objects (the JSON Schema default),
/// the wildcard extra-kv tail can re-match a declared OPTIONAL key with
/// an unconstrained value — a CFG cannot express "any key except these".
/// llama.cpp's json-schema-to-grammar and this crate's json_schema.rs
/// share the identical limitation; value validation for optional keys on
/// open objects belongs to the tool server.
fn qwen35_nested_value_rule(
    fn_name: &str,
    path: &str,
    schema: &serde_json::Value,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
    depth: usize,
) -> Result<String, EmitterError> {
    if depth > MAX_NESTED_DEPTH {
        return Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: format!("nesting depth > {}", MAX_NESTED_DEPTH),
        });
    }
    let obj = match schema.as_object() {
        Some(o) => o,
        // Non-object schema node (true/false/nonsense) → permissive leaf.
        None => return Ok("qwen35-json-val".to_string()),
    };

    // Hard-reject features the grammar cannot enforce (honest 400, no
    // silent downgrade).
    for feat in [
        "allOf",
        "$ref",
        "$defs",
        "not",
        "if",
        "then",
        "else",
        "dependentSchemas",
        "patternProperties",
        "propertyNames",
        "contains",
    ] {
        if obj.contains_key(feat) {
            return Err(EmitterError::UnsupportedSchemaFeature {
                fn_name: fn_name.to_string(),
                param_path: path.to_string(),
                feature: feat.to_string(),
            });
        }
    }

    // anyOf / oneOf → alternation of sub-schema bodies (same acceptance
    // for grammar purposes — a value matching ANY branch is accepted).
    for comb in ["anyOf", "oneOf"] {
        if let Some(serde_json::Value::Array(subs)) = obj.get(comb) {
            if subs.is_empty() {
                return Err(EmitterError::UnsupportedSchemaFeature {
                    fn_name: fn_name.to_string(),
                    param_path: path.to_string(),
                    feature: format!("empty {}", comb),
                });
            }
            let mut alts: Vec<String> = Vec::with_capacity(subs.len());
            for (i, s) in subs.iter().enumerate() {
                alts.push(qwen35_nested_value_rule(
                    fn_name,
                    &format!("{}/{}/{}", path, comb, i),
                    s,
                    rules,
                    rule_counter,
                    depth + 1,
                )?);
            }
            return Ok(format!("( {} )", alts.join(" | ")));
        }
    }

    // enum → literal alternation of the JSON-serialized values (compact
    // tojson form; strings keep their JSON quotes).  Container enum
    // values are rejected (json_schema.rs parity).
    if let Some(serde_json::Value::Array(values)) = obj.get("enum") {
        if values.is_empty() {
            return Err(EmitterError::UnsupportedSchemaFeature {
                fn_name: fn_name.to_string(),
                param_path: path.to_string(),
                feature: "empty enum".to_string(),
            });
        }
        let mut alts: Vec<String> = Vec::with_capacity(values.len());
        for v in values {
            match v {
                serde_json::Value::String(_)
                | serde_json::Value::Number(_)
                | serde_json::Value::Bool(_)
                | serde_json::Value::Null => {
                    let text = serde_json::to_string(v).map_err(|e| {
                        EmitterError::UnsupportedSchemaFeature {
                            fn_name: fn_name.to_string(),
                            param_path: path.to_string(),
                            feature: format!("enum serialize: {}", e),
                        }
                    })?;
                    alts.push(gbnf_literal(&text));
                }
                _ => {
                    return Err(EmitterError::UnsupportedSchemaFeature {
                        fn_name: fn_name.to_string(),
                        param_path: path.to_string(),
                        feature: "container enum value".to_string(),
                    });
                }
            }
        }
        return Ok(format!("( {} )", alts.join(" | ")));
    }

    match obj.get("type") {
        // Untyped nested node → any JSON value (structured included).
        None => Ok("qwen35-json-val".to_string()),
        Some(serde_json::Value::Array(types)) => {
            let mut alts: Vec<String> = Vec::with_capacity(types.len());
            for (i, t) in types.iter().enumerate() {
                let Some(tstr) = t.as_str() else {
                    return Err(EmitterError::UnsupportedSchemaFeature {
                        fn_name: fn_name.to_string(),
                        param_path: path.to_string(),
                        feature: "non-string type union entry".to_string(),
                    });
                };
                let mut stub = serde_json::Map::new();
                stub.insert("type".into(), serde_json::Value::String(tstr.into()));
                alts.push(qwen35_nested_value_rule(
                    fn_name,
                    &format!("{}/type/{}", path, i),
                    &serde_json::Value::Object(stub),
                    rules,
                    rule_counter,
                    depth + 1,
                )?);
            }
            Ok(format!("( {} )", alts.join(" | ")))
        }
        Some(serde_json::Value::String(t)) => match t.as_str() {
            "string" => {
                // iter-231c: `pattern` constrains the JSON string content.
                match compile_pattern(
                    fn_name,
                    path,
                    obj.get("pattern"),
                    crate::serve::api::grammar::regex_gbnf::Surface::QwenJsonString,
                )? {
                    Some(body) => Ok(format!(
                        "{} {} {}",
                        gbnf_literal("\""),
                        body,
                        gbnf_literal("\"")
                    )),
                    None => Ok("qwen35-json-str".to_string()),
                }
            }
            "integer" => Ok("qwen35-int-val".to_string()),
            "number" => Ok("qwen35-num-val".to_string()),
            "boolean" => Ok("qwen35-bool-val".to_string()),
            "null" => Ok("qwen35-null-val".to_string()),
            "object" => qwen35_nested_object(fn_name, path, obj, rules, rule_counter, depth),
            "array" => qwen35_nested_array(fn_name, path, obj, rules, rule_counter, depth),
            other => Err(EmitterError::UnsupportedSchemaFeature {
                fn_name: fn_name.to_string(),
                param_path: path.to_string(),
                feature: format!("type '{}'", other),
            }),
        },
        Some(_) => Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: "non-string type".to_string(),
        }),
    }
}

/// iter-231b — nested `object` compiler (Qwen compact-JSON surface).
/// See `qwen35_nested_value_rule` for the contract.
fn qwen35_nested_object(
    fn_name: &str,
    path: &str,
    obj: &serde_json::Map<String, serde_json::Value>,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
    depth: usize,
) -> Result<String, EmitterError> {
    let properties = obj.get("properties").and_then(|p| p.as_object());
    let additional_closed = matches!(
        obj.get("additionalProperties"),
        Some(serde_json::Value::Bool(false))
    );

    let props = match properties {
        Some(p) if !p.is_empty() => p,
        _ => {
            // No declared shape: closed → only `{}`; open → permissive.
            return Ok(if additional_closed {
                r#""{" "}""#.to_string()
            } else {
                "qwen35-json-obj".to_string()
            });
        }
    };

    let required_set: std::collections::HashSet<&str> = obj
        .get("required")
        .and_then(|v| v.as_array())
        .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
        .unwrap_or_default();

    if required_set.len() > MAX_REQUIRED_KEYS {
        return Err(EmitterError::TooManyRequiredKeys {
            fn_name: format!("{} (nested {})", fn_name, path),
            count: required_set.len(),
        });
    }
    if props.len() > MAX_NESTED_PROPERTIES {
        return Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: format!("> {} properties", MAX_NESTED_PROPERTIES),
        });
    }

    let mut req_kv: Vec<String> = Vec::new();
    let mut opt_kv: Vec<String> = Vec::new();
    let mut sorted_keys: Vec<&String> = props.keys().collect();
    sorted_keys.sort();
    for key in sorted_keys {
        let val_body = qwen35_nested_value_rule(
            fn_name,
            &format!("{}/properties/{}", path, key),
            &props[key],
            rules,
            rule_counter,
            depth + 1,
        )?;
        *rule_counter += 1;
        let kv_name = format!("q35n-{}-kv", *rule_counter);
        // Key literal: JSON-quoted exactly as serde emits it.
        let key_json = serde_json::to_string(key)
            .unwrap_or_else(|_| format!("\"{}\"", key.replace('"', "\\\"")));
        rules.push((
            kv_name.clone(),
            format!("{} \":\" {}", gbnf_literal(&key_json), val_body),
        ));
        if required_set.contains(key.as_str()) {
            req_kv.push(kv_name);
        } else {
            opt_kv.push(kv_name);
        }
    }

    // Wildcard kv for open objects (additionalProperties unset/true):
    // any JSON-string key with any JSON value.
    let extra_kv: Option<String> = if additional_closed {
        None
    } else {
        Some(r#"qwen35-json-str ":" qwen35-json-val"#.to_string())
    };

    build_nested_obj_body("q35n", req_kv, opt_kv, extra_kv, rules, rule_counter)
        .map(|inner| format!(r#""{{" {} "}}""#, inner))
}

/// iter-231b — nested `array` compiler (Qwen compact-JSON surface).
fn qwen35_nested_array(
    fn_name: &str,
    path: &str,
    obj: &serde_json::Map<String, serde_json::Value>,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
    depth: usize,
) -> Result<String, EmitterError> {
    match obj.get("items") {
        None => Ok("qwen35-json-arr".to_string()),
        Some(serde_json::Value::Object(_)) => {
            let item_rule = qwen35_nested_value_rule(
                fn_name,
                &format!("{}/items", path),
                obj.get("items").expect("items checked above"),
                rules,
                rule_counter,
                depth + 1,
            )?;
            Ok(format!(r#""[" ( {0} ("," {0})* )? "]""#, item_rule))
        }
        Some(serde_json::Value::Array(_)) => Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: "tuple-form items".to_string(),
        }),
        Some(_) => Err(EmitterError::UnsupportedSchemaFeature {
            fn_name: fn_name.to_string(),
            param_path: path.to_string(),
            feature: "non-object items".to_string(),
        }),
    }
}

/// iter-231b — shared nested-object inner builder.  Emits the
/// required-permutation + optional-Kleene-suffix body used by BOTH
/// families' nested object compilers (same contract as the top-level
/// parameter grammars): required keys in any order first, then optional
/// keys (plus the wildcard tail for open objects) in any order.
///
/// Returns the GBNF expression for the object's inner kv sequence (no
/// surrounding braces).
fn build_nested_obj_body(
    prefix: &str,
    req_kv: Vec<String>,
    opt_kv: Vec<String>,
    extra_kv: Option<String>,
    rules: &mut Vec<(String, String)>,
    rule_counter: &mut u32,
) -> Result<String, EmitterError> {
    // GBNF literal for the inter-kv comma (compact surfaces — Qwen
    // `tojson` and Gemma `format_argument` — emit NO whitespace).
    // NOTE: the 3-byte form `","` — `r#"","#` would be just `,`.
    let comma = r#"",""#;
    let mut opt_items: Vec<String> = opt_kv;
    if let Some(eb) = &extra_kv {
        opt_items.push(format!("( {} )", eb));
    }

    if req_kv.is_empty() {
        // All-optional object: `( item ("," item)* )?` — {} accepted.
        if opt_items.is_empty() {
            // Closed object, no declared keys → empty body; caller wraps
            // braces: `{" "}` shape handled by the caller passing an empty
            // optional set for a closed object with properties that all
            // got filtered (defensive; today unreachable).
            return Ok(String::new());
        }
        *rule_counter += 1;
        let item_name = format!("{}-{}-item", prefix, *rule_counter);
        rules.push((item_name.clone(), format!("( {} )", opt_items.join(" | "))));
        Ok(format!("( {} ( {} {} )* )?", item_name, comma, item_name))
    } else {
        let req_top = build_nested_kv_permutation(
            &format!("{}-{}", prefix, *rule_counter),
            &req_kv,
            comma,
            rules,
        );
        if opt_items.is_empty() {
            Ok(req_top)
        } else {
            *rule_counter += 1;
            let opt_name = format!("{}-{}-opt", prefix, *rule_counter);
            rules.push((opt_name.clone(), format!("( {} )", opt_items.join(" | "))));
            Ok(format!("{} ( {} {} )*", req_top, comma, opt_name))
        }
    }
}

/// iter-231b — shared any-order permutation builder for nested kv rules.
/// Mirrors `build_qwen35_required_permutation` but parameterized on the
/// rule-name prefix + separator so both families' nested compilers share
/// one implementation.  Sub-rule names are content-addressed (sorted
/// join), so shared subsets across branches are emitted once.
fn build_nested_kv_permutation(
    set_name: &str,
    item_names: &[String],
    separator_lit: &str,
    rules: &mut Vec<(String, String)>,
) -> String {
    let mut sorted = item_names.to_vec();
    sorted.sort();

    if sorted.len() == 1 {
        return sorted[0].clone();
    }

    let rule_name = format!("{}-{}", set_name, sorted.join("-"));
    if rules.iter().any(|(n, _)| n == &rule_name) {
        return rule_name;
    }

    let mut alts: Vec<String> = Vec::new();
    for (i, item) in sorted.iter().enumerate() {
        let remaining: Vec<String> = sorted
            .iter()
            .enumerate()
            .filter(|(j, _)| *j != i)
            .map(|(_, s)| s.clone())
            .collect();
        let rest = build_nested_kv_permutation(set_name, &remaining, separator_lit, rules);
        alts.push(format!("{} {} {}", item, separator_lit, rest));
    }
    rules.push((rule_name.clone(), alts.join(" | ")));
    rule_name
}

/// Sanitize a property name for use as part of a GBNF rule name.
/// Replaces non-alphanumeric/dash chars with `-`.
fn sanitize_rule_name_local(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    for c in raw.chars() {
        if c.is_ascii_alphanumeric() || c == '-' {
            out.push(c);
        } else {
            out.push('-');
        }
    }
    if out.is_empty() {
        out.push('x');
    }
    out
}

/// Silence the unused-import warning when the registry itself is only
/// touched by the engine (which isn't compiled in this test binary).
#[allow(dead_code)]
const _COMPILE_REFERENCES: fn() -> HashMap<String, ModelRegistration> = || HashMap::new();

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // ---- ADR-005 iter-230 B — forced-open seeding (AC-B1/AC-B2) ----

    /// Suffix-rule truth table (Decision B1) for the served templates'
    /// generation-prompt tails.
    #[test]
    fn iter230_b1_prompt_seeds_reasoning_open_truth_table() {
        // qwen thinking-on: template seeds an OPEN think block.
        assert!(prompt_seeds_reasoning_open(
            "<|im_start|>assistant\n<think>\n",
            &QWEN35
        ));
        // qwen thinking-off: pre-closed suppressor → NOT seeded.
        assert!(!prompt_seeds_reasoning_open(
            "<|im_start|>assistant\n<think>\n\n</think>\n\n",
            &QWEN35
        ));
        // Gemma thinking-on: bare model turn — the model emits its own
        // open marker in the completion → NOT seeded.
        assert!(!prompt_seeds_reasoning_open("<|turn>model\n", &GEMMA4));
        // Gemma thinking-off: closed-channel seed ends with the CLOSE
        // marker → NOT seeded.
        assert!(!prompt_seeds_reasoning_open(
            "<|turn>model\n<|channel>thought\n<channel|>",
            &GEMMA4
        ));
        // No reasoning markers → never seeded.
        let no_markers = ModelRegistration {
            family: "none",
            id_substrings: &["x"],
            reasoning_open: None,
            reasoning_close: None,
            tool_open: None,
            tool_close: None,
            tool_preamble: None,
        };
        assert!(!prompt_seeds_reasoning_open("<think>\n", &no_markers));
    }

    /// Seeded-open: close marker split across fragment boundaries; the
    /// pre-close span routes to Reasoning, post-close to Content.
    #[test]
    fn iter230_b1_seeded_open_close_marker_across_fragments() {
        let mut sp = make_reasoning_splitter(&QWEN35, true).unwrap();
        let mut reasoning = String::new();
        let mut content = String::new();
        for frag in ["I think", " therefore</th", "ink>I am"] {
            for (slot, s) in sp.feed(frag) {
                match slot {
                    SplitSlot::Reasoning => reasoning.push_str(&s),
                    SplitSlot::Content => content.push_str(&s),
                }
            }
        }
        if let Some((slot, s)) = sp.finish() {
            match slot {
                SplitSlot::Reasoning => reasoning.push_str(&s),
                SplitSlot::Content => content.push_str(&s),
            }
        }
        assert_eq!(reasoning, "I think therefore");
        assert_eq!(content, "I am");
    }

    /// Seeded-open with NO close marker: finish() drains the tail to
    /// Reasoning — nothing leaks into content.
    #[test]
    fn iter230_b1_seeded_open_no_close_finish_routes_to_reasoning() {
        let (content, reasoning) =
            split_full_output_forced(&QWEN35, "endless pondering with no close", true);
        assert_eq!(content, "");
        assert_eq!(
            reasoning.as_deref(),
            Some("endless pondering with no close")
        );
    }

    /// Unseeded (forced_open=false) behavior is byte-identical to the
    /// legacy constructor on marker-bearing text.
    #[test]
    fn iter230_b1_unseeded_byte_identical_to_legacy() {
        let text = "Sure! <think>step by step</think>The answer is 42.";
        let legacy = split_full_output(&QWEN35, text);
        let forced_false = split_full_output_forced(&QWEN35, text, false);
        assert_eq!(legacy, forced_false);
        assert_eq!(legacy.0, "Sure! The answer is 42.");
        assert_eq!(legacy.1.as_deref(), Some("step by step"));
    }

    /// Redundant model-emitted open marker while seeded open is
    /// reasoning TEXT (today's nested-open behavior), not swallowed.
    #[test]
    fn iter230_b1_redundant_open_while_seeded_is_reasoning_text() {
        let (content, reasoning) =
            split_full_output_forced(&QWEN35, "<think>abc</think>done", true);
        assert_eq!(reasoning.as_deref(), Some("<think>abc"));
        assert_eq!(content, "done");
    }

    /// AC-B2 — factory-only construction pin: no engine-path module
    /// constructs a ReasoningSplitter directly; everything routes
    /// through `make_reasoning_splitter` so the forced-open seed can't
    /// be silently dropped. (Pattern built at runtime so this pin's own
    /// source stays out of the scan.)
    #[test]
    fn iter230_b2_factory_only_construction() {
        let direct = format!("{}::{}", "ReasoningSplitter", "from_registration");
        let modules: [(&str, &str); 4] = [
            ("engine.rs", include_str!("engine.rs")),
            ("engine_qwen35.rs", include_str!("engine_qwen35.rs")),
            ("engine_qwen3vl.rs", include_str!("engine_qwen3vl.rs")),
            ("handlers.rs", include_str!("handlers.rs")),
        ];
        for (name, src) in modules {
            assert_eq!(
                src.matches(&direct).count(),
                0,
                "{name}: direct ReasoningSplitter construction found — \
                 use registry::make_reasoning_splitter(reg, forced_open) \
                 so the iter-230 forced-open seed is threaded"
            );
        }
    }

    #[test]
    fn gemma4_matches_real_model_ids() {
        assert!(GEMMA4.matches("gemma-4-26B-A4B-it-ara-abliterated-dwq"));
        assert!(GEMMA4.matches("gemma-4-27b-it"));
        assert!(GEMMA4.matches("GEMMA-4-test"));
    }

    #[test]
    fn qwen35_matches_family_ids() {
        assert!(QWEN35.matches("qwen3.5-27b"));
        assert!(QWEN35.matches("qwen3.6-35b-a3b-abliterix"));
        assert!(QWEN35.matches("Qwen35-14B-chat"));
    }

    #[test]
    fn non_matching_model_id_returns_none() {
        assert!(find_for("llama-3.2-1b").is_none());
        assert!(find_for("unknown-model").is_none());
    }

    #[test]
    fn gemma4_has_reasoning_and_tools() {
        assert!(GEMMA4.has_reasoning());
        assert!(GEMMA4.has_tools());
        // Iter D W67: the reasoning pair is the runtime `<|channel>` /
        // `<channel|>` channel-block convention (matches `strip_thinking`
        // and tokenizer_config.json `x-regex`), NOT the `<|think|>` /
        // `</think|>` literal which is the prompt-side thinking-mode hint.
        assert_eq!(GEMMA4.reasoning_open, Some("<|channel>"));
        assert_eq!(GEMMA4.reasoning_close, Some("<channel|>"));
    }

    /// Iter D W67: lock in the corrected Gemma 4 reasoning markers — same
    /// bug-class as iter B-2's tool-call fix. The chat-template
    /// `strip_thinking` macro authoritatively defines the reasoning span as
    /// `<|channel>` … `<channel|>` (text.split('<channel|>') THEN look for
    /// `'<|channel>' in part`); the tokenizer_config `x-regex` confirms the
    /// emission shape. Pre-fix the registry declared `<|think|>` /
    /// `</think|>`, the system-side thinking-mode hint, which the model
    /// never emits as a runtime delimiter — so the splitter would never
    /// detect a real Gemma 4 reasoning span.
    #[test]
    fn gemma4_reasoning_markers_match_chat_template_emission() {
        // Authoritative reference: chat_template.jinja `strip_thinking`
        // splits on `<channel|>` then trims `<|channel>...` prefix from
        // each part. Same pair the runtime tokens emit.
        assert_eq!(GEMMA4.reasoning_open, Some("<|channel>"));
        assert_eq!(GEMMA4.reasoning_close, Some("<channel|>"));
        // Cross-check: tokenizer_config.json declares `soc_token` =
        // `<|channel>` and `eoc_token` = `<channel|>`; these are the
        // canonical channel-block delimiters Gemma 4 emits.
        assert_eq!(GEMMA4.reasoning_open.unwrap(), "<|channel>");
        assert_eq!(GEMMA4.reasoning_close.unwrap(), "<channel|>");
    }

    #[test]
    fn qwen35_has_different_reasoning_markers() {
        // Regression: don't conflate Qwen's `<think>` / `</think>` HF
        // convention with Gemma's asymmetric `<|channel>` / `<channel|>`
        // channel-block convention.
        assert_ne!(GEMMA4.reasoning_open, QWEN35.reasoning_open);
        assert_ne!(GEMMA4.reasoning_close, QWEN35.reasoning_close);
    }

    #[test]
    fn register_appends_and_wins_over_builtin_on_substring_overlap() {
        register(ModelRegistration {
            family: "custom",
            id_substrings: &["test_register_overlap"],
            reasoning_open: Some("<R>"),
            reasoning_close: Some("</R>"),
            tool_open: None,
            tool_close: None,
            tool_preamble: None,
        });
        let found = find_for("test_register_overlap-001").expect("found");
        // Built-ins are scanned first; the newly-registered entry only wins
        // if no built-in matches. That's fine for this disjoint substring.
        assert_eq!(found.family, "custom");
    }

    // --- ReasoningSplitter ---

    fn split(reg: &ModelRegistration, s: &str) -> Vec<(SplitSlot, String)> {
        // Run the splitter and coalesce adjacent same-slot runs — the
        // splitter holds back a tail buffer to safely detect markers across
        // fragment boundaries, which can emit one slot run as two parts.
        // Coalescing gives the logical classification.
        let mut sp = ReasoningSplitter::from_registration(reg).unwrap();
        let mut out = sp.feed(s);
        if let Some(tail) = sp.finish() {
            out.push(tail);
        }
        coalesce(&out)
    }

    #[test]
    fn splitter_no_markers_all_content() {
        let out = split(&GEMMA4, "hello world");
        assert_eq!(out, vec![(SplitSlot::Content, "hello world".into())]);
    }

    #[test]
    fn splitter_single_reasoning_span() {
        // Use real gemma markers: `<|channel>` open, `<channel|>` close
        // (iter D W67 corrected from the previous `<|think|>` / `</think|>`
        // declaration that the model never emits at runtime).
        let out = split(&GEMMA4, "pre <|channel>because<channel|> post");
        assert_eq!(
            out,
            vec![
                (SplitSlot::Content, "pre ".into()),
                (SplitSlot::Reasoning, "because".into()),
                (SplitSlot::Content, " post".into()),
            ]
        );
    }

    #[test]
    fn splitter_open_without_close_reasoning_continues_to_end() {
        let out = split(&GEMMA4, "pre <|channel>still thinking");
        assert_eq!(
            out,
            vec![
                (SplitSlot::Content, "pre ".into()),
                (SplitSlot::Reasoning, "still thinking".into()),
            ]
        );
    }

    #[test]
    fn splitter_marker_spans_fragment_boundary() {
        // The open marker `<|channel>` is 10 bytes; feeding it in two
        // fragments should still detect it via the sliding tail buffer.
        let mut sp = ReasoningSplitter::from_registration(&GEMMA4).unwrap();
        let a = sp.feed("before <|chan");
        let b = sp.feed("nel>reasoning<channel|>after");
        let c = sp.finish();
        let mut all: Vec<(SplitSlot, String)> = Vec::new();
        all.extend(a);
        all.extend(b);
        if let Some(t) = c {
            all.push(t);
        }
        let joined = coalesce(&all);
        assert_eq!(
            joined,
            vec![
                (SplitSlot::Content, "before ".into()),
                (SplitSlot::Reasoning, "reasoning".into()),
                (SplitSlot::Content, "after".into()),
            ]
        );
    }

    #[test]
    fn splitter_multiple_reasoning_spans() {
        let out = split(&GEMMA4, "a<|channel>b<channel|>c<|channel>d<channel|>e");
        let joined = coalesce(&out);
        assert_eq!(
            joined,
            vec![
                (SplitSlot::Content, "a".into()),
                (SplitSlot::Reasoning, "b".into()),
                (SplitSlot::Content, "c".into()),
                (SplitSlot::Reasoning, "d".into()),
                (SplitSlot::Content, "e".into()),
            ]
        );
    }

    /// Iter D W67: realistic Gemma 4 emission — the model produces
    /// `<|channel>thought\n[REASONING_TEXT]<channel|>[ANSWER]` per the
    /// tokenizer_config `x-regex`. The literal `thought\n` channel
    /// identifier is part of the routed reasoning span (`strip_thinking`
    /// preserves the channel name), and the post-close run is content.
    #[test]
    fn splitter_gemma4_realistic_thought_channel_emission() {
        let out = split(
            &GEMMA4,
            "<|channel>thought\nlet me compute 73 * 47<channel|>The answer is 3431",
        );
        let joined = coalesce(&out);
        assert_eq!(
            joined,
            vec![
                (
                    SplitSlot::Reasoning,
                    "thought\nlet me compute 73 * 47".into()
                ),
                (SplitSlot::Content, "The answer is 3431".into()),
            ]
        );
    }

    #[test]
    fn splitter_qwen_markers_distinct_from_gemma() {
        let out = split(&QWEN35, "hi <think>pondering</think> there");
        let joined = coalesce(&out);
        assert_eq!(
            joined,
            vec![
                (SplitSlot::Content, "hi ".into()),
                (SplitSlot::Reasoning, "pondering".into()),
                (SplitSlot::Content, " there".into()),
            ]
        );
    }

    #[test]
    fn splitter_does_not_split_utf8_at_fragment_end() {
        // Greek α is 2 bytes. If snap_down_char_boundary were wrong, we'd
        // panic with "byte index X is not a char boundary".
        let mut sp = ReasoningSplitter::from_registration(&GEMMA4).unwrap();
        let _ = sp.feed("hello α");
        let _ = sp.feed("β world");
        let _ = sp.finish();
    }

    #[test]
    fn split_full_output_helper_returns_both_slots() {
        // Two reasoning spans with real Gemma markers (iter D W67:
        // `<|channel>` / `<channel|>` per `strip_thinking`).
        let (content, reasoning) = split_full_output(
            &GEMMA4,
            "a <|channel>r1<channel|> b <|channel>r2<channel|> c",
        );
        assert_eq!(content, "a  b  c");
        assert_eq!(reasoning.as_deref(), Some("r1r2"));
    }

    #[test]
    fn split_full_output_no_markers_returns_none_reasoning() {
        let (content, reasoning) = split_full_output(&GEMMA4, "just plain content");
        assert_eq!(content, "just plain content");
        assert_eq!(reasoning, None);
    }

    /// ADR-005 Phase 4 iter C closure (2026-05-01): non-streaming
    /// surface contract. The handler calls `split_full_output` to
    /// extract `reasoning_text` from the raw decoded stream, THEN
    /// `extract_tool_calls_from_text` runs over the remaining
    /// post-reasoning content to extract tool calls. This test locks
    /// in that `split_full_output` correctly partitions a stream that
    /// contains BOTH reasoning markers AND tool-call markers — the
    /// reasoning span is the only thing extracted; tool-call markers
    /// remain in `content` for downstream tool-call splitter to
    /// consume. Companion to the engine.rs streaming-side
    /// `replay_routes_reasoning_then_tool_call_in_correct_order`
    /// test. Without this, a regression that incorrectly interleaved
    /// the two splitters in `split_full_output` would silently
    /// surface only at LIVE-test time.
    #[test]
    fn split_full_output_preserves_tool_call_markers_in_content() {
        // Qwen 3.5/3.6 reasoning span + tool-call span. The reasoning
        // splitter only knows about reasoning markers; tool-call
        // markers must pass through untouched into the `content`
        // return slot.
        let raw_stream =
            "<think>I should call get_weather</think>OK, calling now: \
             <tool_call>\n<function=get_weather><parameter=city>Paris</parameter></function>\n</tool_call>";
        let (content, reasoning) = split_full_output(&QWEN35, raw_stream);
        assert_eq!(
            reasoning.as_deref(),
            Some("I should call get_weather"),
            "iter C non-streaming contract: reasoning span must be \
             extracted verbatim, markers swallowed"
        );
        assert!(
            !content.contains("<think>") && !content.contains("</think>"),
            "iter C non-streaming contract: reasoning markers must NOT \
             leak into content slot; got content: {content:?}"
        );
        assert!(
            content.contains("<tool_call>") && content.contains("</tool_call>"),
            "iter C+B-2 composition: tool-call markers MUST be preserved \
             in the content slot for the downstream ToolCallSplitter to \
             consume; ReasoningSplitter must not touch them. got content: {content:?}"
        );
        assert!(
            content.contains("OK, calling now:"),
            "iter C non-streaming contract: post-reasoning natural-language \
             preamble must be preserved verbatim; got content: {content:?}"
        );
    }

    /// ADR-005 Phase 4 iter C closure: non-streaming surface symmetric
    /// contract — pure reasoning followed by EOS (no post-reasoning
    /// content). The handler must produce `message.reasoning_content`
    /// populated, `message.content` empty (which serializes to `""`
    /// per OpenAI compat — the assistant gave a non-empty turn that's
    /// just thinking). This locks in the symmetric streaming-side
    /// `replay_streaming_origin_pure_reasoning_no_content` test at
    /// the helper level.
    #[test]
    fn split_full_output_pure_reasoning_returns_empty_content() {
        let (content, reasoning) =
            split_full_output(&QWEN35, "<think>only thinking, no answer</think>");
        assert_eq!(
            reasoning.as_deref(),
            Some("only thinking, no answer"),
            "pure-reasoning input must produce a populated reasoning slot"
        );
        assert_eq!(
            content, "",
            "pure-reasoning input (no content after </think>) must produce \
             empty content slot; got: {content:?}"
        );
    }

    #[test]
    fn list_families_includes_builtins() {
        let fams = list_families();
        assert!(fams.iter().any(|f| f == "gemma4"));
        assert!(fams.iter().any(|f| f == "qwen35"));
    }

    // --- ToolCallSplitter (iter-133 Iter B-2) ---

    /// Iter B-2 W66: lock in the corrected Gemma 4 tool-call markers. Pre-fix
    /// these were `<tool_call>` / `</tool_call>` (the Qwen convention); the
    /// gemma-4 GGUF chat template actually emits `<|tool_call>` (open) and
    /// `<tool_call|>` (close). Real-model fixture
    /// `tests/fixtures/openwebui_multiturn/scenario2_tool_call_chunks.txt`
    /// from W65 confirmed the literal mismatch.
    #[test]
    fn gemma4_tool_call_markers_match_chat_template_emission() {
        assert_eq!(GEMMA4.tool_open, Some("<|tool_call>"));
        assert_eq!(GEMMA4.tool_close, Some("<tool_call|>"));
    }

    fn tcfeed(reg: &ModelRegistration, s: &str) -> Vec<ToolCallEvent> {
        let mut sp = ToolCallSplitter::from_registration(reg).unwrap();
        let mut out = sp.feed(s);
        if let Some(tail) = sp.finish() {
            out.push(tail);
        }
        out
    }

    fn tc_coalesce(v: &[ToolCallEvent]) -> Vec<ToolCallEvent> {
        let mut out: Vec<ToolCallEvent> = Vec::new();
        for ev in v {
            if let (Some(last), ev) = (out.last_mut(), ev) {
                match (last, ev) {
                    (ToolCallEvent::Content(a), ToolCallEvent::Content(b)) => {
                        a.push_str(b);
                        continue;
                    }
                    (ToolCallEvent::ToolCallText(a), ToolCallEvent::ToolCallText(b)) => {
                        a.push_str(b);
                        continue;
                    }
                    _ => {}
                }
            }
            out.push(ev.clone());
        }
        out
    }

    #[test]
    fn tool_call_splitter_no_markers_all_content() {
        let out = tcfeed(&GEMMA4, "hello world");
        assert_eq!(out, vec![ToolCallEvent::Content("hello world".into())]);
    }

    #[test]
    fn tool_call_splitter_single_call_gemma4_markers() {
        let out = tcfeed(&GEMMA4, "pre <|tool_call>call:f{x:1}<tool_call|> post");
        let joined = tc_coalesce(&out);
        assert_eq!(
            joined,
            vec![
                ToolCallEvent::Content("pre ".into()),
                ToolCallEvent::ToolCallOpen,
                ToolCallEvent::ToolCallText("call:f{x:1}".into()),
                ToolCallEvent::ToolCallClose,
                ToolCallEvent::Content(" post".into()),
            ]
        );
    }

    #[test]
    fn tool_call_splitter_qwen35_markers_distinct() {
        let out = tcfeed(
            &QWEN35,
            "pre <tool_call>\n<function=f><parameter=x>\n1\n</parameter></function>\n</tool_call> post",
        );
        let joined = tc_coalesce(&out);
        assert_eq!(joined.len(), 5, "got {joined:?}");
        match (&joined[0], &joined[1], &joined[3], &joined[4]) {
            (
                ToolCallEvent::Content(a),
                ToolCallEvent::ToolCallOpen,
                ToolCallEvent::ToolCallClose,
                ToolCallEvent::Content(b),
            ) => {
                assert_eq!(a, "pre ");
                assert_eq!(b, " post");
            }
            other => panic!("unexpected event sequence: {other:?}"),
        }
    }

    #[test]
    fn tool_call_splitter_marker_spans_fragment_boundary() {
        let mut sp = ToolCallSplitter::from_registration(&GEMMA4).unwrap();
        let a = sp.feed("before <|tool");
        let b = sp.feed("_call>call:f{a:1}<tool_call");
        let c = sp.feed("|>after");
        let d = sp.finish();
        let mut all: Vec<ToolCallEvent> = Vec::new();
        all.extend(a);
        all.extend(b);
        all.extend(c);
        if let Some(t) = d {
            all.push(t);
        }
        let joined = tc_coalesce(&all);
        assert_eq!(
            joined,
            vec![
                ToolCallEvent::Content("before ".into()),
                ToolCallEvent::ToolCallOpen,
                ToolCallEvent::ToolCallText("call:f{a:1}".into()),
                ToolCallEvent::ToolCallClose,
                ToolCallEvent::Content("after".into()),
            ]
        );
    }

    /// iter-219c (2026-05-01) — when the model emits a registered in-call
    /// resync marker (`<|tool_response>`, `<|channel>`, `<|turn>` for
    /// gemma4) MID-tool-call-body, the splitter MUST abort the call by
    /// emitting a synthetic ToolCallClose (with the partial body as
    /// ToolCallText) instead of absorbing the marker bytes verbatim.
    /// This closes the iter-218 LIVE-bug class structurally at the
    /// splitter level — the validity-gate + content-fallback-scrub
    /// downstream layers (iter-219b) catch the SYMPTOM; iter-219c catches
    /// the CAUSE.
    ///
    /// Pre-iter-219c: this test FAILS — splitter emits
    /// `ToolCallText("call:get_current<|tool_response>call:get_current_weather{...}")`.
    /// Post-iter-219c: this test PASSES — splitter emits
    /// `ToolCallText("call:get_current")`, `ToolCallClose` (synthetic),
    /// then re-enters non-tool-call state for the rest.
    #[test]
    fn iter219c_in_call_tool_response_aborts_with_synthetic_close() {
        let out = tcfeed(
            &GEMMA4,
            "<|tool_call>call:get_current<|tool_response>call:get_current_weather{x:1}<tool_call|>",
        );
        let joined = tc_coalesce(&out);
        // The splitter MUST recognize <|tool_response> as a resync marker
        // and abort the malformed call. The synthetic ToolCallClose fires
        // when the resync is observed; subsequent text re-enters non-tool-call
        // routing (Content), where the second `<|tool_call>` reopens a NEW
        // call cleanly.
        assert!(
            matches!(joined.as_slice(),
                [
                    ToolCallEvent::ToolCallOpen,
                    ToolCallEvent::ToolCallText(t1),
                    ToolCallEvent::ToolCallClose,
                    // Optional Content between the abort and the next open
                    // (resync marker bytes are swallowed; whatever followed
                    // before `<|tool_call>` becomes Content).
                    ..
                ] if t1 == "call:get_current"
            ),
            "iter-219c: splitter MUST abort on in-call <|tool_response> with \
             ToolCallText(partial body) + synthetic ToolCallClose. Got: {joined:#?}"
        );
        // Stronger: no event in the sequence should contain `<|tool_response>`
        // as text — the marker bytes MUST be swallowed.
        for ev in &joined {
            match ev {
                ToolCallEvent::ToolCallText(t) | ToolCallEvent::Content(t) => {
                    assert!(
                        !t.contains("<|tool_response>") && !t.contains("<tool_response|>"),
                        "iter-219c: resync marker leaked into text event: {ev:#?}"
                    );
                }
                _ => {}
            }
        }
    }

    /// iter-219c sibling — `<|channel>` mid-call (Gemma 4 reasoning
    /// channel reopened inside a tool body) MUST also abort. NOTE: in
    /// production the `ReasoningSplitter` runs upstream of
    /// `ToolCallSplitter` and would have absorbed `<|channel>...<channel|>`
    /// before reaching here — this test exercises the splitter in
    /// isolation to verify it recognizes `<|channel>` as a resync marker
    /// (so the call aborts cleanly even if upstream routing fails). The
    /// test does NOT assert the `<channel|>` close-marker is scrubbed
    /// from Content because that's `ReasoningSplitter`'s contract, not
    /// `ToolCallSplitter`'s.
    #[test]
    fn iter219c_in_call_channel_marker_aborts() {
        let out = tcfeed(
            &GEMMA4,
            "<|tool_call>call:f<|channel>thought<channel|>{x:1}<tool_call|>",
        );
        let joined = tc_coalesce(&out);
        // Iterate looking for the abort pattern: ToolCallOpen → ToolCallText
        // (containing only `call:f`) → ToolCallClose.
        let saw_clean_partial = joined.windows(3).any(|w| {
            matches!(w,
                [
                    ToolCallEvent::ToolCallOpen,
                    ToolCallEvent::ToolCallText(t),
                    ToolCallEvent::ToolCallClose,
                ] if t == "call:f"
            )
        });
        assert!(
            saw_clean_partial,
            "iter-219c: <|channel> mid-call MUST trigger abort; expected \
             ToolCallText(\"call:f\") + synthetic ToolCallClose; got: {joined:#?}"
        );
        // `<|channel>` (open marker, in resync set) MUST be swallowed.
        // `<channel|>` (close marker, NOT in our resync set; handled by
        // ReasoningSplitter upstream) may appear in Content here — that's
        // fine for the unit-isolation test; production never sees it.
        for ev in &joined {
            if let ToolCallEvent::ToolCallText(t) = ev {
                assert!(
                    !t.contains("<|channel>"),
                    "iter-219c: <|channel> leaked into ToolCallText: {ev:#?}"
                );
            }
        }
    }

    /// iter-219c regression-guard — close_marker that comes BEFORE any
    /// resync marker still wins (existing happy-path behavior unchanged).
    #[test]
    fn iter219c_close_before_resync_still_wins() {
        let out = tcfeed(
            &GEMMA4,
            // Clean call, then post-close `<|tool_response>` (legitimate —
            // host emits tool_response after the call closes; that's
            // post-close territory, not in-call).
            "<|tool_call>call:f{x:1}<tool_call|><|tool_response>tool_result<tool_response|>",
        );
        let joined = tc_coalesce(&out);
        // The first 4 events must be the clean happy-path:
        //   Open, Text("call:f{x:1}"), Close, Content(...)
        assert!(
            joined.len() >= 4,
            "iter-219c happy path: expected ≥4 events; got {joined:#?}"
        );
        match (&joined[0], &joined[1], &joined[2]) {
            (
                ToolCallEvent::ToolCallOpen,
                ToolCallEvent::ToolCallText(t),
                ToolCallEvent::ToolCallClose,
            ) if t == "call:f{x:1}" => {}
            _ => panic!("iter-219c: close_marker MUST win over later resync; got: {joined:#?}"),
        }
    }

    #[test]
    fn tool_call_splitter_open_without_close_finishes_in_call() {
        // Mid-call EOS: `finish()` returns the partial body as ToolCallText.
        let out = tcfeed(&GEMMA4, "<|tool_call>call:f{a:1");
        // Coalesce because the splitter holds back a tail.
        let joined = tc_coalesce(&out);
        assert_eq!(
            joined,
            vec![
                ToolCallEvent::ToolCallOpen,
                ToolCallEvent::ToolCallText("call:f{a:1".into()),
            ]
        );
    }

    #[test]
    fn tool_call_splitter_no_registration_returns_none() {
        let none_reg = ModelRegistration {
            family: "no-tools",
            id_substrings: &["test"],
            reasoning_open: None,
            reasoning_close: None,
            tool_open: None,
            tool_close: None,
            tool_preamble: None,
        };
        assert!(ToolCallSplitter::from_registration(&none_reg).is_none());
    }

    // --- parse_tool_call_body ---

    #[test]
    fn parse_gemma4_simple_string_arg() {
        let parsed = parse_tool_call_body(
            &GEMMA4,
            "call:get_current_weather{location:<|\"|>Paris<|\"|>}",
        )
        .expect("parse");
        assert_eq!(parsed.name, "get_current_weather");
        // Order is HashMap-iteration → json string canonicalized via
        // serde_json (sorted keys not guaranteed but the SET of fields is).
        let v: serde_json::Value = serde_json::from_str(&parsed.arguments_json).expect("arg JSON");
        assert_eq!(v["location"], "Paris");
    }

    #[test]
    fn parse_gemma4_multi_arg_string_and_enum() {
        let parsed = parse_tool_call_body(
            &GEMMA4,
            "call:f{location:<|\"|>San Francisco<|\"|>,unit:<|\"|>celsius<|\"|>}",
        )
        .expect("parse");
        assert_eq!(parsed.name, "f");
        let v: serde_json::Value = serde_json::from_str(&parsed.arguments_json).expect("arg JSON");
        assert_eq!(v["location"], "San Francisco");
        assert_eq!(v["unit"], "celsius");
    }

    #[test]
    fn parse_gemma4_numeric_and_bool_args() {
        let parsed = parse_tool_call_body(&GEMMA4, "call:f{count:42,enabled:true,ratio:1.5}")
            .expect("parse");
        let v: serde_json::Value = serde_json::from_str(&parsed.arguments_json).expect("arg JSON");
        assert_eq!(v["count"], 42);
        assert_eq!(v["enabled"], true);
        assert_eq!(v["ratio"], 1.5);
    }

    #[test]
    fn parse_gemma4_string_with_comma_inside_quotes() {
        // Comma inside `<|"|>...<|"|>` must NOT split top-level args.
        let parsed = parse_tool_call_body(
            &GEMMA4,
            "call:f{addr:<|\"|>1, Main St<|\"|>,city:<|\"|>NYC<|\"|>}",
        )
        .expect("parse");
        let v: serde_json::Value = serde_json::from_str(&parsed.arguments_json).expect("arg JSON");
        assert_eq!(v["addr"], "1, Main St");
        assert_eq!(v["city"], "NYC");
    }

    #[test]
    fn parse_gemma4_empty_args() {
        let parsed = parse_tool_call_body(&GEMMA4, "call:noop{}").expect("parse");
        assert_eq!(parsed.name, "noop");
        assert_eq!(parsed.arguments_json, "{}");
    }

    #[test]
    fn parse_gemma4_invalid_returns_none() {
        // Missing `call:` prefix.
        assert!(parse_tool_call_body(&GEMMA4, "garbage{}").is_none());
        // Missing braces.
        assert!(parse_tool_call_body(&GEMMA4, "call:f").is_none());
        // Missing function name.
        assert!(parse_tool_call_body(&GEMMA4, "call:{}").is_none());
    }

    #[test]
    fn parse_qwen35_function_with_parameters() {
        let parsed = parse_tool_call_body(
            &QWEN35,
            "<function=get_current_weather>\n<parameter=location>\nParis\n</parameter>\n</function>",
        )
        .expect("parse");
        assert_eq!(parsed.name, "get_current_weather");
        let v: serde_json::Value = serde_json::from_str(&parsed.arguments_json).expect("arg JSON");
        // Qwen recommends `tojson`; bare `Paris` is not valid JSON → string fallback.
        assert_eq!(v["location"], "Paris");
    }

    #[test]
    fn parse_qwen35_function_with_jsonish_value() {
        let parsed = parse_tool_call_body(
            &QWEN35,
            "<function=set>\n<parameter=count>\n42\n</parameter>\n</function>",
        )
        .expect("parse");
        let v: serde_json::Value = serde_json::from_str(&parsed.arguments_json).expect("arg JSON");
        // 42 IS valid JSON → number.
        assert_eq!(v["count"], 42);
    }

    #[test]
    fn parse_qwen35_invalid_returns_none() {
        assert!(parse_tool_call_body(&QWEN35, "garbage").is_none());
        assert!(parse_tool_call_body(&QWEN35, "<function=>").is_none());
    }

    // Merge adjacent same-slot runs — useful for asserting against streaming
    // output where the splitter might emit a Content run as two pieces split
    // on the tail-buffer boundary.
    fn coalesce(v: &[(SplitSlot, String)]) -> Vec<(SplitSlot, String)> {
        let mut out: Vec<(SplitSlot, String)> = Vec::new();
        for (slot, s) in v {
            if let Some(last) = out.last_mut() {
                if last.0 == *slot {
                    last.1.push_str(s);
                    continue;
                }
            }
            out.push((*slot, s.clone()));
        }
        out
    }

    // -----------------------------------------------------------------------
    // T1.8 Option B — tool_call_gbnf accept/reject tests
    //
    // Each test:
    //   1. Calls `reg.tool_call_gbnf(fn_name, params_schema)` → GBNF string.
    //   2. Parses it with `grammar::parser::parse` → `Grammar`.
    //   3. Runs `GrammarRuntime::new` → `GrammarRuntime`.
    //   4. Feeds a candidate byte string with `accept_bytes`; asserts
    //      `is_accepted()` for valid inputs and `!(ok && is_accepted())`
    //      for invalid ones.
    //
    // Import from the sibling grammar module (available as
    // `crate::serve::api::grammar::*` inside the test context).
    // -----------------------------------------------------------------------

    fn grammar_runtime_for_gbnf(gbnf: &str) -> crate::serve::api::grammar::sampler::GrammarRuntime {
        let g = crate::serve::api::grammar::parser::parse(gbnf)
            .unwrap_or_else(|e| panic!("parse GBNF:\n{}\nerror: {}", gbnf, e));
        let rid = g
            .rule_id("root")
            .unwrap_or_else(|| panic!("no root rule in GBNF:\n{}", gbnf));
        crate::serve::api::grammar::sampler::GrammarRuntime::new(g, rid)
            .unwrap_or_else(|| panic!("GrammarRuntime::new returned None for GBNF:\n{}", gbnf))
    }

    fn gemma4_runtime(
        fn_name: &str,
        schema_json: &str,
    ) -> crate::serve::api::grammar::sampler::GrammarRuntime {
        // Wave 2.7 W-η: legacy tests use body-only grammars (no markers in the
        // grammar; lazy/auto path).  Tests that exercise the eager
        // marker-wrapped form pass `OneOrMoreCalls{...}` directly via the
        // public emitter API.
        let schema: serde_json::Value = serde_json::from_str(schema_json).unwrap();
        let gbnf = GEMMA4
            .tool_call_gbnf(fn_name, &schema, GrammarShape::SingleBody)
            .unwrap_or_else(|e| panic!("tool_call_gbnf error: {}", e));
        grammar_runtime_for_gbnf(&gbnf)
    }

    fn qwen35_runtime(
        fn_name: &str,
        schema_json: &str,
    ) -> crate::serve::api::grammar::sampler::GrammarRuntime {
        let schema: serde_json::Value = serde_json::from_str(schema_json).unwrap();
        let gbnf = QWEN35
            .tool_call_gbnf(fn_name, &schema, GrammarShape::SingleBody)
            .unwrap_or_else(|e| panic!("tool_call_gbnf error: {}", e));
        grammar_runtime_for_gbnf(&gbnf)
    }

    fn deepseek4_runtime(
        fn_name: &str,
        schema_json: &str,
        shape: GrammarShape,
    ) -> crate::serve::api::grammar::sampler::GrammarRuntime {
        let schema: serde_json::Value = serde_json::from_str(schema_json).unwrap();
        let gbnf = DEEPSEEK4
            .tool_call_gbnf(fn_name, &schema, shape)
            .unwrap_or_else(|error| panic!("tool_call_gbnf error: {error}"));
        grammar_runtime_for_gbnf(&gbnf)
    }

    #[test]
    fn deepseek4_registration_and_multi_invoke_parser_are_openai_compatible() {
        let registration = find_for("DeepSeek-V4-Flash-0731").expect("DeepSeek registration");
        assert_eq!(registration.family, "deepseek4");
        assert_eq!(
            find_for("Deepseek v4 Flash 0731 Source")
                .expect("converted general.name registration")
                .family,
            "deepseek4"
        );
        let body = "\n<|DSML|invoke name=\"read_file\">\n<|DSML|parameter name=\"path\" string=\"true\">src/main.rs</|DSML|parameter>\n</|DSML|invoke>\n<|DSML|invoke name=\"run_tests\">\n<|DSML|parameter name=\"all\" string=\"false\">true</|DSML|parameter>\n</|DSML|invoke>\n";
        let calls = parse_tool_call_bodies(&registration, body).expect("parse DSML block");
        assert_eq!(calls.len(), 2);
        assert_eq!(calls[0].name, "read_file");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&calls[0].arguments_json).unwrap(),
            serde_json::json!({"path": "src/main.rs"})
        );
        assert_eq!(calls[1].name, "run_tests");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&calls[1].arguments_json).unwrap(),
            serde_json::json!({"all": true})
        );
    }

    #[test]
    fn deepseek4_required_grammar_enforces_required_parameter() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "line": {"type": "integer"}
            },
            "required": ["path"]
        }"#;
        let mut accepted = deepseek4_runtime(
            "read_file",
            schema,
            GrammarShape::OneOrMoreCalls { parallel: false },
        );
        let valid = "<|DSML|tool_calls>\n<|DSML|invoke name=\"read_file\">\n<|DSML|parameter name=\"path\" string=\"true\">src/lib.rs</|DSML|parameter>\n</|DSML|invoke>\n</|DSML|tool_calls>";
        assert!(accepted.accept_bytes(valid.as_bytes()));
        assert!(accepted.is_accepted());

        let mut rejected = deepseek4_runtime(
            "read_file",
            schema,
            GrammarShape::OneOrMoreCalls { parallel: false },
        );
        let missing = "<|DSML|tool_calls>\n<|DSML|invoke name=\"read_file\">\n<|DSML|parameter name=\"line\" string=\"false\">7</|DSML|parameter>\n</|DSML|invoke>\n</|DSML|tool_calls>";
        let alive = rejected.accept_bytes(missing.as_bytes());
        assert!(!(alive && rejected.is_accepted()));
    }

    #[test]
    fn deepseek4_parallel_grammar_uses_one_outer_block() {
        let schema = r#"{"type":"object","properties":{}}"#;
        let mut runtime = deepseek4_runtime(
            "ping",
            schema,
            GrammarShape::OneOrMoreCalls { parallel: true },
        );
        let calls = "<|DSML|tool_calls>\n<|DSML|invoke name=\"ping\">\n\n</|DSML|invoke>\n<|DSML|invoke name=\"ping\">\n\n</|DSML|invoke>\n</|DSML|tool_calls>";
        assert!(runtime.accept_bytes(calls.as_bytes()));
        assert!(runtime.is_accepted());
    }

    // -----------------------------------------------------------------------
    // Gemma 4 grammar tests
    // -----------------------------------------------------------------------

    /// Canonical Gemma 4 emission for `get_weather(location: "SF", unit: "F")`.
    /// The grammar must accept the exact string that `parse_gemma4_tool_call`
    /// would successfully parse.
    #[test]
    fn gemma4_tool_call_grammar_accepts_canonical_emission() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            }
        }"#;
        let mut rt = gemma4_runtime("get_weather", schema);
        // Canonical emission: `call:get_weather{location:<|"|>SF<|"|>,unit:<|"|>fahrenheit<|"|>}`
        let input = b"call:get_weather{location:<|\"|>SF<|\"|>,unit:<|\"|>fahrenheit<|\"|>}";
        assert!(rt.accept_bytes(input), "canonical emission rejected");
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// The grammar must also accept the case where keys appear in the
    /// opposite order (unit before location) — since `parse_gemma4_tool_call`
    /// is order-agnostic and we use a Kleene-star kv-list.
    #[test]
    fn gemma4_tool_call_grammar_accepts_reversed_key_order() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {"type": "string"}
            }
        }"#;
        let mut rt = gemma4_runtime("get_weather", schema);
        let input = b"call:get_weather{unit:<|\"|>celsius<|\"|>,location:<|\"|>London<|\"|>}";
        assert!(rt.accept_bytes(input), "reversed key order rejected");
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// The grammar must accept a numeric argument (no `<|"|>` wrapping).
    #[test]
    fn gemma4_tool_call_grammar_accepts_numeric_arg() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "count": {"type": "integer"},
                "enabled": {"type": "boolean"}
            }
        }"#;
        let mut rt = gemma4_runtime("do_thing", schema);
        let input = b"call:do_thing{count:42,enabled:true}";
        assert!(rt.accept_bytes(input), "numeric+boolean args rejected");
        assert!(rt.is_accepted(), "not accepted");
    }

    /// A malformed wrapper prefix (`call_:` with underscore instead of `:`)
    /// must be rejected.
    #[test]
    fn gemma4_tool_call_grammar_rejects_malformed_wrapper_prefix() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = gemma4_runtime("get_weather", schema);
        // `call_:get_weather{...}` — underscore between `call` and `:`.
        let input = b"call_:get_weather{location:<|\"|>SF<|\"|>}";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "malformed prefix accepted (should reject)"
        );
    }

    /// A wrong delimiter (parentheses instead of braces) must be rejected.
    #[test]
    fn gemma4_tool_call_grammar_rejects_wrong_delimiter() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = gemma4_runtime("get_weather", schema);
        // `call:get_weather(SF)` — parentheses instead of braces.
        let input = b"call:get_weather(SF)";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "wrong delimiter accepted (should reject)"
        );
    }

    /// When additionalProperties:false is not explicitly declared in the
    /// parameters schema, the grammar uses a Kleene-star kv-list that accepts
    /// any key from the declared set. An *undeclared* key wrapped in
    /// `<|"|>` should still be accepted because the grammar uses an item
    /// alternation (any known key) — however a key name that doesn't match
    /// any known literal WILL be rejected because the item rule only contains
    /// the declared key literals.
    ///
    /// Note: unlike json_schema's additionalProperties enforcement, the Gemma
    /// kv-list grammar does not try to reject unknown keys — that would require
    /// the O(2^N) permutation algorithm with "used-key" tracking. Instead,
    /// extra fields at runtime are handled by parse_gemma4_tool_call (which
    /// ignores them) or by the schema-level validation at the API layer.
    #[test]
    fn gemma4_tool_call_grammar_empty_args_accepted() {
        let schema = r#"{"type": "object", "properties": {}}"#;
        let mut rt = gemma4_runtime("noop", schema);
        let input = b"call:noop{}";
        assert!(rt.accept_bytes(input), "empty args form rejected");
        assert!(rt.is_accepted(), "not accepted");
    }

    /// iter-219b grammar-exhaust regression guard (2026-05-01) — Agent C's
    /// audit found that `space ::= | " " | "\n"{1,2} [ \t]{0,20}` keeps
    /// `is_dead` from ever flipping after the close marker is consumed
    /// (empty alt + `[ \t]{0,20}` min 0 → runtime perpetually accepting
    /// AND alive). iter-218 claimed "natural grammar-exhaust" termination
    /// for `OneOrMoreCallsBodyOnly{parallel:false}`, but the engine's
    /// break gate at `engine.rs:5045-5059` (`is_accepted && bytes.is_empty()`)
    /// only fires for empty-byte tokens; `<tool_call|>` decodes to 12
    /// bytes (non-empty) so the loop runs past close marker until
    /// max_tokens. This test pins the contract:
    ///
    ///   After accepting `<body><close_marker>`, the grammar MUST be in
    ///   a TERMINAL state — any subsequent byte must terminate (kill all
    ///   stacks; `is_dead == true`). Trailing whitespace allowance was
    ///   the source of the close-gate gap.
    ///
    /// PRE-FIX HEAD: this test FAILS at the `assert!(!alive)` line
    /// because `space`'s `\n{1,2}` alt accepts the trailing newline.
    /// POST-FIX (drop trailing `space` from `OneOrMoreCallsBodyOnly{false}`
    /// + `SingleBody` root_body): this test PASSES.
    #[test]
    fn iter219b_grammar_exhaust_after_close_marker_is_terminal() {
        let schema_json = r#"{"type":"object","properties":{"x":{"type":"integer"}}}"#;
        let schema_v: serde_json::Value = serde_json::from_str(schema_json).unwrap();
        let gbnf = GEMMA4
            .tool_call_gbnf(
                "f",
                &schema_v,
                GrammarShape::OneOrMoreCallsBodyOnly { parallel: false },
            )
            .expect("tool_call_gbnf");
        let mut rt = grammar_runtime_for_gbnf(&gbnf);
        // Accept canonical body + close marker per the lazy-gate contract
        // (open marker has been stripped from the grammar — consumed by the
        // awaiting_trigger no-op gate before grammar engagement).
        assert!(
            rt.accept_bytes(b"call:f{x:1}<tool_call|>"),
            "canonical body+close rejected"
        );
        assert!(
            rt.is_accepted(),
            "post-close: rule must be in an accepting state"
        );
        // Contract: any further byte must terminate the grammar. iter-218's
        // claimed grammar-exhaust termination relies on this — without it,
        // the decode loop runs past close marker because the engine's
        // `is_accepted && bytes.is_empty()` break gate only fires for
        // empty-byte tokens and `<tool_call|>` decodes to 12 bytes.
        let mut clone_lf = rt.clone();
        let alive_after_lf = clone_lf.accept_bytes(b"\n");
        assert!(
            !alive_after_lf,
            "iter-219b: grammar must terminate on trailing `\\n` after close \
             marker; HEAD's `space ::= | \" \" | \"\\n\"{{1,2}} [ \\t]{{0,20}}` \
             allows up to 22 trailing whitespace bytes which prevents \
             `is_dead` from flipping. Drop the trailing ` space` from \
             OneOrMoreCallsBodyOnly{{false}} + SingleBody root_body."
        );
        assert!(
            clone_lf.is_dead(),
            "is_dead must flip to true after rejected continuation post-close"
        );
        // Same contract for a non-whitespace byte (start of stray
        // `<|tool_response>` from the LIVE bug surface).
        let mut clone_lt = rt.clone();
        let alive_after_lt = clone_lt.accept_bytes(b"<");
        assert!(
            !alive_after_lt,
            "iter-219b: post-close grammar must reject `<` (start of any \
             special-token leak like <|tool_response>)"
        );
        assert!(
            clone_lt.is_dead(),
            "is_dead must flip on rejected `<` after close"
        );
    }

    // -----------------------------------------------------------------------
    // Qwen 3.5/3.6 grammar tests
    // -----------------------------------------------------------------------

    /// Canonical Qwen 3.5 emission for `get_weather(location: "Paris")`.
    #[test]
    fn qwen35_tool_call_grammar_accepts_canonical_emission() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {"type": "string"}
            }
        }"#;
        let mut rt = qwen35_runtime("get_weather", schema);
        // Canonical Qwen emission (template emits `\n` around values):
        let input = b"<function=get_weather>\n<parameter=location>\nParis\n</parameter>\n<parameter=unit>\ncelsius\n</parameter>\n</function>";
        assert!(rt.accept_bytes(input), "canonical Qwen35 emission rejected");
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// Reversed parameter order must be accepted (Kleene-star approach).
    #[test]
    fn qwen35_tool_call_grammar_accepts_reversed_param_order() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {"type": "string"}
            }
        }"#;
        let mut rt = qwen35_runtime("get_weather", schema);
        let input = b"<function=get_weather>\n<parameter=unit>\nfahrenheit\n</parameter>\n<parameter=location>\nSF\n</parameter>\n</function>";
        assert!(rt.accept_bytes(input), "reversed param order rejected");
        assert!(rt.is_accepted(), "not accepted");
    }

    /// A malformed function wrapper (wrong tag syntax) must be rejected.
    #[test]
    fn qwen35_tool_call_grammar_rejects_malformed_wrapper() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = qwen35_runtime("get_weather", schema);
        // `[function=get_weather]` — square brackets instead of angle brackets.
        let input =
            b"[function=get_weather]\n[parameter=location]\nParis\n[/parameter]\n[/function]";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "malformed wrapper accepted (should reject)"
        );
    }

    /// Empty parameter list (no arguments).
    #[test]
    fn qwen35_tool_call_grammar_accepts_empty_params() {
        let schema = r#"{"type": "object", "properties": {}}"#;
        let mut rt = qwen35_runtime("ping", schema);
        let input = b"<function=ping></function>";
        assert!(rt.accept_bytes(input), "empty params form rejected");
        assert!(rt.is_accepted(), "not accepted");
    }

    /// Verify the GBNF round-trips: grammar accepts output that
    /// `parse_qwen35_tool_call` can also parse back.  Closes the loop:
    /// grammar-constrained → parseable.
    #[test]
    fn qwen35_grammar_accepted_output_is_parseable() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {"type": "string"}
            }
        }"#;
        let body = "<function=get_weather>\n<parameter=location>\nParis\n</parameter>\n<parameter=unit>\ncelsius\n</parameter>\n</function>";
        // Grammar accepts it.
        let mut rt = qwen35_runtime("get_weather", schema);
        assert!(rt.accept_bytes(body.as_bytes()), "grammar rejected body");
        assert!(rt.is_accepted());
        // parse_qwen35_tool_call also parses it.
        let parsed = parse_tool_call_body(&QWEN35, body).expect("parse_tool_call_body failed");
        assert_eq!(parsed.name, "get_weather");
        let v: serde_json::Value = serde_json::from_str(&parsed.arguments_json).unwrap();
        assert_eq!(v["location"], "Paris");
        assert_eq!(v["unit"], "celsius");
    }

    /// Verify the Gemma 4 grammar round-trip: grammar accepts output that
    /// `parse_gemma4_tool_call` can also parse back.
    #[test]
    fn gemma4_grammar_accepted_output_is_parseable() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
            }
        }"#;
        let body = "call:get_weather{location:<|\"|>San Francisco<|\"|>,unit:<|\"|>celsius<|\"|>}";
        // Grammar accepts it.
        let mut rt = gemma4_runtime("get_weather", schema);
        assert!(rt.accept_bytes(body.as_bytes()), "grammar rejected body");
        assert!(rt.is_accepted());
        // parse_gemma4_tool_call also parses it.
        let parsed = parse_tool_call_body(&GEMMA4, body).expect("parse_tool_call_body failed");
        assert_eq!(parsed.name, "get_weather");
        let v: serde_json::Value = serde_json::from_str(&parsed.arguments_json).unwrap();
        assert_eq!(v["location"], "San Francisco");
        assert_eq!(v["unit"], "celsius");
    }

    /// Unknown model family returns Err from tool_call_gbnf.
    #[test]
    fn unknown_family_tool_call_gbnf_returns_err() {
        let unknown = ModelRegistration {
            family: "unknown_llama",
            id_substrings: &["unknown_llama"],
            reasoning_open: None,
            reasoning_close: None,
            tool_open: None,
            tool_close: None,
            tool_preamble: None,
        };
        let schema: serde_json::Value = serde_json::json!({});
        let result = unknown.tool_call_gbnf("f", &schema, GrammarShape::SingleBody);
        assert!(result.is_err(), "expected Err for unknown family");
        assert!(result.unwrap_err().contains("unknown_llama"));
    }

    // -----------------------------------------------------------------------
    // Wave 2.5 B1 — Required parameter enforcement tests
    // -----------------------------------------------------------------------

    /// B1 Gemma4: schema with `required` — required key present → accept.
    #[test]
    fn b1_gemma4_required_present_accept() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "city": {"type": "string"},
                "units": {"type": "string"}
            },
            "required": ["city"]
        }"#;
        let mut rt = gemma4_runtime("get_weather", schema);
        // city is required; units is optional but we include it too.
        let input = b"call:get_weather{city:<|\"|>Paris<|\"|>,units:<|\"|>metric<|\"|>}";
        assert!(
            rt.accept_bytes(input),
            "required key present should be accepted"
        );
        assert!(rt.is_accepted());
    }

    /// B1 Gemma4: schema with `required` — required key absent → reject.
    #[test]
    fn b1_gemma4_required_missing_reject() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "city": {"type": "string"},
                "units": {"type": "string"}
            },
            "required": ["city"]
        }"#;
        let mut rt = gemma4_runtime("get_weather", schema);
        // Only units supplied; city (required) is absent.
        let input = b"call:get_weather{units:<|\"|>metric<|\"|>}";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "missing required key must be rejected"
        );
    }

    /// B1 Gemma4: required key permuted (opposite order) → still accepted.
    #[test]
    fn b1_gemma4_required_permuted_accept() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "a": {"type": "integer"},
                "b": {"type": "integer"}
            },
            "required": ["a", "b"]
        }"#;
        let mut rt = gemma4_runtime("add", schema);
        // b before a — permutation grammar must accept both orderings.
        let input = b"call:add{b:2,a:1}";
        assert!(
            rt.accept_bytes(input),
            "permuted required keys must be accepted"
        );
        assert!(rt.is_accepted());
    }

    /// B1 Gemma4: schema with 9 required keys → EmitterError::TooManyRequiredKeys.
    /// W-ζ: cap lowered from 16 to 8 to match json_schema.rs ANY_ORDER_MAX_REQUIRED.
    #[test]
    fn b1_gemma4_too_many_required_keys_err() {
        // Build a schema with 9 required keys (> MAX_REQUIRED_KEYS = 8).
        let mut props = serde_json::Map::new();
        let mut required = Vec::new();
        for i in 0..9usize {
            let k = format!("key{}", i);
            props.insert(k.clone(), serde_json::json!({"type": "string"}));
            required.push(serde_json::Value::String(k));
        }
        let schema = serde_json::json!({
            "type": "object",
            "properties": props,
            "required": required
        });
        let result = GEMMA4.tool_call_gbnf("f", &schema, GrammarShape::SingleBody);
        assert!(result.is_err(), "9 required keys must return Err");
        let msg = result.unwrap_err();
        assert!(
            msg.contains("9"),
            "error message should mention count: {}",
            msg
        );
        assert!(
            msg.contains("8"),
            "error message should mention cap: {}",
            msg
        );
    }

    /// W-ζ HIGH-2: Gemma4 boundary — exactly 8 required keys compiles OK.
    #[test]
    fn nine_required_keys_in_gemma_tool_call_gbnf_returns_too_many_required_keys() {
        // 9 keys — must be rejected (boundary at 8).
        let mut props = serde_json::Map::new();
        let mut required = Vec::new();
        for i in 0..9usize {
            let k = format!("p{}", i);
            props.insert(k.clone(), serde_json::json!({"type": "integer"}));
            required.push(serde_json::Value::String(k));
        }
        let schema = serde_json::json!({
            "type": "object",
            "properties": props,
            "required": required
        });
        let result = GEMMA4.tool_call_gbnf("tool9", &schema, GrammarShape::SingleBody);
        assert!(
            result.is_err(),
            "9 required keys must return TooManyRequiredKeys"
        );
        let msg = result.unwrap_err();
        assert!(msg.contains("9"), "error must mention count 9: {}", msg);
        assert!(msg.contains("8"), "error must mention cap 8: {}", msg);
    }

    /// W-ζ HIGH-2: Gemma4 boundary — exactly 8 required keys compiles OK.
    #[test]
    fn eight_required_keys_in_gemma_tool_call_gbnf_compiles_ok() {
        let mut props = serde_json::Map::new();
        let mut required = Vec::new();
        for i in 0..8usize {
            let k = format!("p{}", i);
            props.insert(k.clone(), serde_json::json!({"type": "integer"}));
            required.push(serde_json::Value::String(k));
        }
        let schema = serde_json::json!({
            "type": "object",
            "properties": props,
            "required": required
        });
        let result = GEMMA4.tool_call_gbnf("tool8", &schema, GrammarShape::SingleBody);
        assert!(result.is_ok(), "8 required keys must compile without error");
    }

    /// B1 Qwen35: required key present → accept.
    #[test]
    fn b1_qwen35_required_present_accept() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "city": {"type": "string"},
                "units": {"type": "string"}
            },
            "required": ["city"]
        }"#;
        let mut rt = qwen35_runtime("get_weather", schema);
        let input = b"<function=get_weather>\n<parameter=city>\nParis\n</parameter>\n<parameter=units>\nmetric\n</parameter>\n</function>";
        assert!(
            rt.accept_bytes(input),
            "required key present should be accepted"
        );
        assert!(rt.is_accepted());
    }

    /// B1 Qwen35: required key absent → reject.
    #[test]
    fn b1_qwen35_required_missing_reject() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "city": {"type": "string"},
                "units": {"type": "string"}
            },
            "required": ["city"]
        }"#;
        let mut rt = qwen35_runtime("get_weather", schema);
        // Only units supplied; city (required) is absent.
        let input = b"<function=get_weather>\n<parameter=units>\nmetric\n</parameter>\n</function>";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "missing required key must be rejected"
        );
    }

    /// B1 Qwen35: required keys permuted → accept.
    #[test]
    fn b1_qwen35_required_permuted_accept() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "a": {"type": "integer"},
                "b": {"type": "integer"}
            },
            "required": ["a", "b"]
        }"#;
        let mut rt = qwen35_runtime("add", schema);
        // b before a.
        let input = b"<function=add>\n<parameter=b>\n2\n</parameter>\n<parameter=a>\n1\n</parameter>\n</function>";
        assert!(
            rt.accept_bytes(input),
            "permuted required keys must be accepted"
        );
        assert!(rt.is_accepted());
    }

    /// B1 Qwen35: 9 required keys → EmitterError::TooManyRequiredKeys.
    /// W-ζ: cap lowered from 16 to 8 to match json_schema.rs ANY_ORDER_MAX_REQUIRED.
    #[test]
    fn b1_qwen35_too_many_required_keys_err() {
        let mut props = serde_json::Map::new();
        let mut required = Vec::new();
        for i in 0..9usize {
            let k = format!("key{}", i);
            props.insert(k.clone(), serde_json::json!({"type": "string"}));
            required.push(serde_json::Value::String(k));
        }
        let schema = serde_json::json!({
            "type": "object",
            "properties": props,
            "required": required
        });
        let result = QWEN35.tool_call_gbnf("f", &schema, GrammarShape::SingleBody);
        assert!(result.is_err(), "9 required keys must return Err");
        let msg = result.unwrap_err();
        assert!(
            msg.contains("9"),
            "error message should mention count: {}",
            msg
        );
        assert!(
            msg.contains("8"),
            "error message should mention cap: {}",
            msg
        );
    }

    /// W-ζ HIGH-2: Qwen35 boundary — 9 required keys returns TooManyRequiredKeys.
    #[test]
    fn nine_required_keys_in_qwen35_tool_call_gbnf_returns_too_many_required_keys() {
        let mut props = serde_json::Map::new();
        let mut required = Vec::new();
        for i in 0..9usize {
            let k = format!("q{}", i);
            props.insert(k.clone(), serde_json::json!({"type": "string"}));
            required.push(serde_json::Value::String(k));
        }
        let schema = serde_json::json!({
            "type": "object",
            "properties": props,
            "required": required
        });
        let result = QWEN35.tool_call_gbnf("qtool9", &schema, GrammarShape::SingleBody);
        assert!(
            result.is_err(),
            "9 required keys must return TooManyRequiredKeys"
        );
        let msg = result.unwrap_err();
        assert!(msg.contains("9"), "error must mention count 9: {}", msg);
        assert!(msg.contains("8"), "error must mention cap 8: {}", msg);
    }

    /// W-ζ HIGH-2: Qwen35 boundary — exactly 8 required keys compiles OK.
    #[test]
    fn eight_required_keys_in_qwen35_tool_call_gbnf_compiles_ok() {
        let mut props = serde_json::Map::new();
        let mut required = Vec::new();
        for i in 0..8usize {
            let k = format!("q{}", i);
            props.insert(k.clone(), serde_json::json!({"type": "string"}));
            required.push(serde_json::Value::String(k));
        }
        let schema = serde_json::json!({
            "type": "object",
            "properties": props,
            "required": required
        });
        let result = QWEN35.tool_call_gbnf("qtool8", &schema, GrammarShape::SingleBody);
        assert!(result.is_ok(), "8 required keys must compile without error");
    }

    // -----------------------------------------------------------------------
    // iter-231a (supersedes Wave 2.5 B3) — structured-parameter acceptance
    //
    // Pre-iter-231a these pinned a hard `EmitterError::UnsupportedSchema`
    // rejection for `array`/`object` params (→ HTTP 400 for the whole
    // request).  That gate broke real-world tool schemas (MCP servers
    // expose free-form `object` params such as `config`, `arguments`).
    // The grammar now compiles such params to permissive recursive value
    // rules and ACCEPTS any well-formed structured value.
    // -----------------------------------------------------------------------

    /// iter-231a Gemma4: `array` param compiles AND the runtime accepts a
    /// nested kv-list value exactly as `format_argument` renders it.
    #[test]
    fn iter231a_gemma4_array_param_compiles_and_accepts_nested_value() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "tags": {"type": "array"},
                "name": {"type": "string"}
            }
        }"#;
        let mut rt = gemma4_runtime("tag_item", schema);
        // format_argument: strings `<|"|>...<|"|>`, scalars bare, nested
        // containers recursive, keys bare (escape_keys=False).
        let input = b"call:tag_item{name:<|\"|>x<|\"|>,tags:[<|\"|>a<|\"|>,<|\"|>b<|\"|>,1,true,null,[2,{k:<|\"|>v<|\"|>}]]}";
        assert!(rt.accept_bytes(input), "nested array value rejected");
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// iter-231a Gemma4: `object` param compiles AND accepts a nested
    /// object with bare keys at every level (escape_keys=False).
    #[test]
    fn iter231a_gemma4_object_param_compiles_and_accepts_nested_value() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "config": {"type": "object"}
            }
        }"#;
        let mut rt = gemma4_runtime("configure", schema);
        let input = b"call:configure{config:{model:<|\"|>sonnet<|\"|>,retries:3,nested:{on:true,ids:[1,2]}}}";
        assert!(rt.accept_bytes(input), "nested object value rejected");
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// iter-231a Qwen35: `array` param compiles AND accepts nested compact
    /// JSON (what the template's `tojson` filter emits).
    #[test]
    fn iter231a_qwen35_array_param_compiles_and_accepts_nested_value() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "tags": {"type": "array"}
            }
        }"#;
        let mut rt = qwen35_runtime("tag_item", schema);
        let input = b"<function=tag_item>\n<parameter=tags>\n[\"a\",\"b\",1,true,null,[2,{\"k\":\"v\"}]]\n</parameter>\n</function>";
        assert!(rt.accept_bytes(input), "nested JSON array rejected");
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// iter-231a Qwen35: `object` param compiles AND accepts nested
    /// compact JSON with mixed scalar/container children.
    #[test]
    fn iter231a_qwen35_object_param_compiles_and_accepts_nested_value() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "metadata": {"type": "object"}
            }
        }"#;
        let mut rt = qwen35_runtime("set_meta", schema);
        let input = b"<function=set_meta>\n<parameter=metadata>\n{\"model\":\"sonnet\",\"retries\":3,\"nested\":{\"on\":true,\"ids\":[1,2]}}\n</parameter>\n</function>";
        assert!(rt.accept_bytes(input), "nested JSON object rejected");
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// iter-231a regression — the exact failure shape that motivated the
    /// supersession: an MCP-style tool schema with a free-form `object`
    /// parameter (`config`) plus scalars and an enum.  Pre-iter-231a this
    /// 400'd the entire request at grammar-compile time; opencode and
    /// other agentic clients could not call ANY tool once such a schema
    /// was present in tools[].
    #[test]
    fn iter231a_qwen35_mcp_tool_with_freeform_object_param_compiles_and_runs() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "agentType": {"type": "string"},
                "config": {"type": "object"},
                "memoryDimension": {"type": "integer"},
                "model": {"type": "string", "enum": ["haiku", "sonnet", "opus"]},
                "task": {"type": "string"}
            }
        }"#;
        let mut rt = qwen35_runtime("agent_spawn", schema);
        let input = b"<function=agent_spawn>\n<parameter=agentType>\ncoder\n</parameter>\n<parameter=config>\n{\"maxTurns\":50,\"env\":{\"KEY\":\"value\"},\"nested\":[1,{\"x\":true}]}\n</parameter>\n<parameter=memoryDimension>\n384\n</parameter>\n<parameter=model>\nsonnet\n</parameter>\n<parameter=task>\nimplement feature\n</parameter>\n</function>";
        assert!(rt.accept_bytes(input), "MCP-shaped call rejected");
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// iter-231a structural guard: the JSON-string char rule excludes `<`
    /// so a structured value can never swallow the `</parameter>` close
    /// tag (same conservative contract as `qwen35-str-char`).
    #[test]
    fn iter231a_qwen35_object_param_rejects_angle_bracket_in_json_string() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "config": {"type": "object"}
            }
        }"#;
        let mut rt = qwen35_runtime("configure", schema);
        // `<` inside a JSON string would let the value eat the close tag.
        let input = b"<function=configure>\n<parameter=config>\n{\"a\":\"<bad\"}\n</parameter>\n</function>";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "JSON string containing `<` accepted (must reject — close-tag safety)"
        );
    }

    /// iter-231a integration: scalar params still compile and run under
    /// both emitters (supersession must not regress scalars).
    #[test]
    fn iter231a_scalar_params_unaffected() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "count": {"type": "integer"},
                "enabled": {"type": "boolean"}
            }
        });
        assert!(
            GEMMA4
                .tool_call_gbnf("f", &schema, GrammarShape::SingleBody)
                .is_ok(),
            "scalars must compile"
        );
        assert!(
            QWEN35
                .tool_call_gbnf("f", &schema, GrammarShape::SingleBody)
                .is_ok(),
            "scalars must compile"
        );
    }

    // -----------------------------------------------------------------------
    // iter-231b — full-fidelity nested-schema compilation
    //
    // Structured parameters now constrain everything the schema DECLARES
    // (properties, required, typed items, enums, unions, additionalProperties)
    // and stay open only where the schema itself is open (free-form
    // object/array → permissive recursive value).  Same contract as the
    // top-level parameter grammar: required keys in any order first, then
    // optional keys in any order.
    // -----------------------------------------------------------------------

    /// Qwen35: nested object with declared properties — required keys are
    /// accepted in ANY order (permutation grammar), compact tojson form.
    #[test]
    fn iter231b_qwen35_nested_object_required_keys_any_order() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {
                        "host": {"type": "string"},
                        "port": {"type": "integer"},
                        "tls": {"type": "boolean"}
                    },
                    "required": ["host", "port"]
                }
            }
        }"#;
        // host before port.
        let mut rt = qwen35_runtime("connect", schema);
        let input = b"<function=connect>\n<parameter=server>\n{\"host\":\"example.com\",\"port\":443}\n</parameter>\n</function>";
        assert!(rt.accept_bytes(input), "declared-order rejected");
        assert!(rt.is_accepted());
        // port before host (required any-order), plus optional tls.
        let mut rt2 = qwen35_runtime("connect", schema);
        let input2 = b"<function=connect>\n<parameter=server>\n{\"port\":443,\"host\":\"example.com\",\"tls\":true}\n</parameter>\n</function>";
        assert!(rt2.accept_bytes(input2), "reversed required order rejected");
        assert!(rt2.is_accepted());
    }

    /// Qwen35: omitting a nested required key must be REJECTED by the
    /// grammar (the model physically cannot emit that token path).
    #[test]
    fn iter231b_qwen35_nested_object_missing_required_rejected() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {
                        "host": {"type": "string"},
                        "port": {"type": "integer"}
                    },
                    "required": ["host", "port"]
                }
            }
        }"#;
        let mut rt = qwen35_runtime("connect", schema);
        // port missing — the permutation grammar can never complete.
        let input = b"<function=connect>\n<parameter=server>\n{\"host\":\"example.com\"}\n</parameter>\n</function>";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "nested object missing a required key accepted (must reject)"
        );
    }

    /// Qwen35: `additionalProperties:false` closes the nested key set —
    /// an undeclared key is rejected; the same shape WITHOUT the flag
    /// (open, JSON Schema default) accepts it via the wildcard kv tail.
    #[test]
    fn iter231b_qwen35_nested_object_additional_properties_gate() {
        let closed = r#"{
            "type": "object",
            "properties": {
                "cfg": {
                    "type": "object",
                    "properties": {"a": {"type": "integer"}},
                    "required": ["a"],
                    "additionalProperties": false
                }
            }
        }"#;
        let mut rt = qwen35_runtime("f", closed);
        let input =
            b"<function=f>\n<parameter=cfg>\n{\"a\":1,\"zzz\":2}\n</parameter>\n</function>";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "additionalProperties:false accepted an undeclared key"
        );

        let open = r#"{
            "type": "object",
            "properties": {
                "cfg": {
                    "type": "object",
                    "properties": {"a": {"type": "integer"}},
                    "required": ["a"]
                }
            }
        }"#;
        let mut rt2 = qwen35_runtime("f", open);
        assert!(
            rt2.accept_bytes(input),
            "open object rejected an extra key (wildcard tail must accept)"
        );
        assert!(rt2.is_accepted());
    }

    /// Qwen35: typed array items are enforced — `items:{type:"string"}`
    /// accepts `["a","b"]` and rejects `[1,2]`.
    #[test]
    fn iter231b_qwen35_nested_array_typed_items_enforced() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "tags": {"type": "array", "items": {"type": "string"}}
            }
        }"#;
        let mut rt = qwen35_runtime("tag", schema);
        let good = b"<function=tag>\n<parameter=tags>\n[\"a\",\"b\"]\n</parameter>\n</function>";
        assert!(rt.accept_bytes(good), "string items rejected");
        assert!(rt.is_accepted());

        let mut rt2 = qwen35_runtime("tag", schema);
        let bad = b"<function=tag>\n<parameter=tags>\n[1,2]\n</parameter>\n</function>";
        let ok = rt2.accept_bytes(bad);
        assert!(
            !(ok && rt2.is_accepted()),
            "array with items:string accepted integer items (must reject)"
        );
    }

    /// Qwen35: nested enum + anyOf union bodies are enforced.
    ///
    /// NOTE on rejection strength (iter-231b documented contract): a
    /// REQUIRED key's value is always constrained by its declared grammar
    /// (the permutation position cannot be filled by the wildcard
    /// extra-kv branch), and a CLOSED object (`additionalProperties:
    /// false`) rejects any value/key mismatch.  For OPEN objects the
    /// wildcard extra-kv tail can re-match a declared OPTIONAL key with
    /// an unconstrained value — an inherent CFG limitation shared with
    /// llama.cpp + json_schema.rs (a CFG cannot express "any key except
    /// these").  The anyOf-mismatch rejection below is therefore asserted
    /// on a CLOSED object, where the guarantee holds.
    #[test]
    fn iter231b_qwen35_nested_enum_and_anyof() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "cfg": {
                    "type": "object",
                    "properties": {
                        "mode": {"enum": ["fast", "safe"]},
                        "limit": {"anyOf": [{"type": "integer"}, {"type": "null"}]}
                    },
                    "required": ["mode"],
                    "additionalProperties": false
                }
            }
        }"#;
        let mut rt = qwen35_runtime("f", schema);
        let good = b"<function=f>\n<parameter=cfg>\n{\"mode\":\"fast\",\"limit\":3}\n</parameter>\n</function>";
        assert!(rt.accept_bytes(good), "enum+anyOf valid value rejected");
        assert!(rt.is_accepted());

        let mut rt2 = qwen35_runtime("f", schema);
        // "warp" is not in the enum.
        let bad = b"<function=f>\n<parameter=cfg>\n{\"mode\":\"warp\"}\n</parameter>\n</function>";
        let ok = rt2.accept_bytes(bad);
        assert!(!(ok && rt2.is_accepted()), "undeclared enum value accepted");

        let mut rt3 = qwen35_runtime("f", schema);
        // "3.5" matches neither integer nor null branch of the anyOf, and
        // the object is CLOSED — no wildcard tail to rescue it.
        let bad2 = b"<function=f>\n<parameter=cfg>\n{\"mode\":\"safe\",\"limit\":3.5}\n</parameter>\n</function>";
        let ok2 = rt3.accept_bytes(bad2);
        assert!(
            !(ok2 && rt3.is_accepted()),
            "anyOf-mismatched value accepted on closed object"
        );
    }

    /// Qwen35 (documented contract): for OPEN objects the wildcard
    /// extra-kv tail accepts any well-formed JSON value for any key —
    /// including a declared optional key carrying a value that violates
    /// its declared sub-schema.  Pin the behavior so the caveat is
    /// explicit, not silent.
    #[test]
    fn iter231b_qwen35_open_object_wildcard_tail_documented() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "cfg": {
                    "type": "object",
                    "properties": {
                        "mode": {"enum": ["fast", "safe"]},
                        "limit": {"type": "integer"}
                    },
                    "required": ["mode"]
                }
            }
        }"#;
        let mut rt = qwen35_runtime("f", schema);
        // limit:3.5 violates items integer, but the OPEN object's
        // wildcard tail accepts it as an extra key (CFG limitation,
        // llama.cpp + json_schema.rs parity).  Value validation for
        // optional keys on open objects is the tool server's job.
        let input = b"<function=f>\n<parameter=cfg>\n{\"mode\":\"safe\",\"limit\":3.5}\n</parameter>\n</function>";
        assert!(
            rt.accept_bytes(input) && rt.is_accepted(),
            "open-object wildcard tail must accept (documented CFG limitation)"
        );
        // But a REQUIRED key mismatch is still physically impossible:
        let mut rt2 = qwen35_runtime("f", schema);
        let bad = b"<function=f>\n<parameter=cfg>\n{\"mode\":\"warp\",\"limit\":3}\n</parameter>\n</function>";
        assert!(
            !(rt2.accept_bytes(bad) && rt2.is_accepted()),
            "required-key enum mismatch must reject even on open objects"
        );
    }

    /// Qwen35: features the grammar cannot enforce are an honest 400
    /// (`UnsupportedSchemaFeature` naming feature + dot-path), not a
    /// silent permissive downgrade.
    #[test]
    fn iter231b_qwen35_unsupported_nested_feature_errors() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "cfg": {"type": "object", "properties": {"x": {"$ref": "#/$defs/t"}}}
            }
        });
        let err = QWEN35
            .tool_call_gbnf("f", &schema, GrammarShape::SingleBody)
            .expect_err("$ref must error");
        let msg = err.to_string();
        assert!(msg.contains("$ref"), "error must name the feature: {}", msg);
        assert!(
            msg.contains("/cfg/properties/x"),
            "error must carry the dot-path: {}",
            msg
        );
    }

    /// Qwen35: >8 nested required keys → TooManyRequiredKeys (same SOTA
    /// O(2^N) bound as the top level).
    #[test]
    fn iter231b_qwen35_nested_nine_required_keys_errors() {
        let props: serde_json::Map<String, serde_json::Value> = (0..9)
            .map(|i| (format!("k{}", i), serde_json::json!({"type": "integer"})))
            .collect();
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "cfg": {
                    "type": "object",
                    "properties": props,
                    "required": ["k0","k1","k2","k3","k4","k5","k6","k7","k8"]
                }
            }
        });
        // Public API converts EmitterError → String; assert the payload.
        let err = QWEN35
            .tool_call_gbnf("f", &schema, GrammarShape::SingleBody)
            .expect_err("9 nested required keys must error");
        assert!(
            err.contains("9 required parameters"),
            "error must carry the required-key count: {}",
            err
        );
        assert!(
            err.contains("/cfg"),
            "error must carry the nested path: {}",
            err
        );
    }

    /// Gemma4: nested object with declared properties — required keys in
    /// any order (bare-key kv surface).
    #[test]
    fn iter231b_gemma4_nested_object_required_keys_any_order() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {
                        "host": {"type": "string"},
                        "port": {"type": "integer"}
                    },
                    "required": ["host", "port"]
                }
            }
        }"#;
        let mut rt = gemma4_runtime("connect", schema);
        let input = b"call:connect{server:{port:443,host:<|\"|>example.com<|\"|>}}";
        assert!(rt.accept_bytes(input), "reversed required order rejected");
        assert!(rt.is_accepted());
    }

    /// Gemma4: nested missing required key rejected; typed array items
    /// enforced on the kv surface.
    #[test]
    fn iter231b_gemma4_nested_missing_required_and_typed_items_rejected() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "server": {
                    "type": "object",
                    "properties": {
                        "host": {"type": "string"},
                        "port": {"type": "integer"}
                    },
                    "required": ["host", "port"]
                },
                "tags": {"type": "array", "items": {"type": "string"}}
            }
        }"#;
        let mut rt = gemma4_runtime("connect", schema);
        // port missing.
        let input = b"call:connect{server:{host:<|\"|>example.com<|\"|>}}";
        let ok = rt.accept_bytes(input);
        assert!(
            !(ok && rt.is_accepted()),
            "missing nested required accepted"
        );

        let mut rt2 = gemma4_runtime("connect", schema);
        // integer items against items:string.
        let input2 = b"call:connect{server:{host:<|\"|>h<|\"|>,port:1},tags:[1,2]}";
        let ok2 = rt2.accept_bytes(input2);
        assert!(
            !(ok2 && rt2.is_accepted()),
            "typed array accepted wrong item type"
        );
    }

    /// Gemma4 parser (iter-231b): nested structured arguments round-trip
    /// into `arguments_json` as real JSON objects/arrays — the
    /// pre-iter-231b string-only kv splitter mangled any nested value
    /// containing a comma.
    #[test]
    fn iter231b_gemma4_parser_nested_arguments_round_trip() {
        let body = "call:configure{config:{model:<|\"|>sonnet<|\"|>,retries:3,nested:{on:true,ids:[1,2]}},task:<|\"|>do it<|\"|>}";
        let parsed = parse_gemma4_tool_call(body).expect("nested call must parse");
        assert_eq!(parsed.name, "configure");
        let args: serde_json::Value =
            serde_json::from_str(&parsed.arguments_json).expect("arguments_json valid JSON");
        assert_eq!(
            args,
            serde_json::json!({
                "config": {
                    "model": "sonnet",
                    "retries": 3,
                    "nested": {"on": true, "ids": [1, 2]}
                },
                "task": "do it"
            })
        );
    }

    /// Gemma4 parser (iter-231b): a comma INSIDE a nested container or a
    /// quoted string must not split the top-level kv-list.
    #[test]
    fn iter231b_gemma4_parser_commas_inside_nested_values_do_not_split() {
        let body = "call:f{tags:[<|\"|>a,b<|\"|>,2],note:<|\"|>x,y<|\"|>}";
        let parsed = parse_gemma4_tool_call(body).expect("must parse");
        let args: serde_json::Value =
            serde_json::from_str(&parsed.arguments_json).expect("arguments_json valid JSON");
        assert_eq!(
            args,
            serde_json::json!({
                "tags": ["a,b", 2],
                "note": "x,y"
            })
        );
    }

    /// Qwen35 parser sanity: nested JSON values already round-trip via
    /// the JSON-first value decode (no iter-231b change needed there —
    /// pin the contract so the two families stay symmetric).
    #[test]
    fn iter231b_qwen35_parser_nested_arguments_round_trip() {
        let body = "<function=configure>\n<parameter=config>\n{\"model\":\"sonnet\",\"nested\":{\"ids\":[1,2]}}\n</parameter>\n</function>";
        let parsed = parse_qwen35_tool_call(body).expect("nested call must parse");
        assert_eq!(parsed.name, "configure");
        let args: serde_json::Value =
            serde_json::from_str(&parsed.arguments_json).expect("arguments_json valid JSON");
        assert_eq!(
            args,
            serde_json::json!({"config": {"model": "sonnet", "nested": {"ids": [1, 2]}}})
        );
    }

    /// Both families: top-level UNTYPED parameters now accept structured
    /// values too (the template renders untyped args via tojson /
    /// format_argument as well).
    #[test]
    fn iter231b_untyped_params_accept_structured_values() {
        let schema = r#"{"type": "object", "properties": {"payload": {}}}"#;
        let mut rt = qwen35_runtime("f", schema);
        let q_input =
            b"<function=f>\n<parameter=payload>\n{\"k\":[1,2]}\n</parameter>\n</function>";
        assert!(
            rt.accept_bytes(q_input),
            "qwen untyped structured value rejected"
        );
        assert!(rt.is_accepted());

        let mut rt2 = gemma4_runtime("f", schema);
        let g_input = b"call:f{payload:{k:[1,2]}}";
        assert!(
            rt2.accept_bytes(g_input),
            "gemma untyped structured value rejected"
        );
        assert!(rt2.is_accepted());
    }

    // -----------------------------------------------------------------------
    // iter-231c — regex `pattern` keyword → GBNF compilation
    // -----------------------------------------------------------------------

    /// The exact iter-231c driver: a tool schema whose array items carry
    /// `pattern: "^[a-z][a-z0-9-]*$"` (the ruvnet-brain `argv` shape that
    /// 400'd opencode).  Grammar must accept conforming items and reject
    /// non-conforming ones.
    #[test]
    fn iter231c_qwen35_pattern_on_array_items_enforced() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "argv": {
                    "type": "array",
                    "items": {"type": "string", "pattern": "^[a-z][a-z0-9-]*$"}
                }
            }
        }"#;
        let mut rt = qwen35_runtime("cli_help", schema);
        let good = b"<function=cli_help>\n<parameter=argv>\n[\"ruflo\",\"claude-flow\",\"a\",\"z9-x\"]\n</parameter>\n</function>";
        assert!(rt.accept_bytes(good), "conforming argv rejected");
        assert!(rt.is_accepted());

        // "Bad" (uppercase start) violates the pattern — and the object
        // is a top-level parameter block, so there is no wildcard tail
        // to rescue it (top-level kleene alternation only).
        let mut rt2 = qwen35_runtime("cli_help", schema);
        let bad = b"<function=cli_help>\n<parameter=argv>\n[\"Bad\"]\n</parameter>\n</function>";
        let ok = rt2.accept_bytes(bad);
        assert!(
            !(ok && rt2.is_accepted()),
            "pattern-violating item accepted"
        );

        // "-x" (dash start) also violates it.
        let mut rt3 = qwen35_runtime("cli_help", schema);
        let bad2 = b"<function=cli_help>\n<parameter=argv>\n[\"-x\"]\n</parameter>\n</function>";
        assert!(
            !(rt3.accept_bytes(bad2) && rt3.is_accepted()),
            "dash-start item accepted"
        );
    }

    /// Quantified + alternation patterns on a nested string (year +
    /// http-method shapes).
    #[test]
    fn iter231c_qwen35_pattern_quantifier_and_alternation() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "year": {"type": "string", "pattern": "^\\d{4}$"},
                "method": {"type": "string", "pattern": "^(get|post|delete)$"}
            },
            "required": ["year"]
        }"#;
        // NOTE: top-level Qwen STRING params render RAW (no quotes —
        // the template only `tojson`s non-string values), so the pattern
        // applies to the unquoted text.
        let mut rt = qwen35_runtime("f", schema);
        let good = b"<function=f>\n<parameter=year>\n2026\n</parameter>\n<parameter=method>\npost\n</parameter>\n</function>";
        assert!(
            rt.accept_bytes(good),
            "valid quantifier/alternation strings rejected"
        );
        assert!(rt.is_accepted());

        let mut rt2 = qwen35_runtime("f", schema);
        // "202" is 3 digits — violates \d{4}.
        let bad = b"<function=f>\n<parameter=year>\n202\n</parameter>\n</function>";
        assert!(
            !(rt2.accept_bytes(bad) && rt2.is_accepted()),
            "3-digit year accepted"
        );

        let mut rt3 = qwen35_runtime("f", schema);
        // "patch" is outside the alternation.
        let bad2 = b"<function=f>\n<parameter=year>\n2026\n</parameter>\n<parameter=method>\npatch\n</parameter>\n</function>";
        assert!(
            !(rt3.accept_bytes(bad2) && rt3.is_accepted()),
            "non-alternation method accepted"
        );
    }

    /// Unanchored pattern = JSON Schema "contains" semantics: prefix and
    /// suffix wildcards are added by the compiler.
    #[test]
    fn iter231c_qwen35_unanchored_pattern_is_contains() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "text": {"type": "string", "pattern": "needle"}
            }
        }"#;
        let mut rt = qwen35_runtime("f", schema);
        let input = b"<function=f>\n<parameter=text>\n\"a haystack with needle inside\"\n</parameter>\n</function>";
        assert!(rt.accept_bytes(input), "contains-match rejected");
        assert!(rt.is_accepted());

        let mut rt2 = qwen35_runtime("f", schema);
        let bad = b"<function=f>\n<parameter=text>\n\"nothing here\"\n</parameter>\n</function>";
        assert!(
            !(rt2.accept_bytes(bad) && rt2.is_accepted()),
            "non-containing accepted"
        );
    }

    /// Gemma 4: pattern between the `<|"|>` markers.
    #[test]
    fn iter231c_gemma4_pattern_between_markers() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "argv": {
                    "type": "array",
                    "items": {"type": "string", "pattern": "^[a-z][a-z0-9-]*$"}
                }
            }
        }"#;
        let mut rt = gemma4_runtime("cli_help", schema);
        let good = b"call:cli_help{argv:[<|\"|>ruflo<|\"|>,<|\"|>claude-flow<|\"|>]}";
        assert!(rt.accept_bytes(good), "conforming argv rejected (gemma)");
        assert!(rt.is_accepted());

        let mut rt2 = gemma4_runtime("cli_help", schema);
        let bad = b"call:cli_help{argv:[<|\"|>Bad<|\"|>]}";
        assert!(
            !(rt2.accept_bytes(bad) && rt2.is_accepted()),
            "pattern-violating item accepted (gemma)"
        );
    }

    /// Top-level string parameter with `pattern` (raw Qwen surface).
    #[test]
    fn iter231c_qwen35_toplevel_string_pattern() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "subcommand": {"type": "string", "pattern": "^[a-z][a-z0-9-]*$"}
            }
        }"#;
        let mut rt = qwen35_runtime("cli", schema);
        let good = b"<function=cli>\n<parameter=subcommand>\nstatus\n</parameter>\n</function>";
        assert!(
            rt.accept_bytes(good),
            "valid top-level pattern string rejected"
        );
        assert!(rt.is_accepted());

        let mut rt2 = qwen35_runtime("cli", schema);
        let bad = b"<function=cli>\n<parameter=subcommand>\nStatus\n</parameter>\n</function>";
        assert!(
            !(rt2.accept_bytes(bad) && rt2.is_accepted()),
            "invalid top-level pattern string accepted"
        );
    }

    /// Non-regular regex features (backreference) remain an HONEST error
    /// — never a silent permissive downgrade.
    #[test]
    fn iter231c_nonregular_pattern_errors_honestly() {
        let schema = serde_json::json!({
            "type": "object",
            "properties": {
                "x": {"type": "string", "pattern": "^(a)\\1$"}
            }
        });
        let err = QWEN35
            .tool_call_gbnf("f", &schema, GrammarShape::SingleBody)
            .expect_err("backreference must error");
        assert!(
            err.contains("backreference"),
            "error names the feature: {}",
            err
        );
        assert!(err.contains("/x"), "error carries the path: {}", err);
    }

    // -----------------------------------------------------------------------
    // Wave 2.5 B6 — str-char escape rule and trailing-newline audit tests
    // -----------------------------------------------------------------------

    /// B6 audit: Gemma4 grammar accepts a string value containing a backslash
    /// sequence (e.g. `C:\Users\test`).  The `[^<\\] | [\\] [^\x00-\x1F]` rule
    /// handles `\U` as backslash + non-control char.
    /// Template reference: chat_template.jinja:113 emits `<|"|>arg<|"|>` raw;
    /// no HTML escaping of backslash.  The grammar rule is therefore
    /// conservative-correct: allows the escape pattern the model may produce.
    #[test]
    fn b6_gemma4_str_char_accepts_backslash_sequence() {
        let schema = r#"{
            "type": "object",
            "properties": {"path": {"type": "string"}}
        }"#;
        let mut rt = gemma4_runtime("read_file", schema);
        // path contains a backslash sequence
        let input = "call:read_file{path:<|\"|>C:\\Users\\test<|\"|>}";
        assert!(
            rt.accept_bytes(input.as_bytes()),
            "backslash sequence in Gemma string must be accepted"
        );
        assert!(rt.is_accepted());
    }

    /// B6 audit: Qwen35 trailing newline rule — every `</parameter>` is
    /// followed by `\n`.  Confirmed from tokenizer_config.json chat_template:
    /// `{{- '\n</parameter>\n' }}`.  Grammar emits `newline_lit param_close_lit
    /// newline_lit` for each block, including the last block before `</function>`.
    #[test]
    fn b6_qwen35_trailing_newline_on_last_param_required() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            }
        }"#;
        let mut rt = qwen35_runtime("weather", schema);
        // Canonical template emission: every </parameter> has trailing \n.
        let correct = b"<function=weather>\n<parameter=location>\nParis\n</parameter>\n</function>";
        assert!(
            rt.accept_bytes(correct),
            "trailing \\n after </parameter> must be accepted"
        );
        assert!(rt.is_accepted(), "must be accepted");
    }

    /// B6 audit: Qwen35 grammar rejects emission without trailing newline
    /// after `</parameter>`.  The template always emits the trailing newline,
    /// so a grammar that accepted the no-newline form would be too permissive.
    #[test]
    fn b6_qwen35_no_trailing_newline_rejected() {
        let schema = r#"{
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            }
        }"#;
        let mut rt = qwen35_runtime("weather", schema);
        // Missing trailing \n after </parameter>.
        let wrong = b"<function=weather>\n<parameter=location>\nParis\n</parameter></function>";
        let ok = rt.accept_bytes(wrong);
        assert!(
            !(ok && rt.is_accepted()),
            "emission without trailing \\n after </parameter> must be rejected"
        );
    }

    // -----------------------------------------------------------------------
    // Wave 2.7 W-η Q-A — eager-grammar acceptance + non-marker rejection
    //
    // Audit-driving tests for the `tool_choice=required` enforcement model.
    // These exercise the FULL emit→parse→runtime→mask path on real per-vocab
    // byte tables, mirroring the production decode loop's wiring.
    // -----------------------------------------------------------------------

    /// Helper: build a runtime for the eager (`OneOrMoreCalls`) shape.
    fn gemma4_required_runtime(
        fn_name: &str,
        schema_json: &str,
        parallel: bool,
    ) -> crate::serve::api::grammar::sampler::GrammarRuntime {
        let schema: serde_json::Value = serde_json::from_str(schema_json).unwrap();
        let gbnf = GEMMA4
            .tool_call_gbnf(fn_name, &schema, GrammarShape::OneOrMoreCalls { parallel })
            .unwrap_or_else(|e| panic!("tool_call_gbnf error: {}", e));
        grammar_runtime_for_gbnf(&gbnf)
    }

    fn qwen35_required_runtime(
        fn_name: &str,
        schema_json: &str,
        parallel: bool,
    ) -> crate::serve::api::grammar::sampler::GrammarRuntime {
        let schema: serde_json::Value = serde_json::from_str(schema_json).unwrap();
        let gbnf = QWEN35
            .tool_call_gbnf(fn_name, &schema, GrammarShape::OneOrMoreCalls { parallel })
            .unwrap_or_else(|e| panic!("tool_call_gbnf error: {}", e));
        grammar_runtime_for_gbnf(&gbnf)
    }

    /// T-QA-1: Gemma 4 eager grammar accepts the canonical marker-wrapped call.
    /// Validates the body bytes the model emits between markers (which the
    /// `ToolCallSplitter` swallows in production) by emitting the full
    /// `<|tool_call>...<tool_call|>` form at the runtime's grammar layer.
    #[test]
    fn gemma4_required_grammar_accepts_marker_wrapped_call() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = gemma4_required_runtime("get_weather", schema, false);
        let input = b"<|tool_call>call:get_weather{location:<|\"|>SF<|\"|>}<tool_call|>";
        assert!(
            rt.accept_bytes(input),
            "eager-grammar runtime must accept marker-wrapped call"
        );
        assert!(rt.is_accepted(), "not accepted at end");
    }

    /// T-QA-2 (audit-driving): mask path under `OneOrMoreCalls{parallel:false}`
    /// REJECTS the first non-marker byte at token 0.
    ///
    /// This is the structural-enforcement guarantee: the runtime is eager
    /// (`awaiting_trigger == false`) and the grammar root requires `<` (the
    /// first byte of `<|tool_call>`).  Any token whose decoded bytes don't
    /// prefix the open marker MUST be masked to -inf.
    ///
    /// Mirrors llama.cpp `grammar_lazy=false` for `tool_choice=REQUIRED`
    /// at common/chat.cpp:1200, 1416 — the model is structurally unable
    /// to skip the tool call.
    #[test]
    fn required_eager_grammar_masks_non_marker_first_token() {
        use crate::serve::api::grammar::mask;
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let rt = gemma4_required_runtime("get_weather", schema, false);
        assert!(
            !rt.is_awaiting_trigger(),
            "eager grammar runtime must NOT be in awaiting_trigger state"
        );
        // Build a tiny vocab: one token that starts the open marker (`<`),
        // and several non-marker tokens that the grammar must reject.
        // token_bytes table mirrors what `Engine::token_bytes_table`
        // produces from `Tokenizer::decode(&[id], false)`.
        let token_bytes: Vec<Vec<u8>> = vec![
            b"<".to_vec(),            // 0: starts <|tool_call> — survives
            b"<|tool_call>".to_vec(), // 1: full open marker     — survives
            b"hello".to_vec(),        // 2: plain content        — masked
            b"the".to_vec(),          // 3: plain content        — masked
            b" ".to_vec(),            // 4: whitespace           — masked
            b"\n".to_vec(),           // 5: newline              — masked
            b"call:".to_vec(),        // 6: body-prefix          — masked
            b"".to_vec(),             // 7: empty / EOS          — exempt by design
        ];
        let mut logits = vec![0.0_f32; token_bytes.len()];
        let masked = mask::mask_invalid_tokens(&rt, &token_bytes, &mut logits);

        // Marker-prefix tokens (0, 1) survive; empty token (7) is exempt;
        // everything else (2..=6) is masked to -inf.  That's 5 masked tokens.
        assert_eq!(masked, 5, "expected 5 masked tokens, logits = {:?}", logits);
        assert!(
            logits[0].is_finite(),
            "token 0 (`<`) must survive — prefixes open marker"
        );
        assert!(
            logits[1].is_finite(),
            "token 1 (`<|tool_call>`) must survive — full open marker"
        );
        assert!(!logits[2].is_finite(), "token 2 (`hello`) must be masked");
        assert!(!logits[3].is_finite(), "token 3 (`the`) must be masked");
        assert!(!logits[4].is_finite(), "token 4 (` `) must be masked");
        assert!(!logits[5].is_finite(), "token 5 (`\\n`) must be masked");
        assert!(
            !logits[6].is_finite(),
            "token 6 (`call:`) must be masked — body bytes only legal AFTER open marker"
        );
        assert!(
            logits[7].is_finite(),
            "token 7 (empty bytes) is exempt from mask per mask.rs:77-80 (EOS contract)"
        );
    }

    /// T-QA-3 (audit-driving): mask path under `SingleBody` + lazy
    /// (`awaiting_trigger=true`) ALLOWS every non-marker token at token 0.
    ///
    /// This is the AUTO-mode contract: the runtime is suspended until the
    /// `ToolCallSplitter` sees the open marker; preamble content tokens
    /// flow through unconstrained.  Matches llama.cpp `grammar_lazy=true`
    /// for `tool_choice=AUTO` at common/chat.cpp:913, 1200, 1416.
    #[test]
    fn auto_lazy_grammar_allows_preamble_content() {
        use crate::serve::api::grammar::mask;
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        // Body-only grammar — what `compile_tool_grammar` would emit for AUTO
        // under a future Wave 2.7+ wiring.
        let mut rt = gemma4_runtime("get_weather", schema);
        // Arm the lazy gate the way `engine.rs` does for ToolCallBodyAuto.
        rt.set_awaiting_trigger(true);
        assert!(rt.is_awaiting_trigger());

        let token_bytes: Vec<Vec<u8>> = vec![
            b"<".to_vec(),
            b"<|tool_call>".to_vec(),
            b"hello".to_vec(),
            b"the".to_vec(),
            b" ".to_vec(),
            b"\n".to_vec(),
            b"call:".to_vec(),
        ];
        let mut logits = vec![0.0_f32; token_bytes.len()];
        let masked = mask::mask_invalid_tokens(&rt, &token_bytes, &mut logits);
        assert_eq!(
            masked, 0,
            "lazy/awaiting_trigger runtime must mask zero tokens"
        );
        for (i, l) in logits.iter().enumerate() {
            assert!(
                l.is_finite(),
                "token {} masked under awaiting_trigger; logits = {:?}",
                i,
                logits
            );
        }
    }

    /// T-QA-4: Qwen 3.5/3.6 eager grammar accepts the canonical
    /// marker-wrapped single call.
    #[test]
    fn qwen35_required_grammar_accepts_marker_wrapped_call() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = qwen35_required_runtime("get_weather", schema, false);
        // `<tool_call>\n<function=NAME>\n...\n</function>\n</tool_call>`.
        let input = b"<tool_call>\n<function=get_weather>\n<parameter=location>\nParis\n</parameter>\n</function>\n</tool_call>";
        assert!(
            rt.accept_bytes(input),
            "eager Qwen35 grammar must accept canonical single-call emission"
        );
        assert!(rt.is_accepted());
    }

    /// T-QA-5: under `parallel=false`, the eager grammar REJECTS a second
    /// open marker after the first call's close marker — single-call cap.
    #[test]
    fn gemma4_required_grammar_rejects_second_call_when_parallel_false() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = gemma4_required_runtime("get_weather", schema, false);
        // First call accepted in full.
        let first = b"<|tool_call>call:get_weather{location:<|\"|>SF<|\"|>}<tool_call|>";
        assert!(rt.accept_bytes(first));
        assert!(rt.is_accepted(), "first call must reach accepted state");
        // Second open marker must drive the runtime dead under parallel=false.
        let second_open = b"<|tool_call>";
        let alive = rt.accept_bytes(second_open);
        assert!(
            !alive || rt.is_dead(),
            "second `<|tool_call>` must be rejected under parallel=false"
        );
    }

    // -----------------------------------------------------------------------
    // Wave 2.7 W-η Q-B — parallel_tool_calls grammar shape
    //
    // Audit-driving tests for the multi-call grammar shape per Codex audit
    // divergence "Multi-tool re-entry" (severity med): the wave-2.6 worker
    // landed the no-reset-on-close runtime semantics but kept the single-call
    // grammar shape, so under `parallel_tool_calls=true` the model emitting a
    // second open marker would silently drive the runtime dead.  Q-B emits
    // `(call)+` (Gemma) and `call ("\n" call)*` (Qwen) so the runtime
    // structurally accepts the natural multi-call template output.
    // -----------------------------------------------------------------------

    /// T-QB-1 (audit-driving): Gemma 4 parallel grammar accepts two
    /// back-to-back calls with no separator (chat_template.jinja:189-205).
    #[test]
    fn gemma4_parallel_grammar_accepts_two_calls() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = gemma4_required_runtime("get_weather", schema, true);
        // Two back-to-back calls — Gemma chat_template emits with NO separator.
        let input = b"<|tool_call>call:get_weather{location:<|\"|>SF<|\"|>}<tool_call|>\
                     <|tool_call>call:get_weather{location:<|\"|>NYC<|\"|>}<tool_call|>";
        assert!(
            rt.accept_bytes(input),
            "parallel Gemma 4 grammar must accept two back-to-back calls"
        );
        assert!(rt.is_accepted(), "two-call sequence not in accepting state");
    }

    /// T-QB-2 (audit-driving): Qwen 3.5/3.6 parallel grammar accepts two
    /// calls separated by a literal `\n` (tokenizer_config.json:285+).
    #[test]
    fn qwen35_parallel_grammar_accepts_two_calls_separated_by_newline() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = qwen35_required_runtime("get_weather", schema, true);
        // Two calls separated by literal `\n` per chat_template's `else` branch.
        let input = b"<tool_call>\n<function=get_weather>\n<parameter=location>\nParis\n</parameter>\n</function>\n</tool_call>\n<tool_call>\n<function=get_weather>\n<parameter=location>\nLondon\n</parameter>\n</function>\n</tool_call>";
        assert!(
            rt.accept_bytes(input),
            "parallel Qwen35 grammar must accept two calls with `\\n` separator"
        );
        assert!(rt.is_accepted(), "two-call sequence not accepted");
    }

    /// T-QB-3 (audit-driving): Qwen 3.5/3.6 parallel grammar REJECTS two
    /// calls without the `\n` separator — the chat_template requires the
    /// newline, so the grammar must too.
    #[test]
    fn qwen35_parallel_grammar_rejects_calls_without_newline_separator() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = qwen35_required_runtime("get_weather", schema, true);
        // Two calls back-to-back with NO separator.  This violates the Qwen
        // chat-template contract; the grammar must reject it.
        let input = b"<tool_call>\n<function=get_weather>\n<parameter=location>\nParis\n</parameter>\n</function>\n</tool_call><tool_call>\n<function=get_weather>\n<parameter=location>\nLondon\n</parameter>\n</function>\n</tool_call>";
        let alive = rt.accept_bytes(input);
        assert!(
            !alive || !rt.is_accepted(),
            "Qwen parallel grammar accepted two calls without `\\n` separator (should reject)"
        );
    }

    /// T-QB-4: under `parallel = false`, Qwen 3.5/3.6 grammar REJECTS the
    /// trailing `\n<tool_call>` of a second call.  Mirrors the Gemma 4
    /// equivalent for Qwen's separator semantics.
    #[test]
    fn qwen35_required_grammar_rejects_second_call_when_parallel_false() {
        let schema = r#"{
            "type": "object",
            "properties": {"location": {"type": "string"}}
        }"#;
        let mut rt = qwen35_required_runtime("get_weather", schema, false);
        let first = b"<tool_call>\n<function=get_weather>\n<parameter=location>\nParis\n</parameter>\n</function>\n</tool_call>";
        assert!(rt.accept_bytes(first));
        assert!(rt.is_accepted(), "first call must reach accepted state");
        let second = b"\n<tool_call>";
        let alive = rt.accept_bytes(second);
        assert!(
            !alive || rt.is_dead(),
            "second call open must be rejected under parallel=false"
        );
    }
}