BREP_kernel 0.14.0

A boundary representation (BREP) geometry kernel for building CAD applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
//! The stripe network: a whole selection blended as one construction.
//!
//! # Why this is not a loop over single-edge fillets
//!
//! Blending one edge at a time means every blend after the first is built
//! against a solid the previous ones have already cut, and a corner where two
//! or three of them meet has to be RECONSTRUCTED afterwards from whatever they
//! left behind.  That is the origin of both classic failures: a cutter run
//! past its edge to make a boolean assemble removes material the fillet never
//! touches, and a corner closure that has to identify leftover caps by
//! distance heuristics silently gives up and leaves the corner unmade.
//!
//! Here nothing is cut until everything is known.  Every stripe is marched
//! against the ORIGINAL solid, so the result cannot depend on selection order;
//! every corner is solved from the corner ball ([`solve_corner_ball`]) before
//! any topology changes; and each stripe is then trimmed to the station where
//! its own rolling ball IS the corner ball.  At that station the stripe's
//! contact points ARE the ball's tangency points, so:
//!
//!   * the two stripes sharing a face end their contact rails at the same
//!     point and the face's loop closes with no connector and no leftover;
//!   * at a STAR (every edge at the vertex selected) the stripe's end
//!     cross-section is an arc of the corner sphere, so it can be the shared
//!     edge with the corner patch — exactly tangent, with nothing to intersect;
//!   * at a MITER (two edges selected, the third sharp) the two blends run on
//!     past the ball and are trimmed against each other along their seam,
//!     marched as a level set from the ball's tangency point (`miter.rs`);
//!   * no boolean is involved anywhere, so no cutter can overshoot.
//!
//! Every vertex of the selection is classified once — free end, miter, or
//! star — so a selection mixing them (a face perimeter with one star corner)
//! is one construction, not a composition of per-corner special cases.
//! Configurations the lane does not construct refuse BY NAME: a smooth (G1)
//! two-edge vertex, which is a chain and not a corner; mixed-convexity
//! corners, where the convex stripe has no closure at all because it never
//! reaches the vertex — it switches CARRIERS onto the concave stripes'
//! surfaces and dies in a pole, measured in `runout.rs`; re-entrant
//! miters (the blends wrap the concave edge instead of meeting in a seam);
//! no-common-ball stars.  A CHAMFER reaches the lane too: its stripes are the
//! same march with a chord section (`cross_section_basis`), its STAR closes
//! with the facet those chords bound (`build_chamfer_corner_facet`), its FLUSH
//! join shares one chord where a fillet shares one arc, and its MITER trims the
//! two bevels against each other along a seam marched on the chamfer's OWN
//! level — the signed distance to the sibling's ruled bevel, because the
//! sibling's rolling-ball CANAL is a surface a bevel is not (`bevel_level`).
//! Only the re-entrant corner refuses by name and takes the cutter
//! composition.

use crate::{KernelRefusal, KernelStage, OrRefuse, RefusalClass};
use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, VertexRecord};
use crate::{NurbsCurve, Vec3};

use super::collapse::{check_collapse_closure, collapse_full_width};
use super::corner::*;
use super::edge::*;
use super::miter::*;
use super::restrict::{restrict_third_faces, StripeFaces};
use super::stations::*;

#[path = "network/cap.rs"]
mod cap;

/// One selected edge, marched and fitted against the original solid.
struct Stripe<'a> {
    edge: &'a EdgeRecord,
    first: BlendMate<'a>,
    second: BlendMate<'a>,
    rows: FittedRows,
    name: Option<String>,
    /// Which ends, start then finish, run out into a pole (`pole_end`).
    poles: [bool; 2],
    /// What the stripe's ladder measured and what step 7 reads again on the
    /// shipped windows.
    measure: StripeMeasure,
    law: super::StripeRadius,
    end_radius: [f64; 2],
}

/// One rung of a stripe's ladder: its rows, parameters, stations, the exact
/// dense centres (a fillet's wall verdict), and its vertex-window reading.
struct StripeRung {
    rows: FittedRows,
    parameters: Vec<f64>,
    stations: Vec<Station>,
    /// The stations the march snapped onto the edge's vertices, start then
    /// finish (the stopped-end rollover reads where the stripe's own end is).
    vertex_indices: [usize; 2],
    dense: OpenDenseCentres,
    reading: OpenRungReading,
    rail_reader: Option<std::cell::RefCell<super::edge::RailWindowReader>>,
}

/// A stripe's measurement: the shipped rung's parameters, stations and dense
/// centres (for the shipped-window reading), whether its ladder ACCEPTED it on
/// the vertex window (else the top rung shipped unaccepted), its vertex-window
/// reading, why its construction request stopped, the request rungs
/// attempted, whether the edge is stationary at a vertex (a missing rail is
/// then unread), and whether the wall is judged at all (a fillet).
struct StripeMeasure {
    parameters: Vec<f64>,
    stations: Vec<Station>,
    dense: OpenDenseCentres,
    ladder_accepted: bool,
    ladder_reading: OpenRungReading,
    rail_reader: Option<std::cell::RefCell<super::edge::RailWindowReader>>,
    unmet: Option<crate::BudgetReason>,
    request_rungs: usize,
    stationary_end: bool,
    wall_check: bool,
    exact_lane: bool,
    /// The stations the march snapped onto the edge's vertices, start then
    /// finish (the stopped-end rollover reads where the stripe's own end is).
    vertex_indices: [usize; 2],
}

impl Stripe<'_> {
    /// The blend loop's walk over an end slot runs first-rim -> second-rim
    /// exactly when this is true (see `build_open_surgery`).
    fn walk_first_to_second(&self, at_start: bool) -> bool {
        let blend_cr_forward = !self.first.coedge.forward;
        if at_start {
            !blend_cr_forward
        } else {
            blend_cr_forward
        }
    }

    fn at_start(&self, vertex: u64) -> bool {
        self.edge.start_vertex_id == vertex
    }
}

/// A seated corner ball with its tangency vertices committed.
struct Corner {
    center: Vec3,
    /// True when the ball sits inside the material (every incident edge
    /// convex); false when it sits in the air (every incident edge concave).
    outward: bool,
    /// Face id -> the ball's tangency point on that face, and the vertex id
    /// committed for it.
    tangency: Vec<(u64, Vec3, u64)>,
    radius: f64,
}

impl Corner {
    fn tangency_on(&self, face_id: u64) -> Result<(Vec3, u64), KernelRefusal> {
        self.tangency
            .iter()
            .find(|(id, _, _)| *id == face_id)
            .map(|(_, point, vertex)| (*point, *vertex))
            .ok_or_else(|| {
                format!("blend network: the corner ball has no tangency on face {face_id}")
            }).or_refuse(KernelStage::Refine, "ok_or_else")
    }
}

/// What the selection does at one vertex.
enum VertexKind<'a> {
    /// A star: every edge at the vertex is selected; closed by a patch of the
    /// corner ball.
    Star { corner: Corner },
    /// `corner`'s tangency points are the per-face RAIL/RAIL points
    /// (`solve_rail_rail_point`), its centre the classification ball's; each
    /// stripe ends on the rib through its two points and the ribs are filled
    /// by the ribbon Coons patch (`build_ribbon_star_patch`).
    RibbonStar { corner: Corner },
    /// A miter: two selected edges, the third sharp.  `shared` is the face
    /// both stripes touch; `sharp` the unselected edge; the ball still seats
    /// on the three faces and supplies P, the point both shared-face rails
    /// stop at.
    Miter {
        corner: Corner,
        shared: &'a FaceRecord,
        sharp: &'a EdgeRecord,
    },
    /// A flush join: two selected edges meeting SMOOTHLY (G1).  The rolling
    /// ball is the same ball on the same (or tangent-continuous) faces on
    /// both sides, so both stripes stop at ONE section and share ONE arc,
    /// with no patch.
    ///
    /// On the same two faces that section is the vertex's own.  When the two
    /// stripes' side faces differ (a planar wall running into a cylindrical
    /// one, a cone side into the round on its rim), the ball changes carrier
    /// where its side CONTACT crosses the seam between those faces, and that
    /// is not the vertex section unless the seam happens to lie in the
    /// vertex's normal plane: `join` is the ball seated on the seam
    /// ([`solve_flush_seam_ball`]), and the seam is trimmed at its contact.
    Flush { join: Option<FlushJoin> },
    /// Two equal-radius fillets wrap the unselected sharp edge instead of
    /// intersecting in a seam: convex cap fillets around a concave notch,
    /// or concave boss-base fillets around a convex edge. Each stripe stops
    /// where its wall rail reaches the sharp edge; revolving that section
    /// between the two stops produces a horn-torus sector sharing their pole.
    Reentrant {
        cap: &'a FaceRecord,
        sharp: &'a EdgeRecord,
    },
    /// Lane L (2026-10-14): a MIXED star — one CONCAVE stripe Q between two
    /// walls and two CONVEX stripes, each on one of those walls and the cap
    /// they share, at a planar corner whose walls stand normal to the cap (at
    /// any concave angle to each other), Q's axis normal to the cap (§6.9.7, the class `round_mixed_concave_corner` closes behind the
    /// cutter).  No ball touches all three faces from one side; the rolling
    /// ball rides Q's rim, its centre 2r from Q's axis and r below the cap,
    /// so the closure is the exact torus sector bounded by the two convex
    /// stripes' end sections, Q's inner-equator section and the cap's contact
    /// arc.  Behind `BREP_BLEND_MIXED_STAR`.
    MixedStar(MixedStar),
}

/// The closed-form points of a [`VertexKind::MixedStar`] corner.
#[derive(Clone, Copy, Debug)]
struct MixedStar {
    radius: f64,
    cap: u64,
    wall_a: u64,
    wall_b: u64,
    /// Stripe indices: the concave stripe and the convex stripes on wall A
    /// and on wall B.
    q: usize,
    a: usize,
    b: usize,
    /// Q's inner-equator ends on the walls, and the cap contact ends.
    v_a: Vec3,
    v_b: Vec3,
    w_a: Vec3,
    w_b: Vec3,
    /// Q's axis at the inner-equator level, its direction (away from the cap
    /// into the material's side), and the convex stripes' ball centres at
    /// their stops.
    q_v: Vec3,
    q_w: Vec3,
    axis: Vec3,
    c_a: Vec3,
    c_b: Vec3,
}

/// `BREP_BLEND_MIXED_STAR=1` lets the network close a mixed star
/// ([`VertexKind::MixedStar`]), `=0` is the escape hatch. Promoted 2026-10-15
/// (lane L's record: census with it on — cases OK, integration 417/0, lib
/// green once the three cutter-composition tests were pinned to the
/// composition).
const MIXED_STAR_DEFAULT: bool = true;

pub(crate) fn mixed_star_on() -> bool {
    switch!(live "BREP_BLEND_MIXED_STAR", MIXED_STAR_DEFAULT)
}


/// The outward normal of a PLANAR face, or `None`.
fn planar_outward_normal(face: &FaceRecord) -> Option<Vec3> {
    let Some(crate::AnalyticSurface::Plane { u_dir, v_dir, .. }) = face.surface.analytic() else {
        return None;
    };
    let normal = u_dir.cross(*v_dir).normalized().ok()?;
    Some(if face.same_sense { normal } else { normal.scale(-1.0) })
}

/// Whether the three stripes at `point` are a [`VertexKind::MixedStar`],
/// and its closed-form points when they are.  `None` for every other
/// configuration, which the classification then reads as before.
fn detect_mixed_star(
    mates: &[(&EdgeRecord, BlendMate, BlendMate)],
    stripe_indices: &[usize],
    point: Vec3,
    radius: f64,
) -> Option<MixedStar> {
    if stripe_indices.len() != 3 || !(radius > 0.0) {
        return None;
    }
    let convex: Vec<(usize, bool)> = stripe_indices
        .iter()
        .map(|&index| {
            let (edge, first, second) = &mates[index];
            edge_is_convex(edge, first, second).ok().map(|convex| (index, convex))
        })
        .collect::<Option<Vec<_>>>()?;
    let concave: Vec<usize> = convex.iter().filter(|(_, c)| !*c).map(|(i, _)| *i).collect();
    let rims: Vec<usize> = convex.iter().filter(|(_, c)| *c).map(|(i, _)| *i).collect();
    let ([q], [r0, r1]) = (concave.as_slice(), rims.as_slice()) else {
        return None;
    };
    let faces_of = |index: usize| [mates[index].1.face, mates[index].2.face];
    let [q0, q1] = faces_of(*q);
    // Each rim shares exactly one face with Q (its wall); the rims share the cap.
    let wall_of = |index: usize| -> Option<(&FaceRecord, &FaceRecord)> {
        let [f0, f1] = faces_of(index);
        match (f0.id == q0.id || f0.id == q1.id, f1.id == q0.id || f1.id == q1.id) {
            (true, false) => Some((f0, f1)),
            (false, true) => Some((f1, f0)),
            _ => None,
        }
    };
    let (wall_a, cap_a) = wall_of(*r0)?;
    let (wall_b, cap_b) = wall_of(*r1)?;
    if cap_a.id != cap_b.id || wall_a.id == wall_b.id {
        return None;
    }
    let (na, nb, nc) = (planar_outward_normal(wall_a)?, planar_outward_normal(wall_b)?, planar_outward_normal(cap_a)?);
    // Both walls stand normal to the cap (Q's axis is the cap's normal); the
    // walls themselves meet at any concave angle.
    let k = na.dot(nb);
    if na.dot(nc).abs() > 1e-9 || nb.dot(nc).abs() > 1e-9 || k <= -1.0 + 1e-6 {
        return None;
    }
    for face in [wall_a, wall_b, cap_a] {
        // The corner must lie on every plane (the faces meet at the vertex).
        let Some(crate::AnalyticSurface::Plane { origin, .. }) = face.surface.analytic() else {
            return None;
        };
        let normal = planar_outward_normal(face)?;
        if normal.dot(point.sub(*origin)).abs() > 1e-7 * (1.0 + radius) {
            return None;
        }
    }
    // Q's axis: in the cap plane, r off both walls into the air —
    // corner + r/(1 + n_a·n_b)·(n_a + n_b).  Each rim's centre line runs r
    // inside its wall and r below the cap, so it is 2r from Q's axis and
    // tangent to the torus' centre circle: its stop centre is the foot of
    // the perpendicular, q_v − 2r·n_wall, and the ball touches Q at
    // q_v − r·n_wall (on the wall) and the cap at q_w − 2r·n_wall.
    let r = radius;
    let q_w = point.add(na.add(nb).scale(r / (1.0 + k)));
    let q_v = q_w.sub(nc.scale(r));
    Some(MixedStar {
        radius: r,
        cap: cap_a.id,
        wall_a: wall_a.id,
        wall_b: wall_b.id,
        q: *q,
        a: *r0,
        b: *r1,
        v_a: q_v.sub(na.scale(r)),
        v_b: q_v.sub(nb.scale(r)),
        w_a: q_w.sub(na.scale(2.0 * r)),
        w_b: q_w.sub(nb.scale(2.0 * r)),
        q_v,
        q_w,
        axis: nc.scale(-1.0),
        c_a: q_v.sub(na.scale(2.0 * r)),
        c_b: q_v.sub(nb.scale(2.0 * r)),
    })
}

/// The overshoot ladder for the marches, as fractions of the edge span.  A
/// stripe that ends at a corner needs no overshoot there (its stop station is
/// INSIDE the edge, a tangency setback short of the vertex); the ladder is
/// still needed for free ends, whose support crossings sit at or past the
/// endpoint.
pub(super) const OVERSHOOTS: [f64; 4] = [0.08, 0.16, 0.28, 0.45];

fn mate_at_radius<'a>(mate: &BlendMate<'a>, radius: f64) -> BlendMate<'a> {
    BlendMate {
        face: mate.face,
        coedge: mate.coedge,
        loop_index: mate.loop_index,
        rho: mate.rho.signum() * radius,
    }
}

/// Unit tangent of `edge` at `vertex`, pointing AWAY from it.
pub(super) fn tangent_away_from(edge: &EdgeRecord, vertex: u64) -> Result<Vec3, KernelRefusal> {
    let (t, sign) = if edge.start_vertex_id == vertex {
        (edge.t0, 1.0)
    } else {
        (edge.t1, -1.0)
    };
    // At a vertex, where an involute flank's Hermite fit is stationary: read
    // the one-sided limit from inside the edge.
    edge.curve
        .unit_tangent(t, edge.t0, edge.t1)
        .map(|tangent| tangent.scale(sign))
        .map_err(|error| format!("blend network: edge {}: {error}", edge.id)).or_refuse(KernelStage::Refine, "unit_tangent")
}

/// Whether `edge` is STATIONARY at `vertex` — its first derivative there is too
/// short to normalize, so [`tangent_away_from`] answered with the one-sided
/// limit rather than the derivative. Reads the same parameter it does.
fn stationary_at_vertex(edge: &EdgeRecord, vertex: u64) -> Result<bool, KernelRefusal> {
    let t = if edge.start_vertex_id == vertex {
        edge.t0
    } else {
        edge.t1
    };
    Ok(edge.curve.derivatives(t, 1).or_refuse(KernelStage::Refine, "derivatives")?[1].normalized().is_err())
}

/// The two mating faces of every selected edge, with the signed radius the
/// march offsets each of them by.  Read off the ORIGINAL solid: `rho` is the
/// side the rolling ball sits on, so it is the edge's convexity in the form
/// the corner solve needs.
pub(super) fn stripe_mates<'a>(
    solid: &'a BrepSolid,
    edge_ids: &[u64],
    radius: f64,
) -> Result<Vec<(&'a EdgeRecord, BlendMate<'a>, BlendMate<'a>)>, KernelRefusal> {
    let laws = vec![super::StripeRadius::Constant(radius); edge_ids.len()];
    stripe_mates_laws(solid, edge_ids, &laws)
}

/// [`stripe_mates`] with a radius law per edge: the signs are probed at the
/// law's value at the edge's parameter midpoint (where `signed_radii` probes
/// first), as the single open edge's variable lane does; the magnitude a
/// mate carries is that midpoint value, and every solve at a vertex takes
/// the stripe's END radius instead (`Stripe::end_radius`).
fn stripe_mates_laws<'a>(
    solid: &'a BrepSolid,
    edge_ids: &[u64],
    laws: &[super::StripeRadius],
) -> Result<Vec<(&'a EdgeRecord, BlendMate<'a>, BlendMate<'a>)>, KernelRefusal> {
    let mut mates: Vec<(&EdgeRecord, BlendMate, BlendMate)> = Vec::with_capacity(edge_ids.len());
    for (&edge_id, law) in edge_ids.iter().zip(laws) {
        let radius = law.at_fraction(0.5);
        let edge = solid
            .edges
            .iter()
            .find(|candidate| candidate.id == edge_id)
            .ok_or_else(|| format!("blend network: edge {edge_id} not found")).or_refuse(KernelStage::Refine, "ok_or_else")?;
        if edge.start_vertex_id == edge.end_vertex_id {
            return Err(KernelRefusal::unsupported(KernelStage::Classify, "closed_edge_corner", format!(
                "blend network: edge {edge_id} is closed and has no corner to share"
            )));
        }
        let (first_face, first_loop, first_coedge) = locate_mate(solid, edge_id, None)?;
        let (second_face, second_loop, second_coedge) =
            locate_mate(solid, edge_id, Some((first_face.id, first_loop)))?;
        let (rho1, rho2) = signed_radii(
            edge,
            first_face,
            first_coedge,
            second_face,
            second_coedge,
            radius,
        )?;
        mates.push((
            edge,
            BlendMate {
                face: first_face,
                coedge: first_coedge,
                loop_index: first_loop,
                rho: rho1,
            },
            BlendMate {
                face: second_face,
                coedge: second_coedge,
                loop_index: second_loop,
                rho: rho2,
            },
        ));
    }
    Ok(mates)
}

/// Which selected edges (indices into `mates`) meet at which vertex.
fn stripes_by_vertex(mates: &[(&EdgeRecord, BlendMate, BlendMate)]) -> Vec<(u64, Vec<usize>)> {
    let mut vertex_stripes: Vec<(u64, Vec<usize>)> = Vec::new();
    for (index, (edge, _, _)) in mates.iter().enumerate() {
        for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
            match vertex_stripes.iter_mut().find(|(id, _)| *id == vertex) {
                Some((_, list)) => list.push(index),
                None => vertex_stripes.push((vertex, vec![index])),
            }
        }
    }
    vertex_stripes
}

/// A corner where the selection mixes convexity: at `point` two of the
/// selected edges share a face but want the rolling ball on OPPOSITE sides of
/// it, one blend cutting material away from that face while the other adds
/// material against it.  `convex` and `concave` are indices into the selection.
pub(crate) struct MixedCorner {
    pub(crate) vertex: u64,
    pub(crate) point: Vec3,
    pub(crate) convex: Vec<usize>,
    pub(crate) concave: Vec<usize>,
}

/// The one network refusal the fillet ladder must not paper over: a corner
/// where MORE THAN ONE selected edge is concave and at least one is convex.
///
/// Mixing convexity at a vertex is not by itself unbuildable. The re-entrant
/// vertex of a notch — ONE concave edge with the convex edges that run into
/// it — is closed by the horn-torus sector about that concave edge's own
/// blend, because the ball can roll round it from one convex blend to the
/// other (`round_concave_chain_corner`, `round_convex_corner`, §6.9.7). Its
/// MIRROR — two or more concave edges meeting a convex one — has no closure
/// here at all: the convex blend RUNS OUT against the concave beads partway
/// along its edge, which is the vertex blend nothing in this kernel
/// constructs. `runout.rs` measures what that run-out is — two carrier
/// switches onto the concave stripes' own surfaces and a degenerate pole —
/// and the refusal reports its stations. That boundary is empirical, one
/// concave edge against two, not a rule derived from the balls' sides — the
/// notch splits those the same way and is built.
///
/// So `fillet_edges` reports that class as a TERMINAL refusal rather than
/// retrying it on the cutter, whose answer for it is a shredded solid: sliver
/// end caps at every unclosed corner and a renamed carrier face.
pub(crate) fn mixed_convexity_corner(
    solid: &BrepSolid,
    edge_ids: &[u64],
    radius: f64,
) -> Option<MixedCorner> {
    mixed_convexity_corners(solid, edge_ids, radius).into_iter().next()
}

/// Every mixed-convexity corner of the selection, in vertex order — the
/// runout composition (`runout.rs`) needs BOTH ends of each convex edge,
/// where [`mixed_convexity_corner`] reports the first for the refusal.
pub(crate) fn mixed_convexity_corners(
    solid: &BrepSolid,
    edge_ids: &[u64],
    radius: f64,
) -> Vec<MixedCorner> {
    let mut found = Vec::new();
    let Ok(mates) = stripe_mates(solid, edge_ids, radius) else {
        return found;
    };
    for (vertex_id, stripe_indices) in stripes_by_vertex(&mates) {
        if stripe_indices.len() < 2 {
            continue;
        }
        let mut faces: Vec<(u64, f64)> = Vec::new();
        let mut mixed = false;
        for &index in &stripe_indices {
            for mate in [&mates[index].1, &mates[index].2] {
                match faces.iter().find(|(id, _)| *id == mate.face.id) {
                    Some((_, rho)) => mixed |= (*rho - mate.rho).abs() > 1e-9 * (1.0 + radius),
                    None => faces.push((mate.face.id, mate.rho)),
                }
            }
        }
        if !mixed {
            continue;
        }
        let Some(point) = solid
            .vertices
            .iter()
            .find(|vertex| vertex.id == vertex_id)
            .map(|vertex| vertex.point)
        else {
            continue;
        };
        let mut convex = Vec::new();
        let mut concave = Vec::new();
        for &index in &stripe_indices {
            let (edge, first, second) = &mates[index];
            match edge_is_convex(edge, first, second) {
                Ok(true) => convex.push(index),
                Ok(false) => concave.push(index),
                // Unclassifiable: the corner is still mixed, it just cannot be
                // described edge by edge.  Report it with the side left empty.
                Err(_) => {}
            }
        }
        // Exactly one concave edge is the re-entrant closure's own shape, and
        // it is constructed; only its mirror is refused.
        if concave.len() < 2 || convex.is_empty() {
            continue;
        }
        found.push(MixedCorner {
            vertex: vertex_id,
            point,
            convex,
            concave,
        });
    }
    found
}

/// The inside-corner refusal's name: two selected concave edges over an
/// unselected concave sharp edge.
pub(crate) const REENTRANT_CONCAVE_WHAT: &str = "reentrant_concave";

/// Whether `refusal` is the inside-corner classification above.
pub(crate) fn is_reentrant_concave(refusal: &KernelRefusal) -> bool {
    matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what } if what == REENTRANT_CONCAVE_WHAT)
}

/// `BREP_BLEND_CONCAVE_MITER`: send an inside corner (two selected concave
/// edges over a concave sharp edge) down the two-edge miter lane instead of
/// refusing it by name. `=0`/`off` is the escape hatch. Promoted 2026-10-15
/// (lane L's census with it on: the 96 cases OK, integration and lib green
/// but for three refusal pins whose refusal moves one corner further, to the
/// one-ended concave-third end).
const CONCAVE_MITER_DEFAULT: bool = true;

pub(crate) fn concave_miter_on() -> bool {
    switch!(live "BREP_BLEND_CONCAVE_MITER", CONCAVE_MITER_DEFAULT)
}


// BREP named hunk: begin lcount234_creased_seam_join_20261016
/// `BREP_BLEND_CREASED_SEAM`: close a smooth vertex whose two side faces CREASE
/// along their seam down the two-edge miter lane, with the seam as its sharp
/// edge, instead of refusing it as "not a flush join". The two balls then meet
/// the seam at different points when the seam's faces turn their normals out of
/// the shared face's normal plane, and the closure is the miter's asymmetric
/// one (`solve_miter`): the seam leaves the shallower blend through its side
/// rail at P, and a connector on that blend's side face runs to S on the seam.
/// `=0`/`off` is the escape hatch. Promoted 2026-10-17 (no case reaches a
/// creased BUILD yet, lCount_234 reaches the lane at five vertices and is
/// declined by the corner ball's carrier-extension guard, the same final
/// refusal either way).
const CREASED_SEAM_DEFAULT: bool = true;

pub(crate) fn creased_seam_on() -> bool {
    switch!(live "BREP_BLEND_CREASED_SEAM", CREASED_SEAM_DEFAULT)
}

// BREP named hunk: end lcount234_creased_seam_join_20261016

/// Whether each selected edge is CONVEX (its ball inside the material), in
/// selection order; `None` when the selection's mates cannot be read.
pub(crate) fn selection_convexity(solid: &BrepSolid, edge_ids: &[u64], radius: f64) -> Option<Vec<bool>> {
    let mates = stripe_mates(solid, edge_ids, radius).ok()?;
    mates
        .iter()
        .map(|(edge, first, second)| edge_is_convex(edge, first, second).ok())
        .collect()
}

/// A selected edge with NO blend strip left on it: the corner balls seated at
/// its two ends touch a mate face they share at the same point, or past each
/// other, so the two corner setbacks consume the whole edge (every edge of a
/// 20-cube at r = 10, where each face shrinks to a point and the answer is
/// the r = 10 sphere).  `edge` is an index into the selection; `stops` are
/// the two tangency points on `face_id`, start corner then end corner.
pub(crate) struct DegenerateSetback {
    pub(crate) edge: usize,
    pub(crate) face_id: u64,
    pub(crate) stops: [Vec3; 2],
    pub(crate) strip: f64,
    pub(crate) bar: f64,
    /// True when the two setbacks run PAST each other along the edge (the
    /// radius is beyond the limit), false when they meet within the bar.
    pub(crate) crossed: bool,
}

/// The network refusal that must be TERMINAL for the whole selection rather
/// than a fall-through: a star–star edge whose strip pinches out.
///
/// Inside the network the same condition is caught on the marched rows
/// (`build_open_surgery`'s pinch check), but a refusal there falls through
/// to the cutter composition and the maximal-valid-subset search, and
/// neither can do better on a degenerate selection: on the r = 10 cube the
/// search returned NINE walls over a 5174 volume against the sphere's 4189.
/// So the condition is decided here, before anything is cut, from the corner
/// balls alone — at a star every stripe stops exactly at the ball's tangency
/// point on each of its mate faces, so the strip between two stars is the
/// distance between their tangency points on the face the stripe shares
/// with both, and no march is needed to measure it.  A miter's far station
/// is the seam's exit, not a tangency, so only star–star edges are decided
/// here; the in-network check keeps the rest.
///
/// `None` when nothing is degenerate OR when the balls cannot be seated at
/// all — the network reports its own refusal for that.
pub(crate) fn degenerate_corner_setbacks(
    solid: &BrepSolid,
    edge_ids: &[u64],
    radius: f64,
) -> Option<DegenerateSetback> {
    let mates = stripe_mates(solid, edge_ids, radius).ok()?;
    let scale = solid
        .vertices
        .iter()
        .fold(0.0f64, |worst, vertex| worst.max(vertex.point.length()))
        .max(1.0);
    let bar = corner_station_bar(scale, radius);
    // vertex id -> (face id, the ball's tangency point on it)
    let mut stars: Vec<(u64, Vec<(u64, Vec3)>)> = Vec::new();
    for (vertex_id, stripe_indices) in stripes_by_vertex(&mates) {
        if stripe_indices.len() < 3 {
            continue;
        }
        let point = solid
            .vertices
            .iter()
            .find(|vertex| vertex.id == vertex_id)?
            .point;
        let mut faces: Vec<(&FaceRecord, f64)> = Vec::new();
        let mut consistent = true;
        for &index in &stripe_indices {
            for mate in [&mates[index].1, &mates[index].2] {
                match faces.iter().find(|(face, _)| face.id == mate.face.id) {
                    Some((_, rho)) => {
                        consistent &= (*rho - mate.rho).abs() <= 1e-9 * (1.0 + radius);
                    }
                    None => faces.push((mate.face, mate.rho)),
                }
            }
        }
        // Not a star (an unselected edge at the vertex) or mixed: not this
        // check's question.
        if !consistent || faces.len() != stripe_indices.len() {
            continue;
        }
        let face_refs: Vec<&FaceRecord> = faces.iter().map(|(face, _)| *face).collect();
        let rho_of = |id: u64| faces.iter().find(|(face, _)| face.id == id).map(|(_, rho)| *rho);
        let Ok(prepared) = corner_faces(&face_refs, &rho_of, point) else {
            continue;
        };
        let Ok(ball) = solve_corner_ball(&prepared, scale) else {
            continue;
        };
        if ball.residual > 1e-7 * (1.0 + scale) {
            continue;
        }
        stars.push((
            vertex_id,
            ball.contacts
                .iter()
                .map(|contact| (contact.face_id, contact.point))
                .collect(),
        ));
    }
    let tangency = |vertex: u64, face_id: u64| -> Option<Vec3> {
        stars
            .iter()
            .find(|(id, _)| *id == vertex)?
            .1
            .iter()
            .find(|(id, _)| *id == face_id)
            .map(|(_, point)| *point)
    };
    for (index, (edge, first, second)) in mates.iter().enumerate() {
        if edge.start_vertex_id == edge.end_vertex_id {
            continue;
        }
        let chord = vertex_point_of(solid, edge.end_vertex_id)
            .ok()?
            .sub(vertex_point_of(solid, edge.start_vertex_id).ok()?);
        for mate in [first, second] {
            let (Some(from), Some(to)) = (
                tangency(edge.start_vertex_id, mate.face.id),
                tangency(edge.end_vertex_id, mate.face.id),
            ) else {
                continue;
            };
            let span = to.sub(from);
            let strip = span.length();
            let crossed = strip > bar && span.dot(chord) < 0.0;
            if strip <= bar || crossed {
                return Some(DegenerateSetback {
                    edge: index,
                    face_id: mate.face.id,
                    stops: [from, to],
                    strip,
                    bar,
                    crossed,
                });
            }
        }
    }
    None
}

/// Blend every edge in `edge_ids` as one network.
///
/// `edge_names` is parallel to `edge_ids` (the per-edge blend-face name);
/// `corner_name` names each star patch after the input indices meeting there.
/// Errors — always named — leave the caller's solid untouched.
pub(crate) fn blend_star_network(
    solid: &BrepSolid,
    edge_ids: &[u64],
    radius: f64,
    chamfer: bool,
    edge_names: &[Option<String>],
    corner_name: &dyn Fn(&[usize]) -> Option<String>,
) -> Result<BrepSolid, KernelRefusal> {
    blend_star_network_with_corner_policy(solid, edge_ids, radius, chamfer, edge_names, corner_name, true)
}

/// A runout's intermediate ring needs miter seams as carrier-switch witnesses.
/// Those seams are consumed by its final walls, rather than shipped as corners.
pub(crate) fn blend_star_network_with_corner_policy(
    solid: &BrepSolid,
    edge_ids: &[u64],
    radius: f64,
    chamfer: bool,
    edge_names: &[Option<String>],
    corner_name: &dyn Fn(&[usize]) -> Option<String>,
    wrap_concave: bool,
) -> Result<BrepSolid, KernelRefusal> {
    let laws = vec![super::StripeRadius::Constant(radius); edge_ids.len()];
    blend_star_network_laws(solid, edge_ids, &laws, chamfer, edge_names, corner_name, wrap_concave)
}

/// A stripe is marched at its law, with the law's domain laid between the
/// stripe's two corner stations so that its END value holds at the corner
/// (not at the vertex, and the user's end radius must hold there); every
/// corner ball, miter seam, patch and cap is solved at the end radii, which
/// the stripes meeting at a vertex must agree on. A constant law on every
/// edge is the constant-radius network, byte for byte.
pub(crate) fn blend_star_network_laws(
    solid: &BrepSolid,
    edge_ids: &[u64],
    laws: &[super::StripeRadius],
    chamfer: bool,
    edge_names: &[Option<String>],
    corner_name: &dyn Fn(&[usize]) -> Option<String>,
    wrap_concave: bool,
) -> Result<BrepSolid, KernelRefusal> {
    // A network that refuses takes back the notes its stripes recorded.
    let mark = super::blend_notes_mark();
    let result = blend_star_network_building(solid, edge_ids, laws, chamfer, edge_names, corner_name, wrap_concave);
    if result.is_err() {
        super::blend_notes_truncate(mark);
    }
    result
}

/// The refusal code of a stripe pinched between a corner setback and the
/// station where its taper to a cusp reaches the full radius.
pub(crate) const STRIPE_PINCH_TAPER_WHAT: &str = "stripe_pinch_taper";

fn blend_star_network_building(
    solid: &BrepSolid,
    edge_ids: &[u64],
    laws: &[super::StripeRadius],
    chamfer: bool,
    edge_names: &[Option<String>],
    corner_name: &dyn Fn(&[usize]) -> Option<String>,
    wrap_concave: bool,
) -> Result<BrepSolid, KernelRefusal> {
    if edge_ids.is_empty() {
        return Err(KernelRefusal::input(KernelStage::Collect, "empty_selection", "blend network: no edges selected"));
    }
    if laws.len() != edge_ids.len() || laws.iter().any(|law| !law.is_positive()) {
        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend network: radius must be positive"));
    }
    // The selection's one radius when every law is that constant; otherwise
    // the largest radius any law takes, which is what the tolerance bars and
    // the restriction's reach are sized by. Every CONSTRUCTION below takes
    // its radius from the stripe or the corner it builds, never from this.
    let radius = laws.iter().map(super::StripeRadius::largest).fold(0.0f64, f64::max);
    let _network_timing = super::BlendTimer::start("timing.network_ms");
    let analysis = super::BlendTimer::start("timing.network_analysis_ms");
    // ---- 1. Mates and signed radii, from the ORIGINAL solid. ----
    let mates = stripe_mates_laws(solid, edge_ids, laws)?;

    // ---- 2. Which selected edges meet at which vertex. ----
    let vertex_stripes = stripes_by_vertex(&mates);
    analysis.stop();

    // ---- 3. Seat a ball in every shared vertex, before anything is cut. ----
    let corner_balls = super::BlendTimer::start("timing.corner_balls_ms");
    let mut result = solid.clone();
    let mut take_id = fresh_id_source(solid);
    let scale = solid
        .vertices
        .iter()
        .fold(0.0f64, |worst, vertex| worst.max(vertex.point.length()))
        .max(1.0);
    let mut corners: Vec<(u64, Vec<usize>, VertexKind)> = Vec::new();
    // The smooth vertices whose side faces crease along their seam, closed
    // down the miter lane (`creased_seam_on`).
    let mut creased_vertices: Vec<u64> = Vec::new();
    let mut vertex_radii: Vec<(u64, f64)> = Vec::new();
    for (vertex_id, stripe_indices) in &vertex_stripes {
        if stripe_indices.len() < 2 {
            continue;
        }
        let point = solid
            .vertices
            .iter()
            .find(|vertex| vertex.id == *vertex_id)
            .ok_or_else(|| format!("blend network: vertex {vertex_id} missing")).or_refuse(KernelStage::Refine, "ok_or_else")?
            .point;
        // Lane L: a mixed star (one concave + two convex stripes at an
        // orthogonal planar corner) is its own kind, read before the faces'
        // sides are compared (they disagree there by construction).
        if !chamfer && stripe_indices.len() == 3 && mixed_star_on() {
            let ends: Vec<f64> = stripe_indices
                .iter()
                .map(|&index| laws[index].end(mates[index].0.start_vertex_id == *vertex_id))
                .collect();
            let constant = stripe_indices.iter().all(|&index| laws[index].constant().is_some());
            if constant && ends.iter().all(|end| (end - ends[0]).abs() <= 1e-12 * (1.0 + ends[0])) {
                if let Some(mixed) = detect_mixed_star(&mates, stripe_indices, point, ends[0]) {
                    vertex_radii.push((*vertex_id, ends[0]));
                    corners.push((*vertex_id, stripe_indices.clone(), VertexKind::MixedStar(mixed)));
                    continue;
                }
            }
        }
        // The faces around the corner are the mates of the stripes that end
        // there, with the signed offset each stripe was marched at.
        let mut faces: Vec<(&FaceRecord, f64, usize)> = Vec::new();
        // `faces` then carries the LARGER magnitude (what the
        // classification ball and the bars at this vertex are sized by) and
        // the vertex is an UNEQUAL corner, which only the convex two-edge
        // miter builds below. `(face, the two radii)` for the message.
        let mut unequal: Option<(u64, f64, f64)> = None;
        for &index in stripe_indices {
            let end_radius = laws[index].end(mates[index].0.start_vertex_id == *vertex_id);
            for mate in [&mates[index].1, &mates[index].2] {
                let rho_end = mate.rho.signum() * end_radius;
                match faces.iter_mut().find(|(face, _, _)| face.id == mate.face.id) {
                    Some((_, rho, uses)) => {
                        if rho.signum() != rho_end.signum() {
                            return Err(KernelRefusal::unsupported(KernelStage::Classify, "mixed_convexity", format!(
                                "blend network: the stripes at vertex {vertex_id} disagree on \
                                 which side of face {} the ball sits (mixed convexity)",
                                mate.face.id
                            )));
                        }
                        if (*rho - rho_end).abs() > 1e-9 * (1.0 + radius) {
                            if unequal.is_none() {
                                unequal = Some((mate.face.id, rho.abs(), end_radius));
                            }
                            if rho_end.abs() > rho.abs() {
                                *rho = rho_end;
                            }
                        }
                        *uses += 1;
                    }
                    None => faces.push((mate.face, rho_end, 1)),
                }
            }
        }
        // The one radius every solve at this vertex uses (C2): the stripes'
        // common end radius, which the loop above has just checked — or, at
        // an unequal corner, the larger of them.
        let corner_radius = faces.iter().map(|(_, rho, _)| rho.abs()).fold(0.0f64, f64::max);
        vertex_radii.push((*vertex_id, corner_radius));
        let tapered_here = stripe_indices.iter().any(|&index| laws[index].constant().is_none());
        let is_star = stripe_indices.len() >= 3;
        let refuse_unequal = |why: &str| -> KernelRefusal {
            let (face_id, first, second) = unequal.unwrap_or((0, 0.0, 0.0));
            KernelRefusal::unsupported(KernelStage::Classify, "unequal_corner_radius", format!(
                "blend network: the stripes at vertex {vertex_id} end at different radii \
                 on face {face_id} ({first:.6} and {second:.6}); {why}"
            ))
        };
        let mut ribbon_star = false;
        if unequal.is_some() {
            if is_star {
                if !super::no_common_ball_star_on() {
                    return Err(refuse_unequal("an unequal-radius star has no common ball and its N-sided fill is not in this lane"));
                }
                if tapered_here {
                    return Err(refuse_unequal("an unequal-radius star at a varying radius is not in this lane"));
                }
                ribbon_star = true;
            } else {
                if !super::unequal_miter_on() {
                    return Err(refuse_unequal("an unequal-radius corner is not in this lane"));
                }
                if tapered_here {
                    return Err(refuse_unequal("an unequal-radius corner at a varying radius is not in this lane"));
                }
            }
        }
        if is_star && faces.len() != stripe_indices.len() {
            return Err(KernelRefusal::unsupported(KernelStage::Classify, "partial_corner_selection", format!(
                "blend network: vertex {vertex_id} has {} selected edges around {} faces — \
                 not every edge at the corner is selected, so no ball seats there",
                stripe_indices.len(),
                faces.len()
            )));
        }
        // A two-edge vertex: a G1 continuation is a CHAIN, not a corner (one
        // stripe should run through it — `blend_smooth_chain`); otherwise the
        // two stripes must share exactly one face with one sharp edge
        // between the other two.
        let mut miter: Option<(&FaceRecord, &EdgeRecord)> = None;
        let mut creased = false;
        if !is_star {
            let [a, b] = [stripe_indices[0], stripe_indices[1]];
            let tangent_a = tangent_away_from(mates[a].0, *vertex_id)?;
            let tangent_b = tangent_away_from(mates[b].0, *vertex_id)?;
            if tangent_a.dot(tangent_b) <= -(1.0 - 1e-6) {
                if unequal.is_some() {
                    return Err(refuse_unequal("a flush join at two radii is a step, not a corner, and is not in this lane"));
                }
                if tapered_here && !super::relief::tapered_flush_join_on() {
                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "tapered_flush_join", format!(
                        "blend network: a tapered stripe runs through the smooth vertex {vertex_id}; \
                         a flush join at a varying radius is not in this lane"
                    )));
                }
                // The join is ONE ball on both sides, at the stripes' common
                // END radius here (checked equal above): a tapered stripe's
                // mates carry its midpoint radius, so the join is solved on
                // mates re-signed at the end radius (2026-10-21, the local
                // radius relief, whose ramps cross the smooth vertices of a
                // face's outline).
                let at_end = |index: usize| {
                    let (edge, first, second) = &mates[index];
                    let end = laws[index].end(edge.start_vertex_id == *vertex_id);
                    (*edge, mate_at_radius(first, end), mate_at_radius(second, end))
                };
                let (join_a, join_b) = (at_end(a), at_end(b));
                match flush_join(solid, &join_a, &join_b, *vertex_id, point, scale) {
                    Ok(join) => {
                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                            match &join {
                                Some(join) => eprintln!(
                                    "flush join at vertex {vertex_id} (edges {} and {}): ball centre ({:.6}, {:.6}, {:.6}); contacts {}",
                                    mates[a].0.id,
                                    mates[b].0.id,
                                    join.center.x,
                                    join.center.y,
                                    join.center.z,
                                    join.contacts
                                        .iter()
                                        .map(|contact| format!(
                                            "faces {:?} at ({:.6}, {:.6}, {:.6}) seam {:?}",
                                            contact.faces, contact.point.x, contact.point.y, contact.point.z, contact.seam
                                        ))
                                        .collect::<Vec<_>>()
                                        .join("; ")
                                ),
                                None => eprintln!("flush join at vertex {vertex_id} (edges {} and {}): the vertex section (same two faces)", mates[a].0.id, mates[b].0.id),
                            }
                        }
                        corners.push((*vertex_id, stripe_indices.clone(), VertexKind::Flush { join }));
                        continue;
                    }
                    // A creased seam (the side faces tangent only at the
                    // vertex) goes down the miter lane, its seam the sharp
                    // edge.
                    Err(refusal)
                        if creased_seam_on()
                            && matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "flush_join") =>
                    {
                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                            eprintln!("creased seam at vertex {vertex_id}: {refusal}; trying the miter lane");
                        }
                        creased = true;
                        creased_vertices.push(*vertex_id);
                    }
                    Err(refusal) => return Err(refusal),
                }
            }
            if faces.len() != 3 {
                return Err(KernelRefusal::unsupported(KernelStage::Classify, "corner_face_count", format!(
                    "blend network: vertex {vertex_id} has two selected edges around {} faces \
                     (expected exactly three: one shared, one on each side)",
                    faces.len()
                )));
            }
            let shared = faces
                .iter()
                .find(|(_, _, uses)| *uses == 2)
                .map(|(face, _, _)| *face)
                .ok_or_else(|| {
                    format!("blend network: the two edges at vertex {vertex_id} share no face")
                }).or_refuse(KernelStage::Refine, "ok_or_else")?;
            let others: Vec<&FaceRecord> = faces
                .iter()
                .filter(|(face, _, _)| face.id != shared.id)
                .map(|(face, _, _)| *face)
                .collect();
            // The sharp edge borders both non-shared faces at the vertex.
            let (other_a, other_b) = (others[0], others[1]);
            let sharp_a = boundary_edge_at_vertex(solid, other_a, *vertex_id, mates[a].0.id)
                .or_else(|_| boundary_edge_at_vertex(solid, other_a, *vertex_id, mates[b].0.id))?;
            let sharp_b = boundary_edge_at_vertex(solid, other_b, *vertex_id, mates[a].0.id)
                .or_else(|_| boundary_edge_at_vertex(solid, other_b, *vertex_id, mates[b].0.id))?;
            if sharp_a != sharp_b {
                return Err(KernelRefusal::unsupported(KernelStage::Classify, "corner_sharp_edges", format!(
                    "blend network: vertex {vertex_id} has more than one unselected edge \
                     between the side faces (found {sharp_a} and {sharp_b})"
                )));
            }
            let sharp = solid
                .edges
                .iter()
                .find(|edge| edge.id == sharp_a)
                .ok_or(KernelRefusal::internal(KernelStage::Refine, "sharp_edge", "blend network: the sharp edge vanished"))?;
            if sharp.start_vertex_id == sharp.end_vertex_id {
                return Err(KernelRefusal::unsupported(KernelStage::Classify, "closed_sharp_edge", "blend network: the sharp edge at a miter is closed"));
            }
            // Opposite convexities wrap the sharp edge rather than seating
            // a three-plane ball whose two cylinders meet in a sharp seam.
            // Oblique concave corners retain their asymmetric miter lane.
            let sharp_convex = sharp_edge_is_convex(solid, sharp, other_a, other_b, corner_radius)?;
            let selected_convex = [a, b].iter().all(|&index| {
                let (edge, first, second) = &mates[index];
                edge_is_convex(edge, first, second).unwrap_or(false)
            });
            let selected_concave = [a, b].iter().all(|&index| {
                let (edge, first, second) = &mates[index];
                edge_is_convex(edge, first, second).is_ok_and(|convex| !convex)
            });
            // A ball outside the material wraps a convex boss corner just
            // as a ball inside wraps a concave notch. Both are horn sectors;
            // intersecting the two concave stripes instead makes a sharp seam.
            let plane_normal = |face: &FaceRecord| match face.surface.analytic() {
                Some(crate::AnalyticSurface::Plane { u_dir, v_dir, .. }) => u_dir.cross(*v_dir).normalized().ok(),
                _ => None,
            };
            let perpendicular_cap = plane_normal(shared).zip(plane_normal(other_a))
                .zip(plane_normal(other_b))
                .is_some_and(|((cap, a), b)| cap.dot(a).abs() < 1e-6 && cap.dot(b).abs() < 1e-6);
            if (!sharp_convex && selected_convex)
                || (wrap_concave && !chamfer && sharp_convex && selected_concave && perpendicular_cap) {
                if unequal.is_some() {
                    return Err(refuse_unequal("the horn-torus closure at a re-entrant vertex needs one ball and is not in this lane at two radii"));
                }
                if tapered_here {
                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "tapered_reentrant", format!(
                        "blend network: a tapered stripe ends at the re-entrant vertex {vertex_id}; \
                         the horn-torus closure at a varying radius is not in this lane"
                    )));
                }
                corners.push((
                    *vertex_id,
                    stripe_indices.clone(),
                    VertexKind::Reentrant { cap: shared, sharp },
                ));
                continue;
            }
            if !sharp_convex && !concave_miter_on() {
                // An INSIDE corner: every edge at the vertex is concave and
                // two are selected.  This is not the horn torus's mirror (the
                // horn's mirror is two concave stripes over a CONVEX sharp
                // edge, built above): a ball in the air here is seated by all
                // three faces at once and cannot wrap the sharp edge without
                // entering a wall, so the two pads meet in a SEAM from their
                // floor rails' crossing up to the sharp edge — the mirror of
                // the convex two-edge miter.  `BREP_BLEND_CONCAVE_MITER=1`
                // sends it down that miter lane; off, refused by name.
                return Err(KernelRefusal::unsupported(KernelStage::Classify, REENTRANT_CONCAVE_WHAT, format!(
                    "blend network: vertex {vertex_id} at ({:.3}, {:.3}, {:.3}) is an inside corner: the selected \
                     concave edges {} and {} meet the unselected concave edge {}; the ball in the air is seated by \
                     all three faces and cannot wrap that edge, so the closure is the two pads' seam up to it (the \
                     mirror of the convex two-edge miter, not of the horn torus), which this lane does not build",
                    point.x, point.y, point.z, mates[a].0.id, mates[b].0.id, sharp.id
                )));
            }
            miter = Some((shared, sharp));
        }
        let face_refs: Vec<&FaceRecord> = faces.iter().map(|(face, _, _)| *face).collect();
        let rho_of = |id: u64| {
            faces
                .iter()
                .find(|(face, _, _)| face.id == id)
                .map(|(_, rho, _)| *rho)
        };
        // A creased seam's side faces are tangent AT the vertex, where the
        // corner-ball Newton is singular, so it is seeded a radius up the seam.
        let seed = match (creased, miter) {
            (true, Some((_, sharp))) => point.add(tangent_away_from(sharp, *vertex_id)?.scale(corner_radius)),
            _ => point,
        };
        let prepared = corner_faces(&face_refs, &rho_of, seed)?;
        let ball = solve_corner_ball(&prepared, scale)?;
        if creased && std::env::var("BREP_DEBUG_NETWORK").is_ok() {
            eprintln!("creased seam corner ball at vertex {vertex_id}: centre {:?} residual {:.3e} contacts {:?}", ball.center, ball.residual, ball.contacts.iter().map(|c| (c.face_id, c.point)).collect::<Vec<_>>());
        }
        // The residual IS the common-ball test: N = 3 always has a root, and
        // beyond that a non-zero residual means the fillet cylinders have no
        // single inscribed sphere and the notch needs an N-sided fill.
        let bar = 1e-7 * (1.0 + scale);
        if ball.residual > bar && !ribbon_star {
            if is_star && super::no_common_ball_star_on() && !tapered_here {
                ribbon_star = true;
            } else {
                return Err(KernelRefusal::unsupported(KernelStage::Refine, "n_sided_corner", format!(
                    "blend network: the {} fillets at vertex {vertex_id} have no common inscribed \
                     ball (residual {:.3e} > {bar:.3e}); an N-sided corner fill is not implemented",
                    stripe_indices.len(),
                    ball.residual
                )));
            }
        }
        // Which side of the walls the ball sits on is the corner's
        // convexity: inside the material on every face (convex, the patch
        // faces away from the centre) or in the air on every face (concave,
        // the patch faces toward it).  One of each is a MIXED corner, whose
        // closure is not a sphere at all (the torus-sector class) and is
        // refused here by name.
        let mut inside = 0usize;
        let mut in_air = 0usize;
        for contact in &ball.contacts {
            let face = face_refs
                .iter()
                .find(|face| face.id == contact.face_id)
                .ok_or(KernelRefusal::unsupported(KernelStage::Refine, "ball_off_corner", "blend network: the ball touched a face that is not at the corner"))?;
            let face_outward = if face.same_sense {
                contact.normal
            } else {
                contact.normal.scale(-1.0)
            };
            let ball_inside_material = ball.center.sub(contact.point).dot(face_outward) < 0.0;
            if ball_inside_material {
                inside += 1;
            } else {
                in_air += 1;
            }
            // At a miter whose ball sits INSIDE the material the ball must
            // touch each SIDE face on the face itself, not on its carrier
            // beyond a concave edge: two convex edges meeting at a re-entrant
            // vertex (their third edge concave) have no seam — the ball rolls
            // round the concave edge instead and the closure is a horn torus,
            // which this lane does not build.
            //
            // A ball in the AIR is the mirror case and this test says nothing
            // there: two CONCAVE edges mitering over a convex sharp edge (the
            // base of a boss, a rib standing on a floor) seat their ball on
            // the far side of that sharp edge, so its contact with each side
            // wall is ALWAYS beyond the wall's own boundary — the sliver runs
            // past the corner and the two blends meet in the seam through
            // that contact.  The re-entrant class those two are told apart by
            // is the sharp edge's convexity, which `sharp_edge_is_convex`
            // already decided above.
            if let Some((shared, _)) = miter.filter(|_| ball_inside_material) {
                if contact.face_id != shared.id {
                    let class = crate::parameter_point_in_face(
                        face,
                        crate::Vec2 {
                            x: contact.uv[0],
                            y: contact.uv[1],
                        },
                        1e-6,
                    ).or_refuse(KernelStage::Refine, "parameter_point_in_face")?;
                    // ON the boundary is not beyond it.  The ball of a miter
                    // whose radius is the side face's own width touches that
                    // face at its far corner: the two blends consume the shared
                    // face and both side faces whole at the corner (10-cube,
                    // two top edges, r = d = 10).  That is the ordinary miter
                    // with its shared-face rails collapsed to a point, which
                    // the surgery and `collapse_full_width` build; a contact
                    // BEYOND the boundary is the re-entrant class below.
                    if class != crate::PolygonClass::Inside
                        && class != crate::PolygonClass::Boundary
                    {
                        return Err(KernelRefusal::unsupported(KernelStage::Classify, "reentrant_horn_torus", format!(
                            "blend network: vertex {vertex_id} is re-entrant — the ball \
                             touches face {} beyond its edge, so the two blends do not meet \
                             in a seam but wrap the concave edge (horn-torus closure, not in \
                             this lane)",
                            contact.face_id
                        )));
                    }
                }
            }
        }
        let outward = match (inside, in_air) {
            (_, 0) => true,
            (0, _) => false,
            _ => {
                return Err(KernelRefusal::unsupported(KernelStage::Classify, "mixed_corner", format!(
                    "blend network: vertex {vertex_id} mixes convex and concave edges ({inside} \
                     faces with the ball inside, {in_air} with it in the air); a mixed corner \
                     is not closed by a sphere and this lane does not build it"
                )))
            }
        };
        // A corner is always OUTSIDE its own inscribed ball (a cube corner
        // sits at r√3 from the centre, a nearly flat one at r).  A centre
        // solved on the wrong branch fails this before anything is cut.
        if point.sub(ball.center).length() < corner_radius * (1.0 - 1e-6) {
            return Err(KernelRefusal::internal(KernelStage::Refine, "ball_branch", format!(
                "blend network: the ball solved at vertex {vertex_id} swallows the corner \
                 itself ({:.6} < {corner_radius}) — wrong branch",
                point.sub(ball.center).length()
            )));
        }
        // The point both shared-face rails stop at is their RAIL/RAIL point,
        // the one contact on the shared face that the two stripes' balls, each
        // at its own radius, share (`solve_rail_rail_point`); the seam starts
        // there. Only the convex miter is built: a concave one seats its balls
        // past the vertex and the seam runs back into the span, which this row
        // has not measured. Stripe `index`'s part in a rail/rail solve on face
        // `shared_id`: its other mate is the side face, each at the stripe's
        // signed end radius.
        let rail_rail_stripe = |index: usize, shared_id: u64| -> RailRailStripe<'_> {
            let end_radius = laws[index].end(mates[index].0.start_vertex_id == *vertex_id);
            let (_, first, second) = &mates[index];
            let (on_shared, on_side) = if first.face.id == shared_id {
                (first, second)
            } else {
                (second, first)
            };
            RailRailStripe {
                side: on_side.face,
                rho_shared: on_shared.rho.signum() * end_radius,
                rho_side: on_side.rho.signum() * end_radius,
            }
        };
        let rail_rail = match (unequal, miter) {
            (Some(_), Some((shared, _))) => {
                if !outward {
                    return Err(refuse_unequal("a concave unequal-radius corner is not in this lane"));
                }
                let described = [rail_rail_stripe(stripe_indices[0], shared.id), rail_rail_stripe(stripe_indices[1], shared.id)];
                let solved = solve_rail_rail_point(shared, [&described[0], &described[1]], point, scale)?;
                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                    eprintln!(
                        "network unequal miter at vertex {vertex_id}: rail/rail point {:?} on face {} \
                         (uv {:?}, residual {:.3e}), centres {:?}",
                        solved.point, shared.id, solved.uv, solved.residual, solved.centers
                    );
                }
                Some(solved)
            }
            _ => None,
        };
        // Only the convex star is built.
        let star_points: Vec<(u64, RailRailPoint)> = if ribbon_star {
            if chamfer {
                return Err(KernelRefusal::unsupported(KernelStage::Refine, "n_sided_corner", format!(
                    "blend network: the {} chamfers at vertex {vertex_id} have no common inscribed \
                     ball; the ribbon fill is a fillet's and a chamfer's facet is not in this lane",
                    stripe_indices.len()
                )));
            }
            if !outward {
                return Err(KernelRefusal::unsupported(KernelStage::Refine, "n_sided_corner", format!(
                    "blend network: the {} fillets at vertex {vertex_id} have no common inscribed \
                     ball and the corner is concave; the ribbon fill is not in this lane there",
                    stripe_indices.len()
                )));
            }
            let mut solved = Vec::with_capacity(faces.len());
            for (face, _, _) in &faces {
                let bordering: Vec<usize> = stripe_indices
                    .iter()
                    .copied()
                    .filter(|&index| mates[index].1.face.id == face.id || mates[index].2.face.id == face.id)
                    .collect();
                if bordering.len() != 2 {
                    return Err(KernelRefusal::internal(KernelStage::Refine, "star_face_stripes", format!(
                        "blend network: face {} at vertex {vertex_id} borders {} selected stripes, not two",
                        face.id,
                        bordering.len()
                    )));
                }
                let described = [rail_rail_stripe(bordering[0], face.id), rail_rail_stripe(bordering[1], face.id)];
                let point_on = solve_rail_rail_point(face, [&described[0], &described[1]], point, scale)?;
                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                    eprintln!(
                        "network ribbon star at vertex {vertex_id}: rail/rail point {:?} on face {} \
                         (residual {:.3e})",
                        point_on.point, face.id, point_on.residual
                    );
                }
                solved.push((face.id, point_on));
            }
            solved
        } else {
            Vec::new()
        };
        // Commit the tangency vertices a star needs on every face; a miter
        // only needs the one on the shared face, and creates its other rim
        // vertices from the seam.
        let mut tangency = Vec::with_capacity(ball.contacts.len());
        for contact in &ball.contacts {
            let needed = match miter {
                Some((shared, _)) => contact.face_id == shared.id,
                None => true,
            };
            let point = match (&rail_rail, miter) {
                (Some(solved), Some((shared, _))) if contact.face_id == shared.id => solved.point,
                _ => star_points
                    .iter()
                    .find(|(face_id, _)| *face_id == contact.face_id)
                    .map(|(_, solved)| solved.point)
                    .unwrap_or(contact.point),
            };
            let id = if needed {
                let id = take_id();
                result.vertices.push(VertexRecord { id, point });
                id
            } else {
                0
            };
            tangency.push((contact.face_id, point, id));
        }
        let corner = Corner {
            center: ball.center,
            outward,
            tangency,
            radius: corner_radius,
        };
        let kind = match miter {
            Some((shared, sharp)) => VertexKind::Miter {
                corner,
                shared,
                sharp,
            },
            None if ribbon_star => VertexKind::RibbonStar { corner },
            None => VertexKind::Star { corner },
        };
        corners.push((*vertex_id, stripe_indices.clone(), kind));
    }

    // §6.11 closes a chamfered corner differently from a filleted one, and
    // EVERY kind is built here now: a star's stripes stop at the ball and
    // their end CHORDS bound the facet they bound; a miter's two bevels trim
    // each other along the seam `solve_miter` marches on the chamfer's own
    // level; a flush join shares one chord where a fillet shares one arc; and
    // a re-entrant corner revolves that chord about the concave edge into a
    // CONE where a fillet's ball envelope gives the horn torus.  No chamfer
    // corner reaches the cutter composition any more.

    corner_balls.stop();
    super::record_count("count.corners", corners.len() as u64);

    // ---- 4. March and fit every stripe, against the ORIGINAL solid. ----
    let vertex_radius_of = |vertex: u64| -> Option<f64> {
        vertex_radii.iter().find(|(id, _)| *id == vertex).map(|(_, radius)| *radius)
    };
    let mut stripes: Vec<Stripe> = Vec::with_capacity(mates.len());
    super::record_count("count.stripes", mates.len() as u64);
    for (index, (edge, first, second)) in mates.iter().enumerate() {
        // Where the rows are broken: at each vertex, or — at a flush join
        // across a seam — at the seam ball, the section where this stripe's
        // side contact leaves its carrier (`march_open_stations_ending`).
        let mut ends = [edge.t0, edge.t1];
        for (slot, vertex) in [edge.start_vertex_id, edge.end_vertex_id].into_iter().enumerate() {
            if let Some((_, _, VertexKind::Flush { join: Some(join) })) =
                corners.iter().find(|(id, _, _)| *id == vertex)
            {
                let before = ends[slot];
                ends[slot] = section_parameter_through(edge, join.center, ends[slot], scale)
                    .map_err(|error| {
                        format!(
                            "blend network: edge {}'s section through the flush join's ball at \
                             vertex {vertex}: {error}",
                            edge.id
                        )
                    }).or_refuse(KernelStage::Refine, "map_err")?;
                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                    eprintln!(
                        "flush join at vertex {vertex}: edge {}'s end moves from t={before:.6} to the seam ball's section t={:.6} (edge t in [{:.6}, {:.6}]); ball centre {:?}",
                        edge.id, ends[slot], edge.t0, edge.t1, join.center
                    );
                }
            }
        }
        let law = &laws[index];
        let end_radius = [law.end(true), law.end(false)];
        // A constant law is the constant radius everywhere, whatever the
        // ends read.
        let law_ends: [f64; 2] = {
            let mut law_ends = ends;
            if law.constant().is_none() {
                for (slot, vertex) in [edge.start_vertex_id, edge.end_vertex_id].into_iter().enumerate() {
                    if let Some((_, _, VertexKind::Star { corner } | VertexKind::Miter { corner, .. })) =
                        corners.iter().find(|(id, _, _)| *id == vertex)
                    {
                        law_ends[slot] = section_parameter_through(edge, corner.center, law_ends[slot], scale)
                            .map_err(|error| {
                                format!(
                                    "blend network: edge {}'s section through the corner ball at \
                                     vertex {vertex}: {error}",
                                    edge.id
                                )
                            }).or_refuse(KernelStage::Refine, "map_err")?;
                    }
                }
            }
            law_ends
        };
        // A tapered stripe's rows are BROKEN at its corner stations, as a
        // flush join's are at the seam ball: the march pins a station on each
        // (`open_station_parameters`), so the law's end value — and the kink
        // where it goes flat — sits ON an interpolation node and the fitted
        // rail passes through the corner ball's tangency point exactly,
        // instead of a cubic through the neighbouring stations missing it by
        // the kink's sagitta (4.7e-4 on the 10-box taper 1 → 2).
        if law.constant().is_none() {
            ends = law_ends;
        }
        let radius_at = |t: f64| -> f64 {
            match law.constant() {
                Some(radius) => radius,
                None => law.at_fraction((t - law_ends[0]) / (law_ends[1] - law_ends[0])),
            }
        };
        // The constant a wall is judged against: a tapered stripe has no
        // single rolling ball (as the open edge's variable lane), so its wall
        // is not judged and it takes no exact lane.
        let wall_radius = law.constant();
        // The open march climbs when its FITTED RAILS do not stand on the
        // carriers they are tangent to, read between the stations they were
        // fitted through (`rails_off_carriers`).  Measured, not estimated: a
        // sagitta rule over the same stripes drove the lobe to 229 stations and
        // cost this document 49.6%, because a curvature estimate cannot see
        // that a stripe is already exact.  Here the five straight stripes of
        // the notched cap read 7e-15 on rung zero and never climb, and only the
        // two genuinely curved, genuinely fitted ones pay.
        //
        // The bar is HALF `intersection_fit`, and the halving is the only new
        // number here.  `intersection_fit` is the right family -- it is
        // literally "maximum geometric error accepted while fitting", the same
        // quantity step 2 holds a marched seam to -- but its VALUE was set for
        // an SSI curve, whose consumer is a trim.  A blend rail's consumer is a
        // FACE, whose area enters the solid's volume, and the measured transfer
        // on a filleted part is about tenfold: on the notched cap 2026-09-16 a
        // rail 1.419e-6 off its cylinder puts the solid 1.618e-5 off its closed
        // form.  So a rail sitting exactly at `intersection_fit` (2e-6 here)
        // leaves that row twice outside its own 1e-5 band, and the bar has to
        // be tighter than the contract it comes from.
        //
        // Measured across the bar, notched cap (delta against the closed form,
        // and the whole document's replay, best of three alternating):
        //
        //   bar             delta        cap      revolve_test  bore mouth
        //   2e-6 = fit     -1.618e-5     +0%          +0%           +0%     RED
        //   1e-6 = fit/2   +3.128e-6     +5%         +22%           +0%
        //   2e-7 = 2*model -7.897e-7    +55%         +73%          +16%
        //   1e-7 = model   -1.126e-6   +150%
        //
        // The two tighter bars buy no accuracy the band can see and cost what
        // this project rejects, so the ladder stops at fit/2.
        // A free end whose two mates run tangent into it is a POLE: the
        // section shrinks to the vertex, the march stops there instead of
        // overshooting, and the end is closed by that point (step 6).  The
        // test is a positive identification: a vertex whose offsets cannot be
        // read (no regular normal in reach) is not called a pole, and keeps
        // the free end's own construction and refusals.
        let mut poles = [false, false];
        for (slot, vertex) in [edge.start_vertex_id, edge.end_vertex_id].into_iter().enumerate() {
            if corners.iter().any(|(id, _, _)| *id == vertex) {
                continue;
            }
            let (first_end, second_end) = (mate_at_radius(first, end_radius[slot]), mate_at_radius(second, end_radius[slot]));
            poles[slot] =
                pole_end(edge, &first_end, &second_end, slot == 0, corner_station_bar(scale, end_radius[slot]))
                    .unwrap_or(false);
        }
        // A tapered stripe that stops at a flush join with its own two faces
        // (the vertex section) needs nothing past it, and past it the
        // edge's straight extension may leave the carrier it curls along: on
        // report 5e49bb42's cap rim the relieved stripe's overshoot stations
        // stopped converging 1.8 mm past the vertex. Such an end may stop at
        // its last converged station; the rails must still reach the join
        // (`corner_rails_reach`, read as the end's settlement below).
        let tapered_flush = law.constant().is_none() && super::relief::tapered_flush_join_on();
        let bounded_ends = [edge.start_vertex_id, edge.end_vertex_id].map(|vertex| {
            match corners.iter().find(|(id, _, _)| *id == vertex) {
                Some((_, _, VertexKind::Flush { join: None })) => tapered_flush,
                Some(_) => false,
                None => solid.edges.iter().any(|boundary| boundary.degenerate && boundary.start_vertex_id == vertex),
            }
        });
        let rail_bar = 0.5 * crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
        // The ladder this stripe climbs: the shared rungs, and past them the
        // rungs a CONCAVE corner at either end asks for.  The shared rungs
        // are fractions of the edge's own span, and a concave corner's ball
        // sits a fixed distance past the vertex — about a radius, more
        // between oblique walls — so an edge shorter than about two radii
        // can never carry its rail to that ball on them, and the network
        // refused the whole selection ("contact rail ... misses the corner
        // ball's tangency point") before the cutter capped the corner.  The
        // rungs added here are read off the corner ball already seated
        // (`concave_corner_reach`); nothing changes for a stripe the shared
        // rungs settle, because the climb stops at the first rung that does.
        // A FLUSH JOIN across a seam places its stop where the stripe's side
        // contact crosses the seam (`ends`, the section through the seam
        // ball), and that can sit well past the vertex: on the 2026-10-17
        // shell report the torus|column stripe's contact crosses the pad's
        // rail 0.94 of the stripe's own span beyond its vertex, so no shared
        // rung carried the rows to the stop and the join refused "outside
        // the marched rows" on every rung. The reach a flush end asks for is
        // read off `ends` exactly as a concave corner's is read off its ball.
        let flush_reach = {
            let span = (edge.t1 - edge.t0).abs();
            [(edge.t0 - ends[0]) / span, (ends[1] - edge.t1) / span]
                .into_iter()
                .filter(|reach| reach.is_finite())
                .fold(0.0f64, f64::max)
        };
        let ladder = concave_corner_ladder(edge, &corners, flush_reach);
        // A rung below the reach the ends ask for (`ladder_reach`) cannot
        // carry the rows to them: with `short_rungs_deferred_on` the ladder
        // marches the rungs that can first, and the short ones only when none
        // of those settles (`count.march.short_rungs_deferred` / `_run`).
        let needed_reach = ladder_reach(edge, &corners, flush_reach);
        // The rung's MEASUREMENT, as the open edge's (C3): rails positive and
        // finite inside the rail bar on samples of both rails, and -- a FILLET
        // only (the network's one scalar radius is constant by construction;
        // a chamfer is not judged) -- the wall against the rolling ball's
        // exact centres at `intersection_fit`, then the construction request
        // toward `model` on this same ladder (STATIONS doubling to
        // MAX_OPEN_STATIONS). The ladder can read only the VERTEX window: the
        // shipped windows are fixed by the end plans, and are read again there
        // (step 7) before any claim is made about what ships.
        let wall_check = !chamfer && wall_radius.is_some() && super::station_refinement_on();
        let wall_bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
        let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
        let accepts = |reading: &OpenRungReading| {
            reading.rails_read()
                && reading.rails <= rail_bar
                && (!wall_check || reading.worst_wall().is_some_and(|wall| wall <= wall_bar))
        };
        let meets_model = |reading: &OpenRungReading| reading.worst_wall().is_some_and(|wall| wall <= model);
        let mut chosen: Option<(FittedRows, Vec<f64>, StationRefinement, Vec<Station>, [usize; 2], OpenDenseCentres)> = None;
        let mut last_error: Option<KernelRefusal> = None;
        let mut station_count = super::stations::STATIONS;
        let mut accepted: Option<StripeRung> = None;
        let mut unaccepted: Option<StripeRung> = None;
        let mut request_rungs = 0usize;
        let mut unmet: Option<crate::BudgetReason> = None;
        // Its stations are solved once (every station is a translate of the
        // first, and the fit below checks exactly that), and the ladder's
        // refinement, fold probe, dense centres and ball-resolve wall reading —
        // tautologies on an exact extrusion — are not run; the wall is read
        // directly off the exact rows (`exact_extrusion_wall_readings`). A fit
        // that does not come back exact hands the stripe to the ladder.
        let extrusion = wall_radius.and_then(|_| extrusion_direction(edge, first, second));
        let mut exact_lane = super::exact_lane_on() && extrusion.is_some();
        // The exact REVOLUTION lane (`exact_revolution_on`): a circular
        // edge between a plane and a coaxial revolution carrier is one
        // section revolved. Decided before any station is solved, for a
        // stripe whose two ends a corner stops (a free end's crossing lies
        // in the overshoot, where the carrier's ruled extension and the
        // circle the rows follow part company); the rows are built by
        // `exact_revolution_rows`, which declines by name to the ladder
        // when its witness does not hold.
        let cornered_ends = [edge.start_vertex_id, edge.end_vertex_id]
            .iter()
            .all(|vertex| corners.iter().any(|(id, _, _)| id == vertex));
        let mut revolution = if exact_lane || wall_radius.is_none() || !cornered_ends || !super::exact_revolution_on() {
            None
        } else {
            revolution_lane_axis(edge, first, second)
        };
        // On an edge STATIONARY at a vertex (its derivative vanishes there) the
        // carrier projection stalls near that end: zero_tangent_sites'
        // stationary start read 3.02e-2 for a rail that sits exactly on its
        // plane y = 0 (worst point (0.030, 0, 4.5)); a pcurve-seeded Newton
        // read 3.6e-4 there, and the rail-to-pcurve distance 1.2e-3. There a
        // rail that misses is reported UNREAD, never as that distance.
        let stationary_end = [edge.t0, edge.t1].into_iter().any(|t| {
            edge.curve
                .derivatives(t, 1)
                .map_or(false, |derivatives| derivatives[1].normalized().is_err())
        });
        'rung: loop {
        // A rung climbed to after acceptance is a request rung ATTEMPTED.
        if accepted.is_some() {
            request_rungs += 1;
        }
        chosen = None;
        // (overshoot, deferred): in ladder order, or with the short rungs
        // after the rest. A short rung that runs keeps its precedence: the
        // first rung that fits is the one shipped when none settles, and the
        // last error the one reported when none fits.
        let order: Vec<(f64, bool)> = if short_rungs_deferred_on() {
            let reaching = ladder.iter().filter(|overshoot| **overshoot >= needed_reach).map(|overshoot| (*overshoot, false));
            let short: Vec<(f64, bool)> =
                ladder.iter().filter(|overshoot| **overshoot < needed_reach).map(|overshoot| (*overshoot, true)).collect();
            super::record_count("count.march.short_rungs_deferred", short.len() as u64);
            reaching.chain(short).collect()
        } else {
            ladder.iter().map(|overshoot| (*overshoot, false)).collect()
        };
        let (mut deferred_taken, mut reaching_error) = (false, false);
        for &(overshoot, deferred) in &order {
            if deferred {
                super::record_count("count.march.short_rungs_run", 1);
            }
            let march_timing = super::BlendTimer::start("timing.march_ms");
            let rung_measure: &'static str = match station_count {
                64 => "timing.march.stations_64_ms",
                128 => "timing.march.stations_128_ms",
                256 => "timing.march.stations_256_ms",
                _ => "timing.march.stations_other_ms",
            };
            let rung_timing = super::BlendTimer::start(rung_measure);
            // Both exact lanes march once, with no refinement, dense centres
            // or fold probe (tautologies on an extrusion; the revolution lane
            // declines a wall that could fold before the rows are built).
            let probes_off = exact_lane || revolution.is_some();
            let certified = if exact_lane && poles == [false, false] && bounded_ends == [false, false] {
                if chamfer {
                    super::stations::analytic_network::construct_chamfer(edge, first, second, wall_radius, overshoot, ends)
                } else {
                    super::stations::analytic_network::construct(edge, first, second, wall_radius, overshoot, ends)
                }
            } else if poles == [false, false] && bounded_ends == [false, false] {
                revolution.and_then(|axis| if chamfer {
                    super::stations::analytic_arc::construct_chamfer(edge, first, second, axis, wall_radius, overshoot, ends)
                } else {
                    super::stations::analytic_arc::construct(edge, first, second, axis, wall_radius, overshoot, ends)
                })
            } else { None };
            let mut certified_rows = None;
            let mut certified_parameters = None;
            let marched = if let Some(certified) = certified {
                certified_rows = Some(certified.rows);
                certified_parameters = Some(certified.parameters);
                Ok((certified.stations, certified.vertex_indices, StationRefinement::default(),
                    OpenDenseCentres { station_ts: certified.station_ts, ..OpenDenseCentres::default() }))
            } else {
                march_open_stations_core(
                    edge, first, second, &radius_at, overshoot, ends, station_count, poles, bounded_ends,
                    if probes_off { None } else { super::station_refinement_on().then_some(rail_bar) },
                    if wall_check && !probes_off { OPEN_WALL_CENTRES } else { 0 },
                    !probes_off,
                )
            };
            let march_ms = march_timing.stop();
            rung_timing.stop();
            match marched {
                Ok((stations, vertex_indices, refinement, dense)) => {
                    let mut stations = stations;
                    let mut parameters = certified_parameters.take().unwrap_or_else(|| station_parameters(&stations));
                    // A boundary station (`StationRefinement::boundary_inserted`)
                    // whose chord parameter does not increase on a neighbour's
                    // is one the rows fit would refuse ("parameters must be
                    // strictly increasing"): on the F6 ring of the 2026-10-17
                    // report a crossing 1e-14..1e-8 of a spacing from a flush
                    // join's station got plain stations that solved to the
                    // join's own contacts. Exactly those stations are dropped
                    // — the fit's own test, on the fit's own parameters — and
                    // a dropped crossing leaves its break at the neighbour it
                    // coincides with. Nothing else moves (F7 keeps every one
                    // of its 24 crossings).
                    let mut vertex_indices = vertex_indices;
                    let mut boundary_breaks: Vec<usize> = refinement.boundary_breaks.iter().flatten().copied().collect();
                    for &inserted in refinement.boundary_inserted[..refinement.boundary_inserted_count].iter().rev() {
                        if inserted == 0 || inserted + 1 >= stations.len() {
                            continue;
                        }
                        let with_previous = parameters[inserted] <= parameters[inserted - 1];
                        let with_next = parameters[inserted + 1] <= parameters[inserted];
                        if !(with_previous || with_next) {
                            continue;
                        }
                        stations.remove(inserted);
                        parameters = station_parameters(&stations);
                        for vertex in vertex_indices.iter_mut() {
                            if *vertex > inserted {
                                *vertex -= 1;
                            }
                        }
                        for break_index in boundary_breaks.iter_mut() {
                            if *break_index > inserted {
                                *break_index -= 1;
                            } else if *break_index == inserted {
                                *break_index = if with_previous { inserted - 1 } else { inserted };
                            }
                        }
                        super::record_count("count.march.boundary_stations_coincident", 1);
                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                            eprintln!("open march: edge {}'s boundary station {inserted} coincides with its neighbour in the rows' chord parameter; dropped", edge.id);
                        }
                    }
                    boundary_breaks.sort_unstable();
                    boundary_breaks.dedup();
                    let fit_timing = super::BlendTimer::start("timing.rows_fit_ms");
                    let fitted = if let Some(rows) = certified_rows.take() {
                        super::fold::check_rows_loop(&rows, &stations, &parameters, Some(vertex_indices), radius,
                            vec![first.face.id, second.face.id], scale).map(|_| rows)
                    } else if let Some(axis) = revolution {
                        match exact_revolution_rows(&stations, vertex_indices, chamfer, axis, wall_radius.unwrap_or(radius), first, second) {
                            Ok(ExactRevolution { rows, parameters: exact_parameters, stations: exact_stations }) => {
                                parameters = exact_parameters;
                                stations = exact_stations;
                                Ok(rows)
                            }
                            Err(reason) => {
                                // Not one section revolved: the ladder takes
                                // the stripe from its first rung, every
                                // probe on.
                                super::record_count("count.march.exact_revolution_declined", 1);
                                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                                    eprintln!("open march: edge {}'s stations are not an exact revolution ({reason}); the ladder takes it", edge.id);
                                }
                                revolution = None;
                                continue 'rung;
                            }
                        }
                    } else {
                        fit_open_rows_breaking_at(&stations, &parameters, chamfer, Some(vertex_indices), extrusion, &boundary_breaks).and_then(|rows| {
                            // The fitted wall itself must not double back
                            // along a row (`fold::check_rows_loop`).
                            super::fold::check_rows_loop(&rows, &stations, &parameters, Some(vertex_indices), radius, vec![first.face.id, second.face.id], scale)?;
                            Ok(rows)
                        })
                    };
                    let at_vertices = vertex_stations(&parameters, vertex_indices);
                    let fit_ms = fit_timing.stop();
                    if exact_lane && !fitted.as_ref().map_or(false, |rows| rows.exact_extrusion) {
                        // The stations did not come back as translates of one
                        // section: not this lane.  The ladder takes the stripe
                        // from its first rung, with every probe on.
                        super::record_count("count.march.exact_lane_declined", 1);
                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                            eprintln!("open march: edge {}'s stations are not an exact extrusion; the ladder takes it", edge.id);
                        }
                        exact_lane = false;
                        continue 'rung;
                    }
                    if exact_lane {
                        super::record_count("count.march.exact_lane", 1);
                    }
                    if let Ok(rows) = &fitted {
                        super::record_count(
                            if rows.exact_extrusion {
                                "count.rows.exact_extrusion"
                            } else if rows.revolution_axis.is_some() {
                                "count.rows.exact_revolution"
                            } else {
                                "count.rows.fitted"
                            },
                            1,
                        );
                    }
                    if super::timing::enabled() && crate::profile::profile_enabled() {
                        profile_line!(
                            "blend.stripe edge={} stations={station_count} overshoot={overshoot:.3} \
                             marched={} inserted={} march_ms={march_ms:.3} fit_ms={fit_ms:.3} exact={}",
                            edge.id,
                            parameters.len(),
                            refinement.inserted,
                            fitted.as_ref().map_or(false, |rows| rows.exact_extrusion)
                        );
                    }
                    match fitted {
                        Ok(mut rows) => {
                            rows.vertex_stations = at_vertices;
                            let settled_ends: [bool; 2] = std::array::from_fn(|slot| {
                                let vertex = [edge.start_vertex_id, edge.end_vertex_id][slot];
                                let at_start = slot == 0;
                                // A pole's station is the vertex itself.
                                if poles[slot] {
                                    return true;
                                }
                                if let Some((_, _, kind)) =
                                    corners.iter().find(|(id, _, _)| *id == vertex)
                                {
                                    return corner_rails_reach(
                                        &rows,
                                        first,
                                        second,
                                        kind,
                                        corner_station_bar(scale, radius),
                                    );
                                }
                                resolve_free_end(
                                    solid, edge.id, first, second, &rows, vertex, at_start
                                ).is_ok_and(|(end, reached)| {
                                    reached && (!bounded_ends[slot]
                                        || [end.cr_parameter, end.cs_parameter].iter()
                                            .all(|t| *t > RIM_MARGIN && *t < 1.0 - RIM_MARGIN))
                                })
                            });
                            let settled = settled_ends.iter().all(|reached| *reached);
                            if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                                eprintln!(
                                    "rung: edge {} overshoot {overshoot:.3} stations {} ends [{:.6}, {:.6}] marched t [{:.6}, {:.6}] vertex stations {:?} settled {settled_ends:?}",
                                    edge.id,
                                    parameters.len(),
                                    ends[0],
                                    ends[1],
                                    edge.t0 - overshoot * (edge.t1 - edge.t0),
                                    edge.t1 + overshoot * (edge.t1 - edge.t0),
                                    vertex_indices,
                                );
                            }
                            let bounded_reached = (0..2)
                                .all(|slot| !bounded_ends[slot] || settled_ends[slot]);
                            if (chosen.is_none() || settled || (deferred && !deferred_taken)) && bounded_reached
                            {
                                chosen = Some((rows, parameters.clone(), refinement, stations, vertex_indices, dense));
                                deferred_taken |= deferred;
                            }
                            if settled {
                                break;
                            }
                        }
                        // A fold of the rows is terminal, as the march's own
                        // fold verdict is on the open lane: the ladder's next
                        // rung fits the same looping wall.
                        Err(error) if super::fold::is_wall_fold(&error) => return Err(error),
                        Err(error) => {
                            if !(deferred && reaching_error) {
                                last_error = Some(error);
                            }
                            reaching_error |= !deferred;
                        }
                    }
                }
                Err(error) => {
                    if !(deferred && reaching_error) {
                        last_error = Some(error);
                    }
                    reaching_error |= !deferred;
                }
            }
        }
        let Some((rows, parameters, refinement, stations, vertex_indices, dense)) = chosen.take() else {
            // A request rung that cannot be built: the accepted rung stands.
            if accepted.is_some() {
                unmet = Some(crate::BudgetReason::Incoherent);
                break;
            }
            // The final successful coarse station may still precede the
            // end-face crossing. A denser march can reach it without ever
            // evaluating the singular pole beyond it.
            if bounded_ends.iter().any(|bounded| *bounded)
                && station_count < super::stations::MAX_OPEN_STATIONS
            {
                station_count *= 2;
                continue;
            }
            return Err(last_error.unwrap_or_else(|| {
                KernelRefusal::internal(
                    KernelStage::Refine,
                    "network_march",
                    format!("blend network: the march failed on edge {}", edge.id),
                )
            }));
        };
        // The VERTEX window, both rails and the wall over it (the ladder's
        // scope; the shipped windows are read at step 7).
        let window = {
            let (low, high) = (vertex_indices[0].min(vertex_indices[1]), vertex_indices[0].max(vertex_indices[1]));
            shipped_window(&parameters, parameters[low], parameters[high])
        };
        let reading_timing = super::BlendTimer::start("timing.rung_reading_ms");
        let rails_timing = super::BlendTimer::start("timing.rung_reading.rails_ms");
        let rail_reader = super::edge::network_rail_reuse_on().then(|| std::cell::RefCell::new(
            super::edge::RailWindowReader::new(&rows, &parameters, &stations, [&first.face.surface, &second.face.surface])));
        let (rails, rail_samples) = match rail_reader.as_ref() {
            Some(reader) => reader.borrow_mut().read([window, window]),
            None => rails_on_shipped_windows(&rows, &parameters, &stations, [&first.face.surface, &second.face.surface], [window, window]),
        };
        rails_timing.stop();
        let walls_timing = super::BlendTimer::start("timing.rung_reading.walls_ms");
        let walls_why = match (wall_check, window) {
            (true, Some(window)) if rows.revolution_axis.is_some() => exact_revolution_wall_readings(&rows, &parameters, window, wall_radius.unwrap_or(radius)),
            (true, Some(window)) if exact_lane => exact_extrusion_wall_readings(&rows, &parameters, window, wall_radius.unwrap_or(radius)),
            (true, Some(window)) => open_wall_readings_why(&rows, &parameters, &stations, window, &dense, wall_radius.unwrap_or(radius)),
            _ => Vec::new(),
        };
        walls_timing.stop();
        reading_timing.stop();
        let first_unread = walls_why.iter().find_map(|wall| wall.as_ref().err().cloned());
        let walls: Vec<Option<f64>> = walls_why.into_iter().map(|wall| wall.ok()).collect();
        let mut reading = OpenRungReading {
            station_count,
            stations: parameters.len(),
            rails,
            rail_samples,
            walls,
            first_unread,
            refine_exit: refinement.exit,
            inserted: refinement.inserted,
        };
        // A stationary edge's rail that misses is UNREAD (above), before
        // anything reads the verdict, so the trace and the report agree.
        if stationary_end && !(reading.rails_read() && reading.rails <= rail_bar) {
            reading.rails = f64::NAN;
        }
        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
            // Beside it, the lane's former instrument (clamped carrier
            // projection between the vertex stations), for comparison only.
            let clamped = rails_off_carriers(&rows, &parameters, [&first.face.surface, &second.face.surface]);
            eprintln!(
                "open march: edge {} at {station_count} stations (+{} refined, {:?}; {} in all), \
                 rails {:.3e} off their carriers' extension (clamped projection {:?}; bar {rail_bar:.3e}), \
                 wall {:?} (bar {wall_bar:.3e}){}",
                edge.id,
                refinement.inserted,
                refinement.exit,
                parameters.len(),
                reading.rails,
                clamped.map_err(|error| error.message),
                reading.worst_wall(),
                if accepted.is_some() { ", a request rung" } else { "" }
            );
        }
        let accepted_now = accepts(&reading);
        let rung = StripeRung { rows, parameters, stations, vertex_indices, dense, reading, rail_reader };
        if accepted.is_none() {
            if accepted_now {
                let met = !wall_check || meets_model(&rung.reading);
                accepted = Some(rung);
                if met {
                    break;
                }
            } else if station_count < super::stations::MAX_OPEN_STATIONS {
                station_count *= 2;
                continue;
            } else {
                // The ladder is spent and the rung is still not accepted: the
                // wall ships (a body that built before is never turned into a
                // refusal here), UNACCEPTED, and step 7 reports it typed.
                if stationary_end {
                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                        eprintln!(
                            "open march: edge {} is stationary at a vertex; its rails' reading is \
                             reported unread, never as a distance",
                            edge.id
                        );
                    }
                } else {
                    // A refinement that converged left no mid-span miss to name.
                    let worst = if refinement.worst_miss > 0.0 {
                        format!(
                            ", worst mid-span miss {:.2e} at edge parameter {:.6}",
                            refinement.worst_miss, refinement.worst_t
                        )
                    } else {
                        String::new()
                    };
                    super::record_blend_note(format!(
                        "blend: edge {}'s rails stand {:.2e} off their carriers after {} stations \
                         (bar {rail_bar:.1e}; local refinement {:?}, {} stations inserted{worst}); the \
                         wall ships as marched",
                        edge.id,
                        rung.reading.rails,
                        rung.parameters.len(),
                        refinement.exit,
                        refinement.inserted,
                    ));
                }
                unaccepted = Some(rung);
                break;
            }
        } else {
            if !accepted_now {
                unmet = Some(crate::BudgetReason::Rejected);
                break;
            }
            let met = meets_model(&rung.reading);
            accepted = Some(rung);
            if met {
                unmet = None;
                break;
            }
        }
        // Accepted, short of `model`: one more rung if the budget allows.
        if station_count < super::stations::MAX_OPEN_STATIONS {
            station_count *= 2;
        } else {
            unmet = Some(crate::BudgetReason::StationCeiling);
            break;
        }
        }
        let (ladder_accepted, rung) = match (accepted, unaccepted) {
            (Some(rung), _) => (true, rung),
            (None, Some(rung)) => (false, rung),
            (None, None) => {
                return Err(KernelRefusal::internal(KernelStage::Refine, "network_ladder", "blend network: the stripe ladder ended without a rung"));
            }
        };
        let StripeRung { rows, parameters, stations, vertex_indices, dense, reading, rail_reader } = rung;
        super::record_count("count.stations_shipped", parameters.len() as u64);
        super::record_count("count.request_rungs", request_rungs as u64);
        if !ladder_accepted {
            super::record_count("count.stripes_unaccepted", 1);
        }
        stripes.push(Stripe {
            edge,
            first: BlendMate {
                face: first.face,
                coedge: first.coedge,
                loop_index: first.loop_index,
                rho: first.rho,
            },
            second: BlendMate {
                face: second.face,
                coedge: second.coedge,
                loop_index: second.loop_index,
                rho: second.rho,
            },
            rows,
            name: edge_names.get(index).cloned().flatten(),
            poles,
            measure: StripeMeasure {
                parameters,
                stations,
                dense,
                ladder_accepted,
                ladder_reading: reading,
                rail_reader,
                unmet,
                request_rungs,
                stationary_end,
                wall_check,
                exact_lane,
                vertex_indices,
            },
            law: law.clone(),
            end_radius,
        });
    }

    // Row parameter where `stripe`'s rail on `face_id` passes through
    // `point` — the stop station of a corner.  Both rows share one
    // parameterisation, so either rail reports the same station; the caller
    // asks for the rail it is about to trim.
    let station_on = |stripe: &Stripe, face_id: u64, point: Vec3| -> Result<f64, KernelRefusal> {
        let row = if stripe.first.face.id == face_id {
            &stripe.rows.cr
        } else if stripe.second.face.id == face_id {
            &stripe.rows.cs
        } else {
            return Err(KernelRefusal::internal(KernelStage::Refine, "stripe_face", format!(
                "blend network: edge {} does not touch face {face_id}",
                stripe.edge.id
            )));
        };
        rail_station(row, point, corner_station_bar(scale, radius)).map_err(|reason| match reason {
            RailMiss::OffRail(distance) => format!(
                "blend network: edge {}'s contact rail on face {face_id} misses the corner \
                 ball's tangency point by {distance:.3e}",
                stripe.edge.id
            ),
            RailMiss::OffSpan(station) => format!(
                "blend network: the corner station for edge {} lands at {station:.6}, outside \
                 the marched rows — the radius is too large for this edge",
                stripe.edge.id
            ),
            RailMiss::Projection(error) => error,
        }).or_refuse(KernelStage::Refine, "map_err")
    };

    // Free ends and the horn-torus lane both climb `support_crossing`'s
    // tolerance ladder; a crossing that only resolves on a looser rung builds
    // what the tight rung refused, so the network's answer is gated on being a
    // valid solid (see `SpokeCrossings`).
    let mut crossings = SpokeCrossings::default();

    // ---- 5. Turn every corner into per-stripe end plans. ----
    let end_plans_timing = super::BlendTimer::start("timing.end_plans_ms");
    struct PendingPatch {
        center: Vec3,
        outward: bool,
        normals: Vec<Vec3>,
        arcs: Vec<EdgeRecord>,
        name: Option<String>,
        radius: f64,
    }
    /// A sharp edge to trim once the stripes are in, and the connector to
    /// splice next to a stripe's rail on a face.
    struct PendingMiter {
        vertex: u64,
        sharp_edge: u64,
        sharp_parameter: f64,
        sharp_vertex: u64,
        /// (stripe index whose rail the connector continues from, the face
        /// it lies on, connector edge id, its pcurve on that face — stored
        /// from the rail's end to the sharp edge)
        connector: Option<(usize, u64, u64, NurbsCurve)>,
    }
    struct PendingRibbonPatch {
        center: Vec3,
        outward: bool,
        /// (stripe index, the rib stored in the stripe's loop-walk direction,
        /// its pcurve on that blend in the same direction)
        ribs: Vec<(usize, EdgeRecord, NurbsCurve)>,
        name: Option<String>,
    }
    /// Samples along a rib's parameter line for its fit.
    const RIB_SAMPLES: usize = 48;
    let mut end_plans: Vec<[Option<EndPlan>; 2]> =
        (0..stripes.len()).map(|_| [None, None]).collect();
    let mut patches: Vec<PendingPatch> = Vec::new();
    let mut ribbon_patches: Vec<PendingRibbonPatch> = Vec::new();
    let mut pending_miters: Vec<PendingMiter> = Vec::new();
    // Whether a full-width miter consumed a sharp edge whole (see
    // `collapse_full_width`).
    let mut consumed_sharp_edge = false;
    // It is named here, before any corner is closed, instead of surfacing
    // as the generic `stripe_pinch` of step 7. A full-width channel, whose
    // two stops are one point within the band, is not crossed and collapses
    // as before.
    //
    // On the switch (`crossed_rails_on`) the stripe is CONVERTED
    // (`corner/crossed.rs`): both neighbours end at their rail/rail point
    // `M` on the shared face (the last ball that fits between their side
    // faces), the stripe keeps only its side-face rail, each neighbour gets
    // a rib from `M` down to that rail's end on the sharp edge (the hood's
    // level set on the neighbour's blend), and the stripe's face becomes the
    // hood: its section stretched to the quarter ellipse through `M`.  The
    // two corners are then one patch and the loop below skips them.
    struct CrossedStripe {
        index: usize,
        shared: u64,
        u_start: f64,
        u_finish: f64,
        strip: f64,
        p_start: Vec3,
        p_finish: Vec3,
    }
    let mut crossed: Vec<CrossedStripe> = Vec::new();
    for (index, stripe) in stripes.iter().enumerate() {
        let corner_at = |vertex: u64| -> Option<(u64, &Corner)> {
            corners.iter().find(|(id, _, _)| *id == vertex).and_then(|(_, _, kind)| match kind {
                VertexKind::Miter { corner, shared, .. } => Some((shared.id, corner)),
                _ => None,
            })
        };
        let (Some((shared_start, corner_start)), Some((shared_finish, corner_finish))) =
            (corner_at(stripe.edge.start_vertex_id), corner_at(stripe.edge.end_vertex_id))
        else {
            continue;
        };
        if shared_start != shared_finish || stripe.edge.start_vertex_id == stripe.edge.end_vertex_id {
            continue;
        }
        let shared = shared_start;
        let (p_start, _) = corner_start.tangency_on(shared)?;
        let (p_finish, _) = corner_finish.tangency_on(shared)?;
        let (Ok(u_start), Ok(u_finish)) =
            (station_on(stripe, shared, p_start), station_on(stripe, shared, p_finish))
        else {
            // A stop the rail does not reach is the corner's own refusal, below.
            continue;
        };
        let strip = p_finish.sub(p_start).length();
        let chord = vertex_point_of(solid, stripe.edge.end_vertex_id)?
            .sub(vertex_point_of(solid, stripe.edge.start_vertex_id)?);
        let band = consumed_band(solid);
        if strip > band && (u_finish < u_start || p_finish.sub(p_start).dot(chord) < 0.0) {
            super::record_count("count.crossed_rails", 1);
            crossed.push(CrossedStripe { index, shared, u_start, u_finish, strip, p_start, p_finish });
        }
    }
    let refuse_crossed = |crossing: &CrossedStripe, why: &str| -> KernelRefusal {
        KernelRefusal::unsupported(KernelStage::Refine, "crossed_rails", format!(
            "blend network: edge {}'s rails cross — the corner stops at its two ends run \
             {:.3e} past each other on face {} (stations {:.6} and {:.6}), so the rail between \
             them points against the edge (C4); the radius exceeds the face between the two \
             corners, and {why}",
            stripes[crossing.index].edge.id, crossing.strip, crossing.shared, crossing.u_start, crossing.u_finish
        ))
    };
    if let Some(first) = crossed.first().filter(|_| !super::crossed_rails_on()) {
        return Err(refuse_crossed(first, "converting the stripe into a rib between the merged corners is not built here"));
    }
    let mut handled_corners: Vec<u64> = Vec::new();
    let mut converted_rows: Vec<(usize, FittedRows)> = Vec::new();
    for crossing in &crossed {
        let r_index = crossing.index;
        let r_stripe = &stripes[r_index];
        let shared_id = crossing.shared;
        if chamfer {
            return Err(refuse_crossed(crossing, "the hood over the merged corners is a fillet's; a chamfer's is not built"));
        }
        let corner_parts = |vertex: u64| -> Result<(&Corner, &FaceRecord, &EdgeRecord, &Vec<usize>), KernelRefusal> {
            corners
                .iter()
                .find(|(id, _, _)| *id == vertex)
                .and_then(|(_, indices, kind)| match kind {
                    VertexKind::Miter { corner, shared, sharp } => Some((corner, *shared, *sharp, indices)),
                    _ => None,
                })
                .ok_or_else(|| KernelRefusal::internal(KernelStage::Refine, "crossed_corner", "blend network: a crossed stripe's corner vanished"))
        };
        let (v_start, v_finish) = (r_stripe.edge.start_vertex_id, r_stripe.edge.end_vertex_id);
        let (corner_start, shared_face, sharp_start, indices_start) = corner_parts(v_start)?;
        let (corner_finish, _, sharp_finish, indices_finish) = corner_parts(v_finish)?;
        if handled_corners.contains(&v_start) || handled_corners.contains(&v_finish) {
            return Err(refuse_crossed(crossing, "two crossed stripes share a corner, which the conversion does not merge"));
        }
        let other = |indices: &Vec<usize>| indices.iter().copied().find(|&index| index != r_index);
        let (Some(f_index), Some(b_index)) = (other(indices_start), other(indices_finish)) else {
            return Err(refuse_crossed(crossing, "a corner has no second stripe"));
        };
        if f_index == b_index {
            return Err(refuse_crossed(crossing, "both corners are closed by one neighbouring stripe (a two-edge loop), which the conversion does not merge"));
        }
        if !(corner_start.outward && corner_finish.outward) {
            return Err(refuse_crossed(crossing, "the corners are concave; the hood over the merged corners is built at convex corners only"));
        }
        let radius_here = corner_start.radius;
        let agree = |value: f64| (value - radius_here).abs() <= 1e-9 * (1.0 + radius_here);
        let end_radius_at = |index: usize, vertex: u64| -> f64 {
            let stripe = &stripes[index];
            stripe.end_radius[usize::from(!stripe.at_start(vertex))]
        };
        if !(agree(corner_finish.radius)
            && agree(end_radius_at(r_index, v_start))
            && agree(end_radius_at(r_index, v_finish))
            && agree(end_radius_at(f_index, v_start))
            && agree(end_radius_at(b_index, v_finish))
            && stripes[r_index].law.constant().is_some())
        {
            return Err(refuse_crossed(crossing, "the stripes meet at different radii; the hood over the merged corners is built at one constant radius"));
        }
        let plane_outward = |face: &FaceRecord| -> Option<Vec3> {
            match face.surface.analytic() {
                Some(crate::AnalyticSurface::Plane { u_dir, v_dir, .. }) => {
                    let normal = u_dir.cross(*v_dir).normalized().ok()?;
                    Some(if face.same_sense { normal } else { normal.scale(-1.0) })
                }
                _ => None,
            }
        };
        let top_is_first_r = r_stripe.first.face.id == shared_id;
        let r_side_face = if top_is_first_r { r_stripe.second.face } else { r_stripe.first.face };
        let (Some(n_top), Some(n_side)) = (plane_outward(shared_face), plane_outward(r_side_face)) else {
            return Err(refuse_crossed(crossing, "the hood over the merged corners needs a planar shared face and a planar side face"));
        };
        // M: where the two neighbours' rails on the shared face cross.
        let rail_rail_of = |index: usize, vertex: u64| -> RailRailStripe<'_> {
            let stripe = &stripes[index];
            let end_radius = end_radius_at(index, vertex);
            let (on_shared, on_side) = if stripe.first.face.id == shared_id {
                (&stripe.first, &stripe.second)
            } else {
                (&stripe.second, &stripe.first)
            };
            RailRailStripe {
                side: on_side.face,
                rho_shared: on_shared.rho.signum() * end_radius,
                rho_side: on_side.rho.signum() * end_radius,
            }
        };
        let described = [rail_rail_of(f_index, v_start), rail_rail_of(b_index, v_finish)];
        let seed = crossing.p_start.add(crossing.p_finish).scale(0.5);
        let m = solve_rail_rail_point(shared_face, [&described[0], &described[1]], seed, scale).map_err(|error| {
            refuse_crossed(crossing, &format!("the two neighbouring stripes' rails on the shared face do not cross ({})", error.message))
        })?;
        let origin = vertex_point_of(solid, v_start)?;
        let a = -m.point.sub(origin).dot(n_side);
        if !(a > radius_here * (1.0 + 1e-9)) {
            return Err(refuse_crossed(crossing, &format!(
                "the neighbours' rail/rail point stands {a:.6} inside the side face, not beyond the stripe's own rail at {radius_here:.6}"
            )));
        }
        let frame = HoodFrame { n_top, n_side, origin, a, r: radius_here };
        let hood = hood_rows(&r_stripe.rows, top_is_first_r, &frame)?;
        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
            eprintln!(
                "network crossed stripe {}: rail/rail point {:?} (residual {:.3e}), hood semi-axes {a:.6} by {radius_here:.6}",
                r_stripe.edge.id, m.point, m.residual
            );
        }
        let m_vertex = take_id();
        result.vertices.push(VertexRecord { id: m_vertex, point: m.point });
        // The two corners' shared-face vertices (step 3's balls' tangency
        // points) are not on the body: nothing ends there.
        for corner in [corner_start, corner_finish] {
            if let Some((_, _, id)) = corner.tangency.iter().find(|(face_id, _, _)| *face_id == shared_id) {
                if *id != 0 {
                    result.vertices.retain(|vertex| vertex.id != *id);
                }
            }
        }
        let fit_tolerance = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
        let band = consumed_band(solid);
        let hood_top_line = if top_is_first_r { &hood.cr } else { &hood.cs };
        let r_side_row = if top_is_first_r { &r_stripe.rows.cs } else { &r_stripe.rows.cr };
        for (vertex_id, sharp, n_index) in [(v_start, sharp_start, f_index), (v_finish, sharp_finish, b_index)] {
            let n_stripe = &stripes[n_index];
            let n_at_start = n_stripe.at_start(vertex_id);
            let n_top_first = n_stripe.first.face.id == shared_id;
            let (n_side_row, z_top, z_side) = if n_top_first {
                (&n_stripe.rows.cs, 0.0, 1.0)
            } else {
                (&n_stripe.rows.cr, 1.0, 0.0)
            };
            let u_top_n = station_on(n_stripe, shared_id, m.point)?;
            let (u_side_n, _, q_point_n, escalated_n) = support_crossing(solid, n_side_row, sharp, n_at_start).map_err(|error| {
                refuse_crossed(crossing, &format!("edge {}'s side rail does not reach the sharp edge at vertex {vertex_id} ({})", n_stripe.edge.id, error.message))
            })?;
            crossings.note(escalated_n);
            let r_at_start = r_stripe.at_start(vertex_id);
            let (u_side_r, t_sharp, q_point, escalated_r) = support_crossing(solid, r_side_row, sharp, r_at_start).map_err(|error| {
                refuse_crossed(crossing, &format!("the stripe's side rail does not reach the sharp edge at vertex {vertex_id} ({})", error.message))
            })?;
            crossings.note(escalated_r);
            if q_point_n.sub(q_point).length() > band {
                return Err(refuse_crossed(crossing, &format!(
                    "the two side rails meet the sharp edge at vertex {vertex_id} {:.3e} apart",
                    q_point_n.sub(q_point).length()
                )));
            }
            // The rail's end on the sharp edge: the far vertex itself when
            // the side faces are consumed down to it (full height).
            let far_vertex = if sharp.start_vertex_id == vertex_id { sharp.end_vertex_id } else { sharp.start_vertex_id };
            let far_point = vertex_point_of(solid, far_vertex)?;
            let q_vertex = if q_point.sub(far_point).length() <= band {
                far_vertex
            } else {
                let id = take_id();
                result.vertices.push(VertexRecord { id, point: q_point });
                id
            };
            // The rib on the neighbour: the hood's level set on its blend,
            // from M down to Q, fitted on both surfaces.
            let marched = march_rib(
                &n_stripe.rows.surface,
                &hood.surface,
                &frame,
                m.point,
                u_top_n,
                z_top,
                q_point,
                u_side_n,
                z_side,
                n_stripe.edge.id,
            )?;
            let n_surface = &n_stripe.rows.surface;
            let hood_surface = &hood.surface;
            let (rib_curve, rib_on_n, rib_on_hood) = fit_marched(
                &marched,
                "merged-corner rib",
                &|point: Vec3| Ok(off_surface(n_surface, point)?.max(off_surface(hood_surface, point)?)),
                fit_tolerance,
            )?;
            let domain = rib_curve.domain().or_refuse(KernelStage::Refine, "domain")?;
            let rib_id = take_id();
            result.edges.push(EdgeRecord {
                id: rib_id,
                curve: rib_curve,
                t0: domain[0],
                t1: domain[1],
                start_vertex_id: m_vertex,
                end_vertex_id: q_vertex,
                degenerate: false,
                name: None,
            });
            // The plans: the rib is stored from M (the shared rim) to Q
            // (the far rim); each stripe's loop walks it in its own sense.
            let plan = |top_first: bool, walk_p_to_far: bool, u_top: f64, u_side: f64, pcurve: &NurbsCurve| -> Result<EndPlan, KernelRefusal> {
                let (cr_parameter, cs_parameter, first_vertex, second_vertex) = if top_first {
                    (u_top, u_side, m_vertex, q_vertex)
                } else {
                    (u_side, u_top, q_vertex, m_vertex)
                };
                let edges = if walk_p_to_far {
                    vec![(rib_id, true, pcurve.clone())]
                } else {
                    vec![(rib_id, false, pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?)]
                };
                Ok(EndPlan::Miter(MiterEnd { cr_parameter, cs_parameter, first_vertex, second_vertex, edges }))
            };
            let walk_n = n_stripe.walk_first_to_second(n_at_start) == n_top_first;
            end_plans[n_index][usize::from(!n_at_start)] = Some(plan(n_top_first, walk_n, u_top_n, u_side_n, &rib_on_n)?);
            let u_top_r = crate::project_point_to_curve(hood_top_line, m.point)
                .or_refuse(KernelStage::Refine, "project_point_to_curve")?
                .u;
            let walk_r = r_stripe.walk_first_to_second(r_at_start) == top_is_first_r;
            end_plans[r_index][usize::from(!r_at_start)] = Some(plan(top_is_first_r, walk_r, u_top_r, u_side_r, &rib_on_hood)?);
            pending_miters.push(PendingMiter {
                vertex: vertex_id,
                sharp_edge: sharp.id,
                sharp_parameter: t_sharp,
                sharp_vertex: q_vertex,
                connector: None,
            });
            handled_corners.push(vertex_id);
        }
        converted_rows.push((r_index, hood));
        super::record_count("count.crossed_rails_converted", 1);
    }
    // BREP_PROFILE split of the end plans, one measure per corner kind's loop.
    let stars_miters_timing = super::BlendTimer::start("timing.end_plans.stars_miters_ms");
    for (vertex_id, stripe_indices, kind) in &corners {
        if handled_corners.contains(vertex_id) {
            continue;
        }
        match kind {
            // Planned below, once every star and miter is in.
            VertexKind::Reentrant { .. } | VertexKind::Flush { .. } | VertexKind::MixedStar(_) => continue,
            VertexKind::Star { corner } => {
                let radius = corner.radius;
                let mut arcs: Vec<EdgeRecord> = Vec::with_capacity(stripe_indices.len());
                let mut normals: Vec<Vec3> = Vec::with_capacity(stripe_indices.len());
                for (_, point, _) in &corner.tangency {
                    normals.push(point.sub(corner.center).normalized().or_refuse(KernelStage::Refine, "normalized")?);
                }
                for &index in stripe_indices {
                    let stripe = &stripes[index];
                    let at_start = stripe.at_start(*vertex_id);
                    let (first_point, first_vertex) = corner.tangency_on(stripe.first.face.id)?;
                    let (second_point, second_vertex) =
                        corner.tangency_on(stripe.second.face.id)?;
                    let station_first = station_on(stripe, stripe.first.face.id, first_point)?;
                    let station_second =
                        station_on(stripe, stripe.second.face.id, second_point)?;
                    if (station_first - station_second).abs() > 1e-3 {
                        return Err(KernelRefusal::internal(KernelStage::Refine, "stripe_vertex_stations", format!(
                            "blend network: edge {} meets vertex {vertex_id} at inconsistent \
                             stations ({station_first:.6} on one support, {station_second:.6} \
                             on the other)",
                            stripe.edge.id
                        )));
                    }
                    let station = (station_first + station_second) * 0.5;
                    // The cross-section at the stop station is an arc of the
                    // corner sphere from one tangency point to the other.  It
                    // is stored in the direction the blend face's loop walks
                    // it, so the blend uses it forward and the patch, which
                    // always takes its boundary the other way round, reversed.
                    let walk_first_to_second = stripe.walk_first_to_second(at_start);
                    let (from, to, from_vertex, to_vertex) = if walk_first_to_second {
                        (first_point, second_point, first_vertex, second_vertex)
                    } else {
                        (second_point, first_point, second_vertex, first_vertex)
                    };
                    // §6.11: the chamfer's section at the stop station is the
                    // CHORD between the same two tangency points the fillet
                    // arcs between — the iso-parameter line of a ruled bevel.
                    let arc = if chamfer {
                        crate::make_line(from, to).or_refuse(KernelStage::Refine, "make_line")?
                    } else {
                        corner_section_arc(corner.center, radius, from, to)?
                    };
                    let arc_domain = arc.domain().or_refuse(KernelStage::Refine, "domain")?;
                    let arc_edge_id = take_id();
                    let record = EdgeRecord {
                        id: arc_edge_id,
                        curve: arc,
                        t0: arc_domain[0],
                        t1: arc_domain[1],
                        start_vertex_id: from_vertex,
                        end_vertex_id: to_vertex,
                        degenerate: false,
                        name: None,
                    };
                    result.edges.push(record.clone());
                    arcs.push(record);
                    // The blend surface's own parameter space: z runs 0 -> 1
                    // from the first support row to the second, so the
                    // cross-section is the iso-parameter line at the stop
                    // station, walked in the same direction as the arc.
                    let arc_blend_pcurve = if walk_first_to_second {
                        crate::sweep_topology::parameter_line(station, 0.0, station, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?
                    } else {
                        crate::sweep_topology::parameter_line(station, 1.0, station, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?
                    };
                    end_plans[index][usize::from(!at_start)] = Some(EndPlan::Corner(CornerEnd {
                        cr_parameter: station,
                        cs_parameter: station,
                        first_vertex,
                        second_vertex,
                        arc_edge_id,
                        arc_blend_pcurve,
                    }));
                }
                patches.push(PendingPatch {
                    center: corner.center,
                    outward: corner.outward,
                    normals,
                    arcs,
                    name: corner_name(stripe_indices),
                    radius,
                });
            }
            VertexKind::RibbonStar { corner } => {
                // The stripe's end is a miter-shaped plan (two different
                // stop stations, one closing edge); the patch is built in
                // step 7 from the ribs.
                let fit_tolerance = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
                let mut ribs: Vec<(usize, EdgeRecord, NurbsCurve)> = Vec::with_capacity(stripe_indices.len());
                for &index in stripe_indices {
                    let stripe = &stripes[index];
                    let at_start = stripe.at_start(*vertex_id);
                    let (first_point, first_vertex) = corner.tangency_on(stripe.first.face.id)?;
                    let (second_point, second_vertex) = corner.tangency_on(stripe.second.face.id)?;
                    let u_first = station_on(stripe, stripe.first.face.id, first_point)?;
                    let u_second = station_on(stripe, stripe.second.face.id, second_point)?;
                    let walk_first_to_second = stripe.walk_first_to_second(at_start);
                    // The rib leaves each rail/rail point along the OTHER
                    // stripe's rail on that face, toward the vertex.  On a
                    // cylindrical blend that direction is the ruling, along
                    // which the blend's normal does not turn, so the Coons
                    // patch's two ribbons at that corner ask for the same
                    // twist (the vertex-enclosure obstruction vanishes:
                    // `ribbon_star.rs`); the rib and the crossing rail then
                    // continue each other through the point.  The direction
                    // is pulled back into the blend's (u, z) space by least
                    // squares on the surface's first derivatives.
                    let vertex_point = vertex_point_of(solid, *vertex_id)?;
                    let leave_along = |face_id: u64, at: Vec3, uv: [f64; 2]| -> Result<[f64; 2], KernelRefusal> {
                        let other = stripe_indices
                            .iter()
                            .copied()
                            .find(|&other| other != index && (stripes[other].first.face.id == face_id || stripes[other].second.face.id == face_id))
                            .ok_or(KernelRefusal::internal(KernelStage::Refine, "star_rail_pair", format!(
                                "blend network: no second stripe on face {face_id} at vertex {vertex_id}"
                            )))?;
                        let other_stripe = &stripes[other];
                        let rail = if other_stripe.first.face.id == face_id { &other_stripe.rows.cr } else { &other_stripe.rows.cs };
                        let u_other = station_on(other_stripe, face_id, at)?;
                        let derivatives = rail.derivatives(u_other, 1).or_refuse(KernelStage::Refine, "derivatives")?;
                        let mut direction = derivatives[1].normalized().or_refuse(KernelStage::Refine, "normalized")?;
                        if direction.dot(vertex_point.sub(at)) < 0.0 {
                            direction = direction.scale(-1.0);
                        }
                        let surface_derivatives = stripe.rows.surface.derivatives(uv[0], uv[1], 1).or_refuse(KernelStage::Refine, "derivatives")?;
                        let (s_u, s_z) = (surface_derivatives[1][0], surface_derivatives[0][1]);
                        // Least squares: [s_u s_z] [du dz]ᵀ ≈ direction.
                        let (a, b, c) = (s_u.dot(s_u), s_u.dot(s_z), s_z.dot(s_z));
                        let (r0, r1) = (s_u.dot(direction), s_z.dot(direction));
                        let det = a * c - b * b;
                        if !(det.abs() > 1e-18) {
                            return Err(KernelRefusal::ill_posed(KernelStage::Refine, "rib_direction", format!(
                                "blend network: the blend of edge {} is singular at its rail/rail point on face {face_id}",
                                stripe.edge.id
                            )));
                        }
                        Ok([(c * r0 - b * r1) / det, (a * r1 - b * r0) / det])
                    };
                    let (from, to) = if walk_first_to_second {
                        (([u_first, 0.0], first_point, first_vertex), ([u_second, 1.0], second_point, second_vertex))
                    } else {
                        (([u_second, 1.0], second_point, second_vertex), ([u_first, 0.0], first_point, first_vertex))
                    };
                    let (face_from, face_to) = if walk_first_to_second {
                        (stripe.first.face.id, stripe.second.face.id)
                    } else {
                        (stripe.second.face.id, stripe.first.face.id)
                    };
                    let d_from = leave_along(face_from, from.1, from.0)?;
                    let d_to = leave_along(face_to, to.1, to.0)?;
                    // Into the strip from z = 0, out of it toward z = 1: the
                    // Hermite's end tangent at `to` points along the rib's
                    // travel, i.e. AGAINST the direction that leaves `to`.
                    let chord = ((to.0[0] - from.0[0]).powi(2) + (to.0[1] - from.0[1]).powi(2)).sqrt();
                    let unit = |d: [f64; 2]| -> Result<[f64; 2], KernelRefusal> {
                        let length = (d[0] * d[0] + d[1] * d[1]).sqrt();
                        if !(length > 0.0) {
                            return Err(KernelRefusal::ill_posed(KernelStage::Refine, "rib_direction", "blend network: a rib's leaving direction is zero"));
                        }
                        Ok([d[0] / length * chord, d[1] / length * chord])
                    };
                    let (t_from, t_to) = (unit(d_from)?, unit([-d_to[0], -d_to[1]])?);
                    if !(t_from[1] * (to.0[1] - from.0[1]) > 0.0 && t_to[1] * (to.0[1] - from.0[1]) > 0.0) {
                        return Err(KernelRefusal::unsupported(KernelStage::Refine, "n_sided_corner", format!(
                            "blend network: edge {}'s rib would leave its rail/rail point away from its strip \
                             (directions {t_from:?} and {t_to:?} in (u, z)); the ribbon fill is not built here",
                            stripe.edge.id
                        )));
                    }
                    let hermite = |fraction: f64| -> [f64; 2] {
                        let (s2, s3) = (fraction * fraction, fraction * fraction * fraction);
                        let (h00, h10, h01, h11) = (2.0 * s3 - 3.0 * s2 + 1.0, s3 - 2.0 * s2 + fraction, -2.0 * s3 + 3.0 * s2, s3 - s2);
                        [
                            h00 * from.0[0] + h10 * t_from[0] + h01 * to.0[0] + h11 * t_to[0],
                            h00 * from.0[1] + h10 * t_from[1] + h01 * to.0[1] + h11 * t_to[1],
                        ]
                    };
                    let mut marched = MarchedCurve { points: Vec::new(), uv_first: Vec::new(), uv_second: Vec::new() };
                    for sample in 0..=RIB_SAMPLES {
                        let fraction = sample as f64 / RIB_SAMPLES as f64;
                        let uv = hermite(fraction);
                        let point = if sample == 0 {
                            from.1
                        } else if sample == RIB_SAMPLES {
                            to.1
                        } else {
                            stripe.rows.surface.evaluate_extended(uv[0], uv[1]).or_refuse(KernelStage::Refine, "evaluate_extended")?
                        };
                        marched.points.push(point);
                        marched.uv_first.push(uv);
                        marched.uv_second.push(uv);
                    }
                    let surface = &stripe.rows.surface;
                    let (rib_curve, rib_pcurve, _) = fit_marched(
                        &marched,
                        "rib",
                        &|point: Vec3| off_surface(surface, point),
                        fit_tolerance,
                    )?;
                    let domain = rib_curve.domain().or_refuse(KernelStage::Refine, "domain")?;
                    let rib_id = take_id();
                    let record = EdgeRecord {
                        id: rib_id,
                        curve: rib_curve,
                        t0: domain[0],
                        t1: domain[1],
                        start_vertex_id: from.2,
                        end_vertex_id: to.2,
                        degenerate: false,
                        name: None,
                    };
                    result.edges.push(record.clone());
                    end_plans[index][usize::from(!at_start)] = Some(EndPlan::Miter(MiterEnd {
                        cr_parameter: u_first,
                        cs_parameter: u_second,
                        first_vertex,
                        second_vertex,
                        edges: vec![(rib_id, true, rib_pcurve.clone())],
                    }));
                    ribs.push((index, record, rib_pcurve));
                }
                ribbon_patches.push(PendingRibbonPatch {
                    center: corner.center,
                    outward: corner.outward,
                    ribs,
                    name: corner_name(stripe_indices),
                });
            }
            VertexKind::Miter {
                corner,
                shared,
                sharp,
            } => {
                let radius = corner.radius;
                let [mut ia, mut ib] = [stripe_indices[0], stripe_indices[1]];
                // That stripe's sections — planes normal to its own edge,
                // which lies in the side face — cross the rail transversally,
                // so the exit bisects cleanly; on the LARGER stripe's domain
                // the same exit is a tangency of the level (the box fixture:
                // its sections are parallel to the side face, and the level's
                // minimum just touches zero there) and the bisection lost the
                // seam by name (`miter_exit_seam`). So the smaller stripe
                // marches the seam; equal radii keep the selection's order.
                let end_radius_at = |index: usize| -> f64 {
                    let stripe = &stripes[index];
                    stripe.end_radius[usize::from(!stripe.at_start(*vertex_id))]
                };
                if end_radius_at(ib) < end_radius_at(ia) * (1.0 - 1e-9) {
                    std::mem::swap(&mut ia, &mut ib);
                }
                let (p_point, p_vertex) = corner.tangency_on(shared.id)?;
                let describe = |index: usize| -> Result<MiterStripe, KernelRefusal> {
                    let stripe = &stripes[index];
                    let shared_first = stripe.first.face.id == shared.id;
                    let other_face = if shared_first {
                        stripe.second.face
                    } else {
                        stripe.first.face
                    };
                    let at_start = stripe.at_start(*vertex_id);
                    Ok(MiterStripe {
                        rows: &stripe.rows,
                        shared_first,
                        at_start,
                        u_ball: station_on(stripe, shared.id, p_point)?,
                        other_face,
                        radius: stripe.end_radius[usize::from(!at_start)],
                    })
                };
                let mut described = [describe(ia)?, describe(ib)?];
                let fit_tolerance = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
                // At a creased seam whose two side rails reach the seam at
                // DIFFERENT points the closure must be the asymmetric one,
                // and their separation is second order in the crease (1.5e-4
                // on the tilted fixture at r = 1), far inside the miter's
                // 1e-6 symmetric bar: read at that bar, the follower's rail
                // was pulled onto the leader's seam point (P = S) and the
                // body read 1.1e-4 off its oracle.  Where the rails reach the
                // seam at one point (a seam in the shared face's normal plane:
                // P = S exactly) nothing changes.
                let creased_bar = if creased_vertices.contains(vertex_id) {
                    let rail_on_seam = |index: usize| -> Result<Vec3, KernelRefusal> {
                        let stripe = &stripes[index];
                        let side_row = if stripe.first.face.id == shared.id { &stripe.rows.cs } else { &stripe.rows.cr };
                        Ok(support_crossing(solid, side_row, sharp, stripe.at_start(*vertex_id))?.2)
                    };
                    let apart = rail_on_seam(ia)?.sub(rail_on_seam(ib)?).length();
                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                        eprintln!("creased seam at vertex {vertex_id}: the side rails reach the seam {apart:.3e} apart");
                    }
                    (apart > 1e-9 * (1.0 + scale)).then(|| 1e-10 * (1.0 + radius))
                } else {
                    None
                };
                let _miter_timing = super::BlendTimer::start("timing.end_plans.miter_ms");
                let solve = |described: &[MiterStripe; 2]| {
                    solve_miter(
                        [&described[0], &described[1]],
                        radius,
                        chamfer,
                        sharp,
                        scale,
                        fit_tolerance,
                        consumed_band(solid),
                        creased_bar,
                    )
                };
                // A seam that FOLDS in the leader's sections where it meets
                // the follower's far rail (`miter_seam_fold`) is marched on
                // the follower's domain instead, where that rail is the
                // leader's own and its crossing is transversal.
                let closure = match solve(&described) {
                    Err(refusal) if super::miter::is_miter_seam_fold(&refusal) => {
                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                            eprintln!("miter at vertex {vertex_id}: {refusal}; marching the seam on the other stripe");
                        }
                        super::record_count("count.miter.fold_swapped", 1);
                        std::mem::swap(&mut ia, &mut ib);
                        described = [describe(ia)?, describe(ib)?];
                        solve(&described)?
                    }
                    other => other?,
                };
                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                    let seam = match &closure {
                        MiterClosure::Symmetric { seam, .. } => seam,
                        MiterClosure::Asymmetric { seam, .. } => seam,
                    };
                    // The seam must ride BOTH walls: for a fillet that is the
                    // two canals, for a chamfer the two bevels — the same two
                    // surfaces their levels are written against.
                    let mut worst = 0.0f64;
                    for point in &seam.points {
                        for index in [ia, ib] {
                            let rows = &stripes[index].rows;
                            let own_radius = described[usize::from(index == ib)].radius;
                            let d = if chamfer {
                                crate::project_point_to_surface(&rows.surface, *point)
                                    .map(|p| p.distance)
                                    .unwrap_or(f64::NAN)
                            } else {
                                rows.center
                                    .as_ref()
                                    .and_then(|center| {
                                        crate::project_point_to_curve(center, *point).ok()
                                    })
                                    .map(|p| (p.distance - own_radius).abs())
                                    .unwrap_or(f64::NAN)
                            };
                            worst = worst.max(d);
                        }
                    }
                    let what = if chamfer { "off both bevels" } else { "|dist-to-centre - r|" };
                    eprintln!(
                        "network seam at vertex {vertex_id}: {} samples, worst {what} {worst:.3e}",
                        seam.points.len()
                    );
                }

                // Commit the vertices and edges the closure names, then hand
                // each stripe its end plan in its loop's walk order.
                let commit_curve = |result: &mut BrepSolid,
                                    take_id: &mut dyn FnMut() -> u64,
                                    curve: NurbsCurve,
                                    from: u64,
                                    to: u64|
                 -> Result<u64, KernelRefusal> {
                    let domain = curve.domain().or_refuse(KernelStage::Refine, "domain")?;
                    let id = take_id();
                    result.edges.push(EdgeRecord {
                        id,
                        curve,
                        t0: domain[0],
                        t1: domain[1],
                        start_vertex_id: from,
                        end_vertex_id: to,
                        degenerate: false,
                        name: None,
                    });
                    Ok(id)
                };
                let commit_vertex = |result: &mut BrepSolid,
                                     take_id: &mut dyn FnMut() -> u64,
                                     point: Vec3|
                 -> u64 {
                    let id = take_id();
                    result.vertices.push(VertexRecord { id, point });
                    id
                };
                // A plan for stripe `index` whose end is closed by `edges`
                // listed from P (the shared rim) to the far rim, with pcurves
                // on this stripe's blend in that same direction.
                let plan_for = |index: usize,
                                far_station: f64,
                                far_vertex: u64,
                                edges: Vec<(u64, NurbsCurve)>|
                 -> Result<EndPlan, KernelRefusal> {
                    let stripe = &stripes[index];
                    let at_start = stripe.at_start(*vertex_id);
                    let shared_first = stripe.first.face.id == shared.id;
                    let u_ball = described[usize::from(index == ib)].u_ball;
                    let (cr_parameter, cs_parameter, first_vertex, second_vertex) =
                        if shared_first {
                            (u_ball, far_station, p_vertex, far_vertex)
                        } else {
                            (far_station, u_ball, far_vertex, p_vertex)
                        };
                    // The walk runs P -> far exactly when the loop walks
                    // first -> second and P is on the first side, or the
                    // reverse of both.
                    let walk_p_to_far = stripe.walk_first_to_second(at_start) == shared_first;
                    let slot = if walk_p_to_far {
                        edges
                            .into_iter()
                            .map(|(id, pcurve)| (id, true, pcurve))
                            .collect()
                    } else {
                        edges
                            .into_iter()
                            .rev()
                            .map(|(id, pcurve)| Ok((id, false, pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?)))
                            .collect::<Result<Vec<_>, KernelRefusal>>()?
                    };
                    Ok(EndPlan::Miter(MiterEnd {
                        cr_parameter,
                        cs_parameter,
                        first_vertex,
                        second_vertex,
                        edges: slot,
                    }))
                };
                let slot_of = |index: usize| usize::from(!stripes[index].at_start(*vertex_id));
                // Where the closure lands on the sharp edge.  At full width it
                // lands on the sharp edge's FAR vertex (the side faces are
                // consumed down to it), and that vertex is the point, not a
                // fresh one beside it: the sharp edge is then consumed whole
                // rather than trimmed to nothing (`consume_sharp_edge`).
                let far_vertex = if sharp.start_vertex_id == *vertex_id {
                    sharp.end_vertex_id
                } else {
                    sharp.start_vertex_id
                };
                let far_point = vertex_point_of(solid, far_vertex)?;
                let band = consumed_band(solid);
                let commit_on_sharp =
                    |result: &mut BrepSolid, take_id: &mut dyn FnMut() -> u64, point: Vec3| {
                        if point.sub(far_point).length() <= band {
                            far_vertex
                        } else {
                            commit_vertex(result, take_id, point)
                        }
                    };
                match closure {
                    MiterClosure::Symmetric {
                        seam_fit: (curve, on_a, on_b),
                        exit,
                        sharp_parameter,
                        ..
                    } => {
                        let q_point = sharp.curve.evaluate(sharp_parameter).or_refuse(KernelStage::Refine, "evaluate")?;
                        let q_vertex = commit_on_sharp(&mut result, &mut take_id, q_point);
                        let seam_id =
                            commit_curve(&mut result, &mut take_id, curve, p_vertex, q_vertex)?;
                        end_plans[ia][slot_of(ia)] =
                            Some(plan_for(ia, exit[0], q_vertex, vec![(seam_id, on_a)])?);
                        end_plans[ib][slot_of(ib)] =
                            Some(plan_for(ib, exit[1], q_vertex, vec![(seam_id, on_b)])?);
                        pending_miters.push(PendingMiter {
                            vertex: *vertex_id,
                            sharp_edge: sharp.id,
                            sharp_parameter,
                            sharp_vertex: q_vertex,
                            connector: None,
                        });
                    }
                    MiterClosure::Asymmetric {
                        seam,
                        seam_fit: (seam_curve, seam_on_a, seam_on_b),
                        leader,
                        exit_leader,
                        connector_fit: (connector_curve, on_follower, on_face),
                        exit_follower,
                        sharp_parameter,
                        ..
                    } => {
                        let (leader_index, follower_index) = if leader == 0 {
                            (ia, ib)
                        } else {
                            (ib, ia)
                        };
                        let exit_point = *seam.points.last().ok_or(KernelRefusal::internal(KernelStage::Refine, "miter_seam", "miter: empty seam"))?;
                        let x_vertex = commit_vertex(&mut result, &mut take_id, exit_point);
                        // At a creased seam S is where the FOLLOWER's own ball
                        // touches the seam: seated exactly (the flush join's
                        // seam ball on the follower's carriers) rather than
                        // read off the connector's marched end, which carries
                        // the follower rail's fit (1.6e-9 on the tilted
                        // fixture at r = 1).
                        let (sharp_parameter, q_point) = if creased_bar.is_some() {
                            let follower = &stripes[follower_index];
                            let (on_shared, on_side) = if follower.first.face.id == shared.id {
                                (&follower.first, &follower.second)
                            } else {
                                (&follower.second, &follower.first)
                            };
                            let ball = solve_flush_seam_ball(
                                on_shared.face,
                                on_shared.rho,
                                on_side.face,
                                on_side.rho,
                                sharp,
                                *vertex_id,
                                vertex_point_of(solid, *vertex_id)?,
                                scale,
                            )?;
                            (ball.seam_parameter, ball.seam_point)
                        } else {
                            (sharp_parameter, sharp.curve.evaluate(sharp_parameter).or_refuse(KernelStage::Refine, "evaluate")?)
                        };
                        let q_vertex = commit_on_sharp(&mut result, &mut take_id, q_point);
                        let seam_id = commit_curve(
                            &mut result,
                            &mut take_id,
                            seam_curve,
                            p_vertex,
                            x_vertex,
                        )?;
                        let connector_id = commit_curve(
                            &mut result,
                            &mut take_id,
                            connector_curve,
                            x_vertex,
                            q_vertex,
                        )?;
                        // Seam images are stored on stripe 0 then stripe 1.
                        let (seam_on_leader, seam_on_follower) = if leader == 0 {
                            (seam_on_a, seam_on_b)
                        } else {
                            (seam_on_b, seam_on_a)
                        };
                        end_plans[leader_index][slot_of(leader_index)] = Some(plan_for(
                            leader_index,
                            exit_leader,
                            x_vertex,
                            vec![(seam_id, seam_on_leader)],
                        )?);
                        end_plans[follower_index][slot_of(follower_index)] = Some(plan_for(
                            follower_index,
                            exit_follower,
                            q_vertex,
                            vec![(seam_id, seam_on_follower), (connector_id, on_follower)],
                        )?);
                        pending_miters.push(PendingMiter {
                            vertex: *vertex_id,
                            sharp_edge: sharp.id,
                            sharp_parameter,
                            sharp_vertex: q_vertex,
                            connector: Some((
                                leader_index,
                                described[usize::from(leader != 0)].other_face.id,
                                connector_id,
                                on_face,
                            )),
                        });
                    }
                }
            }
        }
    }

    // Re-entrant corners: stop each stripe where its wall rail reaches the
    // concave edge, share the pole there, and close with the horn-torus
    // sector between the two end sections plus the cap arc between the two
    // cap rails.
    struct PendingHorn {
        vertex: u64,
        cap_face: u64,
        sharp_edge: u64,
        sharp_parameter: f64,
        pole_vertex: u64,
        pole: Vec3,
        axis: Vec3,
        /// Per stripe (in `stripe_indices` order): its index, the stored
        /// section arc (pole <-> cap point), its cap-rail vertex and point,
        /// and its ball centre at the stop.
        ends: Vec<(usize, EdgeRecord, u64, Vec3, Vec3)>,
        name: Option<String>,
        /// A near-tangent crease whose stop sections are not exact meridians
        /// (`tilted_horn_on`): closed by the ruled patch between the two
        /// sections, not the torus.
        tilted: bool,
    }
    let mut pending_horns: Vec<PendingHorn> = Vec::new();
    stars_miters_timing.stop();
    let reentrant_timing = super::BlendTimer::start("timing.end_plans.reentrant_ms");
    for (vertex_id, stripe_indices, kind) in &corners {
        let radius = vertex_radius_of(*vertex_id).unwrap_or(radius);
        let VertexKind::Reentrant { cap, sharp } = kind else {
            continue;
        };
        let corner_point = solid
            .vertices
            .iter()
            .find(|vertex| vertex.id == *vertex_id)
            .ok_or(KernelRefusal::internal(KernelStage::Refine, "reentrant_vertex", "blend network: re-entrant vertex missing"))?
            .point;
        // Each stripe's wall rail meets the concave edge at the pole; both
        // must meet it at the SAME point (equal wall dihedrals), and the ball
        // centre there must sit over the pole exactly one radius out.
        let mut ends: Vec<(usize, f64, f64, Vec3, Vec3, Vec3)> = Vec::new(); // (index, u_stop, t_pole, pole, cap point, centre)
        for &index in stripe_indices {
            let stripe = &stripes[index];
            let at_start = stripe.at_start(*vertex_id);
            let cap_first = stripe.first.face.id == cap.id;
            let (wall_rail, cap_rail) = if cap_first {
                (&stripe.rows.cs, &stripe.rows.cr)
            } else {
                (&stripe.rows.cr, &stripe.rows.cs)
            };
            let (u_stop, t_pole, pole, escalated) = support_crossing(solid, wall_rail, sharp, at_start)
                .map_err(|error| {
                    format!(
                        "blend network: edge {}'s wall rail does not reach the concave edge at \
                         vertex {vertex_id} ({error})",
                        stripe.edge.id
                    )
                }).or_refuse(KernelStage::Refine, "map_err")?;
            crossings.note(escalated);
            if !(u_stop > RIM_MARGIN && u_stop < 1.0 - RIM_MARGIN) {
                return Err(KernelRefusal::internal(KernelStage::Refine, "concave_stop", format!(
                    "blend network: edge {}'s stop at the concave edge lands at {u_stop:.6}, \
                     outside the marched rows",
                    stripe.edge.id
                )));
            }
            let cap_point = cap_rail.evaluate(u_stop).or_refuse(KernelStage::Refine, "evaluate")?;
            let center = stripe
                .rows
                .center
                .as_ref()
                .ok_or(KernelRefusal::internal(KernelStage::Refine, "centre_path", "blend network: stripe rows carry no centre path"))?
                .evaluate(u_stop).or_refuse(KernelStage::Refine, "evaluate")?;
            ends.push((index, u_stop, t_pole, pole, cap_point, center));
        }
        let pole = ends[0].3;
        let pole_gap = ends[1].3.sub(pole).length();
        if pole_gap > 1e-6 * (1.0 + radius) {
            return Err(KernelRefusal::unsupported(KernelStage::Refine, "horn_torus_dihedrals", format!(
                "blend network: the two blends at vertex {vertex_id} reach the concave edge \
                 {pole_gap:.3e} apart (unequal wall dihedrals) — the closure is not a horn torus \
                 and this lane does not build it"
            )));
        }
        let axis = tangent_away_from(sharp, *vertex_id)?;
        // (`BREP_TILTED_HORN`, default off): the stripes' two ball centres
        // pivot about the concave edge by the crease angle. When that angle
        // is small (a near-tangent crease), a section a little off the
        // meridian is admitted and the closure is the ruled patch between the
        // two stop sections, accepted only where its every sampled point
        // stands on the pivoting ball to the fit tolerance (below, at the
        // sewing).
        let pivot = {
            let radial = |center: Vec3| center.sub(ends[0].3).normalized().ok();
            match (radial(ends[0].5), radial(ends[1].5)) {
                (Some(a), Some(b)) => a.dot(b).clamp(-1.0, 1.0).acos(),
                _ => f64::INFINITY,
            }
        };
        let mut tilted = false;
        for (index, u_stop, _, _, cap_point, center) in &ends {
            // The section at the stop must be a meridian of the torus about
            // the concave edge: its plane (normal = the stripe's direction
            // there) must contain the axis, and its centre must sit one
            // radius from the pole, perpendicular to the axis.
            let stripe = &stripes[*index];
            let centre_path = stripe
                .rows
                .center
                .as_ref()
                .ok_or(KernelRefusal::internal(KernelStage::Refine, "centre_path", "blend network: stripe rows carry no centre path"))?;
            let [c0, c1] = centre_path.domain().or_refuse(KernelStage::Refine, "domain")?;
            let direction = centre_path.unit_tangent(*u_stop, c0, c1).map_err(|error| {
                format!(
                    "blend network: edge {}'s centre path at u = {u_stop}: {error}",
                    stripe.edge.id
                )
            }).or_refuse(KernelStage::Refine, "map_err")?;
            let radial = center.sub(pole);
            let on_pivot = (radial.length() - radius).abs() <= 1e-6 * (1.0 + radius)
                && radial.dot(axis).abs() <= 1e-6 * (1.0 + radius);
            if direction.dot(axis).abs() > 1e-6
                && on_pivot
                && tilted_horn_on()
                && pivot <= TILTED_HORN_MAX_PIVOT
                && direction.dot(axis).abs() <= TILTED_HORN_MAX_TILT
            {
                tilted = true;
                continue;
            }
            if direction.dot(axis).abs() > 1e-6 || !on_pivot {
                return Err(KernelRefusal::unsupported(KernelStage::Refine, "horn_torus_tilt", format!(
                    "blend network: edge {}'s section at vertex {vertex_id} is not a meridian \
                     of the horn torus about the concave edge (tilted class) — not in this lane",
                    stripe.edge.id
                )));
            }
            if (cap_point.sub(corner_point).length() - radius).abs() > 1e-6 * (1.0 + radius) {
                return Err(KernelRefusal::unsupported(KernelStage::Refine, "horn_torus_cap", format!(
                    "blend network: edge {}'s cap rail stops {:.6} from the re-entrant vertex, \
                     not one radius — the cap is not planar or the walls are not perpendicular \
                     to it",
                    stripe.edge.id,
                    cap_point.sub(corner_point).length()
                )));
            }
        }
        let pole_vertex = {
            let id = take_id();
            result.vertices.push(VertexRecord { id, point: pole });
            id
        };
        let mut committed: Vec<(usize, EdgeRecord, u64, Vec3, Vec3)> = Vec::new();
        for (index, u_stop, _, _, cap_point, center) in &ends {
            let stripe = &stripes[*index];
            let at_start = stripe.at_start(*vertex_id);
            let cap_first = stripe.first.face.id == cap.id;
            let cap_vertex = take_id();
            result.vertices.push(VertexRecord {
                id: cap_vertex,
                point: *cap_point,
            });
            // The section arc of the ball at the stop, from the cap point to
            // the pole, stored in the blend loop's walk direction like a star
            // arc.
            let (first_point, first_vertex, second_point, second_vertex) = if cap_first {
                (*cap_point, cap_vertex, pole, pole_vertex)
            } else {
                (pole, pole_vertex, *cap_point, cap_vertex)
            };
            let walk_first_to_second = stripe.walk_first_to_second(at_start);
            let (from, to, from_vertex, to_vertex) = if walk_first_to_second {
                (first_point, second_point, first_vertex, second_vertex)
            } else {
                (second_point, first_point, second_vertex, first_vertex)
            };
            // §6.11: a chamfer's section at the stop is the CHORD between
            // the ball's two contacts, exactly as at a star — and here one of
            // those contacts is the POLE, the single point where the ball
            // touches the concave edge.
            let arc = if chamfer {
                crate::make_line(from, to).or_refuse(KernelStage::Refine, "make_line")?
            } else {
                corner_section_arc(*center, radius, from, to)?
            };
            let arc_domain = arc.domain().or_refuse(KernelStage::Refine, "domain")?;
            let arc_edge_id = take_id();
            let record = EdgeRecord {
                id: arc_edge_id,
                curve: arc,
                t0: arc_domain[0],
                t1: arc_domain[1],
                start_vertex_id: from_vertex,
                end_vertex_id: to_vertex,
                degenerate: false,
                name: None,
            };
            result.edges.push(record.clone());
            let arc_blend_pcurve = if walk_first_to_second {
                crate::sweep_topology::parameter_line(*u_stop, 0.0, *u_stop, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?
            } else {
                crate::sweep_topology::parameter_line(*u_stop, 1.0, *u_stop, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?
            };
            end_plans[*index][usize::from(!at_start)] = Some(EndPlan::Corner(CornerEnd {
                cr_parameter: *u_stop,
                cs_parameter: *u_stop,
                first_vertex,
                second_vertex,
                arc_edge_id,
                arc_blend_pcurve,
            }));
            committed.push((*index, record, cap_vertex, *cap_point, *center));
        }
        pending_horns.push(PendingHorn {
            vertex: *vertex_id,
            cap_face: cap.id,
            sharp_edge: sharp.id,
            sharp_parameter: ends[0].2,
            pole_vertex,
            pole,
            axis,
            ends: committed,
            name: corner_name(stripe_indices),
            tilted,
        });
    }

    // Lane L, mixed stars: each convex stripe stops at its section through
    // its wall's tangency point V (where Q's rail on that wall meets its
    // own), Q stops at its inner-equator section V_A..V_B; the cap's contact
    // arc W_A..W_B and the torus sector are sewn after the stripes.
    struct PendingMixedStar {
        vertex: u64,
        mixed: MixedStar,
        /// The three end-section arcs: rim A, rim B, Q.
        arcs: [EdgeRecord; 3],
        v_a: u64,
        v_b: u64,
        w_a: u64,
        w_b: u64,
        name: Option<String>,
    }
    let mut pending_mixed: Vec<PendingMixedStar> = Vec::new();
    reentrant_timing.stop();
    let mixed_star_timing = super::BlendTimer::start("timing.end_plans.mixed_star_ms");
    for (vertex_id, stripe_indices, kind) in &corners {
        let VertexKind::MixedStar(mixed) = kind else {
            continue;
        };
        let mut new_vertex = |point: Vec3, result: &mut BrepSolid| {
            let id = take_id();
            result.vertices.push(VertexRecord { id, point });
            id
        };
        let v_a = new_vertex(mixed.v_a, &mut result);
        let v_b = new_vertex(mixed.v_b, &mut result);
        let w_a = new_vertex(mixed.w_a, &mut result);
        let w_b = new_vertex(mixed.w_b, &mut result);
        // (stripe, [(face, point, vertex); 2], ball centre at the stop)
        let plans = [
            (mixed.a, [(mixed.wall_a, mixed.v_a, v_a), (mixed.cap, mixed.w_a, w_a)], mixed.c_a),
            (mixed.b, [(mixed.wall_b, mixed.v_b, v_b), (mixed.cap, mixed.w_b, w_b)], mixed.c_b),
            (mixed.q, [(mixed.wall_a, mixed.v_a, v_a), (mixed.wall_b, mixed.v_b, v_b)], mixed.q_v),
        ];
        let mut arcs: Vec<EdgeRecord> = Vec::with_capacity(3);
        for (index, contacts, center) in plans {
            let stripe = &stripes[index];
            let at_start = stripe.at_start(*vertex_id);
            let station_0 = station_on(stripe, contacts[0].0, contacts[0].1)?;
            let station_1 = station_on(stripe, contacts[1].0, contacts[1].1)?;
            if (station_0 - station_1).abs() > 1e-3 {
                return Err(KernelRefusal::internal(KernelStage::Refine, "mixed_star_stations", format!(
                    "blend network: edge {} meets the mixed star at vertex {vertex_id} at inconsistent \
                     stations ({station_0:.6} and {station_1:.6})",
                    stripe.edge.id
                )));
            }
            let station = 0.5 * (station_0 + station_1);
            let on = |face_id: u64| contacts.iter().find(|(face, _, _)| *face == face_id).copied();
            let (_, first_point, first_vertex) = on(stripe.first.face.id).ok_or(KernelRefusal::internal(
                KernelStage::Refine, "mixed_star_face", "blend network: a mixed star stripe misses its face"))?;
            let (_, second_point, second_vertex) = on(stripe.second.face.id).ok_or(KernelRefusal::internal(
                KernelStage::Refine, "mixed_star_face", "blend network: a mixed star stripe misses its face"))?;
            let walk_first_to_second = stripe.walk_first_to_second(at_start);
            let (from, to, from_vertex, to_vertex) = if walk_first_to_second {
                (first_point, second_point, first_vertex, second_vertex)
            } else {
                (second_point, first_point, second_vertex, first_vertex)
            };
            let arc = corner_section_arc(center, mixed.radius, from, to)?;
            let arc_domain = arc.domain().or_refuse(KernelStage::Refine, "domain")?;
            let record = EdgeRecord {
                id: take_id(),
                curve: arc,
                t0: arc_domain[0],
                t1: arc_domain[1],
                start_vertex_id: from_vertex,
                end_vertex_id: to_vertex,
                degenerate: false,
                name: None,
            };
            result.edges.push(record.clone());
            let arc_blend_pcurve = if walk_first_to_second {
                crate::sweep_topology::parameter_line(station, 0.0, station, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?
            } else {
                crate::sweep_topology::parameter_line(station, 1.0, station, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?
            };
            end_plans[index][usize::from(!at_start)] = Some(EndPlan::Corner(CornerEnd {
                cr_parameter: station,
                cs_parameter: station,
                first_vertex,
                second_vertex,
                arc_edge_id: record.id,
                arc_blend_pcurve,
            }));
            arcs.push(record);
        }
        let arcs: [EdgeRecord; 3] = arcs.try_into().map_err(|_| KernelRefusal::internal(KernelStage::Refine, "mixed_star_arcs", "blend network: a mixed star needs three arcs"))?;
        pending_mixed.push(PendingMixedStar {
            vertex: *vertex_id,
            mixed: *mixed,
            arcs,
            v_a,
            v_b,
            w_a,
            w_b,
            name: corner_name(stripe_indices),
        });
    }

    // Flush joins: both stripes stop at their own vertex section, which is
    // the same ball on both sides, and share one arc.
    struct PendingFlush {
        vertex: u64,
        /// The seam edges between the two stripes' differing side faces, to
        /// trim at the rims on them: (edge id, parameter, rim).
        seam_trims: Vec<(u64, f64, u64)>,
    }
    let mut pending_flush: Vec<PendingFlush> = Vec::new();
    mixed_star_timing.stop();
    let flush_timing = super::BlendTimer::start("timing.end_plans.flush_ms");
    for (vertex_id, stripe_indices, kind) in &corners {
        let radius = vertex_radius_of(*vertex_id).unwrap_or(radius);
        let VertexKind::Flush { join } = kind else {
            continue;
        };
        let [ia, ib] = [stripe_indices[0], stripe_indices[1]];
        let section = |index: usize| -> Result<(f64, Vec3, Vec3, Vec3), KernelRefusal> {
            let stripe = &stripes[index];
            if let Some(join) = join {
                // Across a seam: the stripe stops where its rails pass the
                // seam ball's contacts, and the section IS that ball's, so
                // both stripes carry the same points to the bar below.  The
                // station is read on a rail whose contact sits on a seam —
                // where that rail changes carrier — and the other rail must
                // pass its own contact there.
                let contact = |face_id: u64| {
                    join.contact_on(face_id).ok_or_else(|| {
                        format!(
                            "blend network: the flush join at vertex {vertex_id} has no contact \
                             on edge {}'s face {face_id}",
                            stripe.edge.id
                        )
                    })
                };
                let (first_contact, second_contact) =
                    (contact(stripe.first.face.id).or_refuse(KernelStage::Refine, "contact")?, contact(stripe.second.face.id).or_refuse(KernelStage::Refine, "contact")?);
                let seam_first = first_contact.seam.is_some();
                let (lead_face, lead_row, lead, other_face, other_row, other) = if seam_first {
                    (
                        stripe.first.face.id,
                        &stripe.rows.cr,
                        first_contact,
                        stripe.second.face.id,
                        &stripe.rows.cs,
                        second_contact,
                    )
                } else {
                    (
                        stripe.second.face.id,
                        &stripe.rows.cs,
                        second_contact,
                        stripe.first.face.id,
                        &stripe.rows.cr,
                        first_contact,
                    )
                };
                let station_bar = corner_station_bar(scale, radius);
                let station = rail_station(lead_row, lead.point, station_bar).map_err(
                    |reason| match reason {
                        RailMiss::OffRail(distance) => format!(
                            "blend network: edge {}'s contact rail on face {lead_face} misses \
                             the flush join's seam contact at vertex {vertex_id} by \
                             {distance:.3e}",
                            stripe.edge.id
                        ),
                        RailMiss::OffSpan(station) => format!(
                            "blend network: the flush join station for edge {} lands at \
                             {station:.6}, outside the marched rows",
                            stripe.edge.id
                        ),
                        RailMiss::Projection(error) => error,
                    },
                ).or_refuse(KernelStage::Refine, "map_err")?;
                let other_miss = other_row.evaluate(station).or_refuse(KernelStage::Refine, "evaluate")?.sub(other.point).length();
                if other_miss > station_bar {
                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join", format!(
                        "blend network: edge {}'s contact rail on face {other_face} misses the \
                         flush join's contact at vertex {vertex_id} by {other_miss:.3e} at the \
                         station its seam contact is on",
                        stripe.edge.id
                    )));
                }
                return Ok((station, first_contact.point, second_contact.point, join.center));
            }
            let at_start = stripe.at_start(*vertex_id);
            let station = stripe
                .rows
                .vertex_stations
                .ok_or(KernelRefusal::internal(KernelStage::Refine, "vertex_stations", "blend network: stripe rows carry no vertex stations"))?
                [usize::from(!at_start)];
            if !(station > RIM_MARGIN && station < 1.0 - RIM_MARGIN) {
                return Err(KernelRefusal::internal(KernelStage::Refine, "vertex_section", format!(
                    "blend network: edge {}'s vertex section lands at {station:.6}, outside \
                     the marched rows",
                    stripe.edge.id
                )));
            }
            let center = stripe
                .rows
                .center
                .as_ref()
                .ok_or(KernelRefusal::internal(KernelStage::Refine, "centre_path", "blend network: stripe rows carry no centre path"))?
                .evaluate(station).or_refuse(KernelStage::Refine, "evaluate")?;
            Ok((
                station,
                stripe.rows.cr.evaluate(station).or_refuse(KernelStage::Refine, "evaluate")?,
                stripe.rows.cs.evaluate(station).or_refuse(KernelStage::Refine, "evaluate")?,
                center,
            ))
        };
        let (station_a, cr_a, cs_a, center_a) = section(ia)?;
        let (station_b, cr_b, cs_b, center_b) = section(ib)?;
        let bar = 1e-6 * (1.0 + radius);
        if center_a.sub(center_b).length() > bar {
            return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join", format!(
                "blend network: the two blends at the smooth vertex {vertex_id} sit on \
                 different balls ({:.3e} apart) — not a flush join",
                center_a.sub(center_b).length()
            )));
        }
        // Pair stripe b's rims with stripe a's by position (the mates may be
        // different faces that are tangent there).
        let (b_first_matches_a_first, mismatch) = {
            let direct = cr_b.sub(cr_a).length().max(cs_b.sub(cs_a).length());
            let crossed = cr_b.sub(cs_a).length().max(cs_b.sub(cr_a).length());
            if direct <= crossed {
                (true, direct)
            } else {
                (false, crossed)
            }
        };
        if mismatch > bar {
            return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join", format!(
                "blend network: the two sections at the smooth vertex {vertex_id} differ by \
                 {mismatch:.3e} — not a flush join"
            )));
        }
        // Shared rim vertices, keyed by stripe a's first/second sides.
        let rim_first = take_id();
        result.vertices.push(VertexRecord {
            id: rim_first,
            point: cr_a,
        });
        let rim_second = take_id();
        result.vertices.push(VertexRecord {
            id: rim_second,
            point: cs_a,
        });
        // One arc, stored in stripe a's walk direction; stripe b walks it the
        // other way (its loop runs opposite across the shared edge), which
        // the corner plan expresses by storing... no: a corner plan always
        // uses its arc forward.  So commit the arc in a's walk direction and
        // give b a plan whose arc pcurve runs the same 3D way — b's walk is
        // guaranteed opposite by manifoldness, so b uses `forward = false`.
        // `CornerEnd` cannot say that; a `MiterEnd` can.
        let stripe_a = &stripes[ia];
        let at_start_a = stripe_a.at_start(*vertex_id);
        let walk_a_first_to_second = stripe_a.walk_first_to_second(at_start_a);
        let (from, to, from_vertex, to_vertex) = if walk_a_first_to_second {
            (cr_a, cs_a, rim_first, rim_second)
        } else {
            (cs_a, cr_a, rim_second, rim_first)
        };
        // §6.11: the shared section is the one both stripes stop at, and a
        // chamfer's is the CHORD between the two rims a fillet arcs between.
        // Nothing else about a flush join depends on its shape — the two
        // stripes' agreement was already measured on the ball's centre and on
        // the rim points themselves, which are the chord's own ends.
        let arc = if chamfer {
            crate::make_line(from, to).or_refuse(KernelStage::Refine, "make_line")?
        } else {
            corner_section_arc(center_a, radius, from, to)?
        };
        let arc_domain = arc.domain().or_refuse(KernelStage::Refine, "domain")?;
        let arc_edge_id = take_id();
        result.edges.push(EdgeRecord {
            id: arc_edge_id,
            curve: arc,
            t0: arc_domain[0],
            t1: arc_domain[1],
            start_vertex_id: from_vertex,
            end_vertex_id: to_vertex,
            degenerate: false,
            name: None,
        });
        let pcurve_a = if walk_a_first_to_second {
            crate::sweep_topology::parameter_line(station_a, 0.0, station_a, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?
        } else {
            crate::sweep_topology::parameter_line(station_a, 1.0, station_a, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?
        };
        end_plans[ia][usize::from(!at_start_a)] = Some(EndPlan::Corner(CornerEnd {
            cr_parameter: station_a,
            cs_parameter: station_a,
            first_vertex: rim_first,
            second_vertex: rim_second,
            arc_edge_id,
            arc_blend_pcurve: pcurve_a,
        }));
        // Stripe b: its first/second rims map onto a's by the pairing above.
        let stripe_b = &stripes[ib];
        let at_start_b = stripe_b.at_start(*vertex_id);
        let (b_first_vertex, b_second_vertex) = if b_first_matches_a_first {
            (rim_first, rim_second)
        } else {
            (rim_second, rim_first)
        };
        // b's walk over the slot, first-rim -> second-rim or the reverse, in
        // terms of the arc's stored direction (a's walk).  The stored arc
        // runs a-first -> a-second when `walk_a_first_to_second`.
        let b_walk_first_to_second = stripe_b.walk_first_to_second(at_start_b);
        let b_walk_in_a_terms = b_walk_first_to_second == b_first_matches_a_first;
        let forward = b_walk_in_a_terms == walk_a_first_to_second;
        let pcurve_b = if b_walk_first_to_second {
            crate::sweep_topology::parameter_line(station_b, 0.0, station_b, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?
        } else {
            crate::sweep_topology::parameter_line(station_b, 1.0, station_b, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?
        };
        end_plans[ib][usize::from(!at_start_b)] = Some(EndPlan::Miter(MiterEnd {
            cr_parameter: station_b,
            cs_parameter: station_b,
            first_vertex: b_first_vertex,
            second_vertex: b_second_vertex,
            edges: vec![(arc_edge_id, forward, pcurve_b)],
        }));
        if forward {
            return Err(KernelRefusal::internal(KernelStage::Refine, "flush_join_orientation", format!(
                "blend network: the two blends at the smooth vertex {vertex_id} walk their \
                 shared section the same way — inconsistent orientation"
            )));
        }
        // Where the side faces differ, each seam between them runs from the
        // vertex through the ball's contact on it, and is trimmed there.
        let seam_trims = join
            .iter()
            .flat_map(|join| &join.contacts)
            .filter_map(|contact| {
                let (seam_id, parameter) = contact.seam?;
                let rim = if contact.faces.contains(&stripe_a.first.face.id) {
                    rim_first
                } else {
                    rim_second
                };
                Some((seam_id, parameter, rim))
            })
            .collect();
        pending_flush.push(PendingFlush {
            vertex: *vertex_id,
            seam_trims,
        });
    }

    let mut pending_caps: Vec<PendingCap> = Vec::new();
    // The stopped-end rollover (switch, default off): a stripe whose finish
    // end the network CAPS and whose tracks left their carriers across
    // tangent edges before the vertex rolls onto the neighbours there; its
    // re-marched rows, crossings and cap leg chains, for its surgery.
    let mut rolled_ends: Vec<Option<RolledEnd>> = (0..stripes.len()).map(|_| None).collect();
    let mut pending_tapers: Vec<super::taper_runout::PendingTaper> = Vec::new();
    // The (stripe index) of every end planned as a taper to a cusp.
    let mut taper_ends: Vec<usize> = Vec::new();

    flush_timing.stop();
    let free_ends_timing = super::BlendTimer::start("timing.end_plans.free_ends_ms");
    // ---- 6. Free ends keep the §6.9 transverse construction — or, where
    //         the edge runs smoothly into an unselected one, a CAP. ----
    for (index, stripe) in stripes.iter().enumerate() {
        for (slot, (vertex, at_start)) in [
            (stripe.edge.start_vertex_id, true),
            (stripe.edge.end_vertex_id, false),
        ]
        .into_iter()
        .enumerate()
        {
            if end_plans[index][slot].is_some() {
                continue;
            }
            if stripe.poles[slot] {
                end_plans[index][slot] = Some(EndPlan::Corner(plan_pole_end(
                    solid,
                    &mut result,
                    &mut take_id,
                    stripe,
                    vertex,
                    at_start,
                )?));
                continue;
            }
            // On a CONCAVE edge, a mate CUSPED at this vertex (lane R7's
            // class) tapers to its tip before the free end is asked: the free
            // end can find a crossing there (report b46db89a's sliver, whose
            // contact meets the sliver's straight boundary) and ship a wall
            // that overhangs the cusp into air. A convex edge keeps R7's
            // order, the taper only where the free end refuses: asked first,
            // the face ring's convex ends planned tapers from outside their
            // edge (t −1.34, 1.11) where the free end builds
            // (`fillet::tests::face_ring_fillet_builds_the_full_ring`).
            let concave = (stripe.first.rho > 0.0) == stripe.first.face.same_sense;
            if concave && super::relief::relief_enabled() {
                if let Some(plan) = super::taper_runout::plan_taper_end(
                    solid,
                    &mut result,
                    &mut take_id,
                    stripe.edge,
                    &stripe.first,
                    &stripe.second,
                    &stripe.rows,
                    stripe.law.constant(),
                    chamfer,
                    stripe.walk_first_to_second(at_start),
                    stripe.name.as_deref(),
                    vertex,
                    &mut pending_tapers,
                )? {
                    let support = [stripe.first.face, stripe.second.face]
                        .into_iter()
                        .find(|face| super::taper_runout::cusped_at(solid, stripe.edge, face, vertex))
                        .map(|face| face.name.clone().unwrap_or_else(|| format!("face #{}", face.id)))
                        .unwrap_or_default();
                    super::record_blend_note(format!(
                        "radius tapered to zero at the tip where `{support}` narrows to a point (edge {})",
                        stripe.name.clone().unwrap_or_else(|| format!("#{}", stripe.edge.id))
                    ));
                    taper_ends.push(index);
                    end_plans[index][slot] = Some(EndPlan::Cap(plan));
                    continue;
                }
                // The support check admits a CONCAVE edge's cusped tip as the
                // taper's (`fillet/analyze.rs::support_extent`); a free end
                // there would ship the wall the check exists to refuse. A
                // convex edge's cusped end keeps the free end, as before
                // (`fillet::tests::face_ring_fillet_builds_the_full_ring`:
                // its taper misses B by 8.8e-7 and the free end builds).
                let cusped = [stripe.first.face, stripe.second.face]
                    .into_iter()
                    .any(|face| super::taper_runout::cusped_at(solid, stripe.edge, face, vertex));
                if cusped && stripe.law.constant().is_some() && !chamfer {
                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "taper_runout_unplanned", format!(
                        "blend network: a mate of edge {} narrows to a cusp at vertex {vertex}, and the round's \
                         taper to that tip could not be planned",
                        stripe.edge.id
                    )));
                }
            }
            match resolve_free_end(
                solid,
                stripe.edge.id,
                &stripe.first,
                &stripe.second,
                &stripe.rows,
                vertex,
                at_start,
            ) {
                Ok((end, _)) => {
                    crossings.note(end.escalated);
                    end_plans[index][slot] = Some(EndPlan::Free(end));
                }
                Err(free_error) => {
                    // A mate CUSPED here while the other mate's boundary runs
                    // on along the edge (report 80c5d9d1's F10, the straight
                    // edge of a sliver whose far side F9's tapered round
                    // took: the sliver ends at the round's hairline end, and
                    // the box top's boundary continues past it to the tip)
                    // tapers to the cusp; the tangent cap below would close
                    // the round on a planar web under the overhang.
                    let cusped = [stripe.first.face, stripe.second.face]
                        .into_iter()
                        .any(|face| super::taper_runout::cusped_at(solid, stripe.edge, face, vertex));
                    if cusped {
                        // Not planned (or refused): the end is asked as
                        // before, with whatever a refused plan added undone.
                        let marks = (result.vertices.len(), result.edges.len(), pending_tapers.len());
                        let planned = super::taper_runout::plan_taper_end(
                            solid,
                            &mut result,
                            &mut take_id,
                            stripe.edge,
                            &stripe.first,
                            &stripe.second,
                            &stripe.rows,
                            stripe.law.constant(),
                            chamfer,
                            stripe.walk_first_to_second(at_start),
                            stripe.name.as_deref(),
                            vertex,
                            &mut pending_tapers,
                        );
                        if let Ok(Some(plan)) = planned {
                            taper_ends.push(index);
                            end_plans[index][slot] = Some(EndPlan::Cap(plan));
                            continue;
                        }
                        result.vertices.truncate(marks.0);
                        result.edges.truncate(marks.1);
                        pending_tapers.truncate(marks.2);
                    }
                    // A nearly tangent line/arc junction can have no free-end
                    // crossing, or put it beyond the marched rows. Retry those
                    // failures with a vertex section only within a small
                    // angular window (about 0.8 degrees). A cap at a genuine
                    // corner can validate but erase the notch needed by a
                    // later convex-corner closure (the acute-prism cases).
                    // This does not snap the junction to tangency; the cap's
                    // carrier legs, restriction and validation still have to
                    // prove that the section closes on the original solid.
                    let continuing = [stripe.first.face, stripe.second.face]
                        .iter()
                        .find_map(|face| {
                            let id = boundary_edge_at_vertex(solid, face, vertex, stripe.edge.id)
                                .ok()?;
                            let boundary = solid.edges.iter().find(|e| e.id == id)?;
                            let own = tangent_away_from(stripe.edge, vertex).ok()?;
                            let other = tangent_away_from(boundary, vertex).ok()?;
                            let alignment = own.dot(other);
                            let tangent = alignment <= -(1.0 - 1e-6);
                            let missing_crossing = matches!(
                                &free_error.class,
                                RefusalClass::UnsupportedGeometry { what }
                                    if what == "support_crossing_uv_outside"
                                        || what == "support_crossing_uv_none"
                                        || what == super::edge::END_TANGENT_CONTINUATION_WHAT
                            );
                            (tangent || (missing_crossing && alignment <= -(1.0 - 1e-4)))
                                .then_some((boundary, tangent))
                        });
                    let Some((boundary, tangent)) = continuing else {
                        // Lane R7: an end the free end and the cap both
                        // refuse, where a mate is cusped at this vertex, ends
                        // on a tapered runout (`taper_runout.rs`).
                        match super::taper_runout::plan_taper_end(
                            solid,
                            &mut result,
                            &mut take_id,
                            stripe.edge,
                            &stripe.first,
                            &stripe.second,
                            &stripe.rows,
                            stripe.law.constant(),
                            chamfer,
                            stripe.walk_first_to_second(at_start),
                            stripe.name.as_deref(),
                            vertex,
                            &mut pending_tapers,
                        )? {
                            Some(plan) => {
                                taper_ends.push(index);
                                end_plans[index][slot] = Some(EndPlan::Cap(plan));
                                continue;
                            }
                            None => return Err(free_error),
                        }
                    };
                    // Before the tangent reads took the one-sided limit, a
                    // stationary edge here read as "does not continue" and
                    // refused with `free_error`. The limit now says it does
                    // continue, but no fixture has shown a stripe capped
                    // through a stationary join to be the right body, so the
                    // direction is read and the cap is not built.
                    if stationary_at_vertex(stripe.edge, vertex)?
                        || stationary_at_vertex(boundary, vertex)?
                    {
                        return Err(KernelRefusal::unsupported(KernelStage::Refine, "stationary_join", format!(
                            "blend network: edge {} continues smoothly into edge {} at vertex \
                             {vertex} only by the one-sided limit of a stationary tangent (a \
                             first derivative that vanishes at the vertex); a stripe capped \
                             through a stationary join is not verified, so it is not built",
                            stripe.edge.id, boundary.id
                        )));
                    }
                    // The end the network caps: with the switch on, a finish
                    // end whose tracks left their carriers rolls first.
                    let rolled = if !at_start && super::stopped_end_rollover_on() {
                        plan_stopped_end_rollover(solid, stripe, chamfer)?
                    } else {
                        None
                    };
                    let (plan, needs_validation, chains) = match rolled {
                        Some((rows, sides)) => {
                            let outcome = plan_cap_end(
                                solid,
                                &mut result,
                                &mut take_id,
                                stripe,
                                &rows,
                                vertex,
                                at_start,
                                stripe.end_radius[slot],
                                &mut pending_caps,
                                [sides[0].as_ref(), sides[1].as_ref()],
                            )?;
                            rolled_ends[index] = Some(RolledEnd { rows, sides, chains: [Vec::new(), Vec::new()] });
                            outcome
                        }
                        None => plan_cap_end(
                            solid,
                            &mut result,
                            &mut take_id,
                            stripe,
                            &stripe.rows,
                            vertex,
                            at_start,
                            stripe.end_radius[slot],
                            &mut pending_caps,
                            [None, None],
                        )?,
                    };
                    if let Some(rolled) = rolled_ends[index].as_mut() {
                        rolled.chains = chains;
                    }
                    crossings.note(needs_validation || !tangent);
                    end_plans[index][slot] = Some(EndPlan::Cap(plan));
                }
            }
        }
    }

    free_ends_timing.stop();
    end_plans_timing.stop();
    // ---- 7. Sew: every stripe, then the corner patches and the miter
    //         trims, then one prune. ----
    let surgery_timing = super::BlendTimer::start("timing.surgery_ms");
    let mut sewn: Vec<SewnStripe> = Vec::with_capacity(stripes.len());
    // Each FILLET stripe's shipped wall, read on what ships and owed typed
    // where it does not meet its bars: bound to its sewn face at the end.
    let mut owed: Vec<OwedWallReport> = Vec::new();
    for (index, stripe) in stripes.iter().enumerate() {
        let [start_plan, finish_plan] = std::mem::replace(&mut end_plans[index], [None, None]);
        let (Some(start_plan), Some(finish_plan)) = (start_plan, finish_plan) else {
            return Err(KernelRefusal::internal(KernelStage::Refine, "stripe_end_plan", "blend network: a stripe end was left unplanned"));
        };
        // The two ends must leave some rail between them.  When the corner
        // setbacks from both ends meet or cross, the edge is shorter than the
        // fillet is wide and its blend strip pinches out — a configuration
        // this lane names rather than builds (pinch splitting is not
        // implemented).
        //
        // "Some rail" is a LENGTH, measured on the rail itself, and the bar
        // is the one the corner stations were accepted under
        // (`corner_station_bar`): two stops closer than that are the same
        // point by this lane's own standard, and two stops farther apart
        // bound a strip the surgery splits like any other.  It used to be
        // read in ROW PARAMETER against `RIM_MARGIN`, which is the margin a
        // single station needs from the row's END, not a strip width — and
        // 2e-3 of a row is 0.04 on a 20-long edge, so every strip narrower
        // than that (all twelve edges of a 20-cube at r ≥ 9.99, a strip of
        // 0.02) was refused as a pinch and fell through to the cutter
        // composition, which returned a validating solid with half the
        // part's volume again.  The row's parameter is not a length.
        //
        // A strip within `consumed_band` of nothing is the FULL-WIDTH corner:
        // the two stops are one point, the surgery builds no rail there, and
        // `collapse_full_width` identifies the rims and drops what lost its
        // area.  Any wider strip is kept as a face — it is at least a sliver
        // wide, the same rule the consumed width follows — and only stops that
        // CROSS by more than the band are a pinch.  The bar used to be the
        // corner station's own (1.8e-5 on a 10-cube), which sent every strip
        // under it to the cutter composition; at 1e-5 short of full width that
        // built a collapsed 5F/8E/5V miter 8.0e-4 off its closed form.
        let band = consumed_band(solid);
        let converted = converted_rows.iter().find(|(converted_index, _)| *converted_index == index).map(|(_, rows)| rows);
        let rolled = rolled_ends[index].take();
        let stripe_rows: &FittedRows = rolled.as_ref().map(|rolled| &rolled.rows).or(converted).unwrap_or(&stripe.rows);
        for (row, start, finish, which) in [
            (
                &stripe_rows.cr,
                start_plan.cr_parameter(),
                finish_plan.cr_parameter(),
                "first",
            ),
            (
                &stripe_rows.cs,
                start_plan.cs_parameter(),
                finish_plan.cs_parameter(),
                "second",
            ),
        ] {
            let strip = row.evaluate(finish).or_refuse(KernelStage::Refine, "evaluate")?.sub(row.evaluate(start).or_refuse(KernelStage::Refine, "evaluate")?).length();
            if finish <= start && strip > band {
                // An end planned as a TAPER to a cusp (`taper_runout.rs`)
                // stops where the width reaches 2R; a setback past it means
                // the round has no constant run, which the group answers by
                // building at a smaller radius (`fillet/edges.rs`, report
                // 80c5d9d1's F10: r 1 on a sliver at most 2 wide within 0.9
                // of its square corner).
                let tapered = taper_ends.contains(&index);
                let what = if tapered { STRIPE_PINCH_TAPER_WHAT } else { "stripe_pinch" };
                let why = if tapered {
                    "the round's taper to its tip reaches the full radius only inside the corner setback"
                } else {
                    "the blend strip pinches out and pinch splitting is not implemented"
                };
                return Err(KernelRefusal::unsupported(KernelStage::Refine, what, format!(
                    "blend network: edge {} is shorter than the two corner setbacks that meet \
                     on it (its {which} rail would run from {start:.6} to {finish:.6}, stops \
                     {strip:.3e} past each other against a band of {band:.3e}); {why}",
                    stripe.edge.id
                )));
            }
        }
        let rows = FittedRows {
            surface: stripe_rows.surface.clone(),
            cr: stripe_rows.cr.clone(),
            cs: stripe_rows.cs.clone(),
            cr_pcurve: stripe_rows.cr_pcurve.clone(),
            cs_pcurve: stripe_rows.cs_pcurve.clone(),
            u_domain: stripe_rows.u_domain,
            center: None,
            exact_extrusion: stripe_rows.exact_extrusion,
            vertex_stations: stripe_rows.vertex_stations,
            revolution_axis: stripe_rows.revolution_axis,
        };
        // The SHIPPED windows: each rail between the parameters its two end
        // plans trim it to (corner station, pole, flush join, miter, cap or
        // free-end crossing), retained overshoot included; the wall over
        // their envelope.
        let spans = [
            shipped_span(&stripe.measure.parameters, &stripe_rows.cr, start_plan.cr_parameter(), finish_plan.cr_parameter(), band),
            shipped_span(&stripe.measure.parameters, &stripe_rows.cs, start_plan.cs_parameter(), finish_plan.cs_parameter(), band),
        ];
        let report_timing = super::BlendTimer::start("timing.surgery.wall_report_ms");
        let report = if converted.is_some() {
            None
        } else {
            shipped_wall_report(stripe, spans, stripe.law.constant().unwrap_or(radius), solid)
        };
        report_timing.stop();
        sewn.push(build_open_surgery_with_tail(
            solid,
            &mut result,
            &mut take_id,
            stripe.edge,
            &stripe.first,
            &stripe.second,
            rows,
            [start_plan, finish_plan],
            stripe.name.as_deref(),
            match rolled.as_ref() {
                Some(rolled) => [
                    rolled.sides[0].as_ref().map(|side| super::rollover::TailSplice { rolled: side, legs: rolled.chains[0].clone() }),
                    rolled.sides[1].as_ref().map(|side| super::rollover::TailSplice { rolled: side, legs: rolled.chains[1].clone() }),
                ],
                None => [None, None],
            },
        )?);
        if let Some((reason, bar, measured, detail)) = report {
            let face_id = sewn[sewn.len() - 1].blend_face_id;
            // The wall AS SEWN (an exact extrusion is transposed at sewing). A
            // surgery that returned a face it did not sew is incoherent: it
            // refuses, as the open edge's lane does, rather than drop what the
            // wall owes.
            let face = result.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == face_id).ok_or_else(|| {
                KernelRefusal::internal(
                    KernelStage::Sew,
                    "network_blend_face",
                    format!("blend network: edge {}'s sewn blend face {face_id} is not in the body it was sewn into", stripe.edge.id),
                )
            })?;
            owed.push(OwedWallReport {
                edge: stripe.edge.id,
                name: stripe.name.clone(),
                surface: face.surface.clone(),
                reason,
                bar,
                measured,
                detail,
            });
        }
    }
    let closures_timing = super::BlendTimer::start("timing.surgery.closures_ms");
    for patch in patches {
        let face = if chamfer {
            build_chamfer_corner_facet(
                patch.center,
                &patch.normals,
                &patch.arcs,
                patch.outward,
                patch.name.as_deref(),
                &mut take_id,
            )?
        } else {
            let (face, pole) = build_corner_patch_exact(
                patch.center,
                patch.radius,
                &patch.normals,
                &patch.arcs,
                patch.outward,
                patch.name.as_deref(),
                &mut take_id,
            )?;
            if let Some(edge) = pole {
                result.edges.push(edge);
            }
            face
        };
        let shell_index = result
            .shells
            .iter()
            .position(|shell| !shell.faces.is_empty())
            .ok_or(KernelRefusal::internal(KernelStage::Sew, "shell", "blend network: the solid has no shell to sew the corner patch into"))?;
        result.shells[shell_index].faces.push(face);
    }
    for patch in ribbon_patches {
        let ribs: Vec<RibbonRib<'_>> = patch
            .ribs
            .iter()
            .map(|(index, edge, pcurve)| RibbonRib {
                edge: edge.clone(),
                surface: &stripes[*index].rows.surface,
                pcurve: pcurve.clone(),
            })
            .collect();
        let (face, reading) = build_ribbon_star_patch(&ribs, patch.center, patch.outward, patch.name.as_deref(), &mut take_id)?;
        super::record_count("count.ribbon_star_fills", 1);
        if super::timing::enabled() && crate::profile::profile_enabled() {
            profile_line!(
                "blend.ribbon_star residual={:.3e} scale={:.3e} twist={:.3e}",
                reading.cross_derivative_residual, reading.cross_derivative_scale, reading.twist_discrepancy
            );
        }
        let shell_index = result
            .shells
            .iter()
            .position(|shell| !shell.faces.is_empty())
            .ok_or(KernelRefusal::internal(KernelStage::Sew, "shell", "blend network: the solid has no shell to sew the ribbon fill into"))?;
        result.shells[shell_index].faces.push(face);
    }
    for miter in pending_miters {
        // The sharp edge loses its corner end: it now starts at the seam's
        // exit on it, on both faces it borders — or, where the exit IS its far
        // vertex, it is gone.
        let consumed_whole = result
            .edges
            .iter()
            .find(|edge| edge.id == miter.sharp_edge)
            .is_some_and(|edge| {
                edge.start_vertex_id == miter.sharp_vertex || edge.end_vertex_id == miter.sharp_vertex
            });
        if consumed_whole {
            // An ASYMMETRIC miter whose connector ends on the far vertex is
            // the full-width case of the connector's face: the follower's
            // rail on its other mate lands on that vertex (a boss whose side
            // face is exactly one radius wide, the reported star rib whose
            // inner vertices sit one radius off the plate), the sharp edge is
            // consumed whole, and the connector takes its place on the
            // leader's other face — between the leader's rail and whatever
            // edge followed the sharp edge at the far vertex (spliced by
            // vertex adjacency below, since there is no sharp edge left to
            // be adjacent to).  Measured 2026-10-01 on that rib at r = 1:
            // refused here by name, the group fell to the cutter's capped
            // corners.
            consume_sharp_edge(&mut result, miter.sharp_edge);
            consumed_sharp_edge = true;
            if miter.connector.is_none() {
                continue;
            }
        } else {
            trim_edge_at(
                &mut result,
                miter.sharp_edge,
                miter.sharp_parameter,
                miter.vertex,
                miter.sharp_vertex,
            )?;
        }
        let Some((leader_index, face_id, connector_id, on_face)) = miter.connector else {
            continue;
        };
        // The connector sits on the leader's other face between the
        // leader's rail there (which ends at the seam's exit) and the
        // trimmed sharp edge (which starts where the connector ends).
        let leader = &stripes[leader_index];
        let rail_id = if leader.first.face.id == face_id {
            sewn[leader_index].cr_edge_id
        } else {
            sewn[leader_index].cs_edge_id
        }
        .ok_or_else(|| {
            format!(
                "{RAIL_COLLAPSE_UNSUPPORTED} the miter connector at vertex {} runs from a leader \
                 rail that collapsed to a point",
                miter.vertex
            )
        }).or_refuse(KernelStage::Refine, "ok_or_else")?;
        // The rail's two ends and the connector's start (the seam's exit),
        // read before the face is borrowed: with the sharp edge consumed
        // whole the connector is placed by this adjacency instead.
        let vertices_of = |result: &BrepSolid, id: u64| {
            result
                .edges
                .iter()
                .find(|edge| edge.id == id)
                .map(|edge| (edge.start_vertex_id, edge.end_vertex_id))
                .ok_or(KernelRefusal::internal(
                    KernelStage::Sew,
                    "connector_edges",
                    "blend network: a miter edge vanished before the connector was spliced",
                ))
        };
        let (rail_start, rail_end) = vertices_of(&result, rail_id)?;
        let (connector_start, _) = vertices_of(&result, connector_id)?;
        let coedge_id = take_id();
        let face = result
            .shells
            .iter_mut()
            .flat_map(|shell| &mut shell.faces)
            .find(|face| face.id == face_id)
            .ok_or(KernelRefusal::internal(KernelStage::Sew, "connector_face", "blend network: the connector's face is missing"))?;
        let mut spliced = false;
        for loop_record in &mut face.loops {
            let count = loop_record.coedges.len();
            let Some(rail_at) = loop_record
                .coedges
                .iter()
                .position(|coedge| coedge.edge_id == rail_id)
            else {
                continue;
            };
            let (insert_at, forward, pcurve) = if consumed_whole {
                // No sharp edge to be adjacent to: the connector follows the
                // rail when the rail's walk ends at the seam's exit, and
                // precedes it (reversed) when the walk starts there.
                let rail = &loop_record.coedges[rail_at];
                let (walk_start, walk_end) = if rail.forward {
                    (rail_start, rail_end)
                } else {
                    (rail_end, rail_start)
                };
                if walk_end == connector_start {
                    (rail_at + 1, true, on_face.clone())
                } else if walk_start == connector_start {
                    (rail_at, false, on_face.reversed().or_refuse(KernelStage::Refine, "reversed")?)
                } else {
                    return Err(KernelRefusal::internal(
                        KernelStage::Sew,
                        "connector_adjacency",
                        "blend network: the leader's rail does not end at the seam's exit on \
                         the connector's face",
                    ));
                }
            } else {
                let Some(sharp_at) = loop_record
                    .coedges
                    .iter()
                    .position(|coedge| coedge.edge_id == miter.sharp_edge)
                else {
                    continue;
                };
                if (rail_at + 1) % count == sharp_at {
                    // rail -> connector -> sharp: the walk runs from the rail's
                    // end (the seam's exit) to the sharp edge, the stored sense.
                    (rail_at + 1, true, on_face.clone())
                } else if (sharp_at + 1) % count == rail_at {
                    (sharp_at + 1, false, on_face.reversed().or_refuse(KernelStage::Refine, "reversed")?)
                } else {
                    return Err(
                        KernelRefusal::internal(KernelStage::Sew, "connector_adjacency", "blend network: the leader's rail and the sharp edge are not adjacent on \
                         the connector's face"),
                    );
                }
            };
            loop_record.coedges.insert(
                insert_at,
                CoedgeRecord {
                    id: coedge_id,
                    edge_id: connector_id,
                    forward,
                    pcurve,
                },
            );
            spliced = true;
            break;
        }
        if !spliced {
            return Err(
                KernelRefusal::internal(KernelStage::Sew, "connector_loop", "blend network: no loop on the connector's face holds the leader's rail and \
                 the sharp edge"),
            );
        }
    }
    for horn in pending_horns {
        let radius = vertex_radius_of(horn.vertex).unwrap_or(radius);
        trim_edge_at(
            &mut result,
            horn.sharp_edge,
            horn.sharp_parameter,
            horn.vertex,
            horn.pole_vertex,
        )?;
        let corner_point = solid
            .vertices
            .iter()
            .find(|vertex| vertex.id == horn.vertex)
            .ok_or(KernelRefusal::internal(KernelStage::Refine, "reentrant_vertex", "blend network: re-entrant vertex missing"))?
            .point;
        let [(index_a, arc_a, cap_a, cap_point_a, center_a), (index_b, arc_b, cap_b, cap_point_b, center_b)] =
            <[_; 2]>::try_from(horn.ends).map_err(|_| KernelRefusal::internal(KernelStage::Refine, "horn_ends", "blend network: a horn needs two ends"))?;
        // The cap arc: the torus's tangency with the cap, a circle of one
        // radius about the re-entrant vertex from one cap point to the other.
        // Tilted: the ball's contact with the cap runs only the pivot's
        // length (radius x crease angle); its chord stands on the cap to the
        // cap's curvature over that length, read by the pcurve's projection.
        let cap_arc = if horn.tilted {
            crate::make_line(cap_point_a, cap_point_b).or_refuse(KernelStage::Refine, "make_line")?
        } else {
            corner_section_arc(corner_point, radius, cap_point_a, cap_point_b)?
        };
        let cap_domain = cap_arc.domain().or_refuse(KernelStage::Refine, "domain")?;
        let cap_arc_id = take_id();
        result.edges.push(EdgeRecord {
            id: cap_arc_id,
            curve: cap_arc.clone(),
            t0: cap_domain[0],
            t1: cap_domain[1],
            start_vertex_id: cap_a,
            end_vertex_id: cap_b,
            degenerate: false,
            name: None,
        });
        // Splice it into the cap's loop between the two cap rails.
        let cap_forward_on_cap: bool;
        let horn_rail = |index: usize| {
            if stripes[index].first.face.id == horn.cap_face {
                sewn[index].cr_edge_id
            } else {
                sewn[index].cs_edge_id
            }
            .ok_or_else(|| {
                format!(
                    "{RAIL_COLLAPSE_UNSUPPORTED} a cap rail at the re-entrant vertex {} collapsed \
                     to a point",
                    horn.vertex
                )
            })
        };
        let (rail_a, mut rail_b) = (horn_rail(index_a).or_refuse(KernelStage::Refine, "horn_rail")?, horn_rail(index_b).or_refuse(KernelStage::Refine, "horn_rail")?);
        // Tilted (a creased mate's seam vertex): the corner is also the
        // cap's own periodic seam, and the ball's stop sits off that seam
        // by the support's slope, so one cap rail runs PAST the seam before
        // its stop. That rail is split where its pcurve crosses the seam
        // and the seam edge is trimmed there; the piece past it is carried
        // onto the seam's other side.
        if horn.tilted {
            for rail in [rail_a, rail_b] {
                if let Some(piece) = split_rail_at_cap_seam(&mut result, horn.cap_face, rail, horn.vertex, &mut take_id)? {
                    if rail == rail_b {
                        rail_b = piece;
                    } else {
                        return Err(KernelRefusal::unsupported(KernelStage::Sew, "tilted_horn_seam", "blend network: the tilted horn's leading cap rail crosses the cap's seam; not built"));
                    }
                }
            }
        }
        {
            let cap_face = result
                .shells
                .iter_mut()
                .flat_map(|shell| &mut shell.faces)
                .find(|face| face.id == horn.cap_face)
                .ok_or(KernelRefusal::internal(KernelStage::Sew, "cap_face", "blend network: the cap face is missing"))?;
            let cap_pcurve = {
                // The cap is planar here (checked above): its pcurve is the
                // projection of the arc's samples.
                let mut samples = Vec::with_capacity(17);
                let mut parameters = Vec::with_capacity(17);
                for k in 0..=16 {
                    let t = cap_domain[0] + (cap_domain[1] - cap_domain[0]) * k as f64 / 16.0;
                    let point = cap_arc.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
                    let projection = crate::project_point_to_surface(&cap_face.surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
                    samples.push(crate::Vec4::from_point(
                        Vec3::new(projection.u, projection.v, 0.0),
                        1.0,
                    ));
                    parameters.push(k as f64 / 16.0);
                }
                crate::fit::interpolate_homogeneous(&samples, 3, &parameters).or_refuse(KernelStage::Refine, "interpolate_homogeneous")?
            };
            let mut spliced: Option<bool> = None;
            for loop_record in &mut cap_face.loops {
                let count = loop_record.coedges.len();
                let (Some(at_a), Some(at_b)) = (
                    loop_record.coedges.iter().position(|c| c.edge_id == rail_a),
                    loop_record.coedges.iter().position(|c| c.edge_id == rail_b),
                ) else {
                    continue;
                };
                let (insert_at, forward, pcurve) = if (at_a + 1) % count == at_b {
                    (at_a + 1, true, cap_pcurve.clone())
                } else if (at_b + 1) % count == at_a {
                    (at_b + 1, false, cap_pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?)
                } else {
                    return Err(
                        KernelRefusal::internal(KernelStage::Sew, "cap_rails", "blend network: the two cap rails are not adjacent on the cap"),
                    );
                };
                loop_record.coedges.insert(
                    insert_at,
                    CoedgeRecord {
                        id: take_id(),
                        edge_id: cap_arc_id,
                        forward,
                        pcurve,
                    },
                );
                spliced = Some(forward);
                break;
            }
            let Some(forward) = spliced else {
                return Err(KernelRefusal::internal(KernelStage::Sew, "cap_loop", "blend network: no cap loop holds both cap rails"));
            };
            cap_forward_on_cap = forward;
        }
        // The horn-torus sector: the generatrix is the first stripe's section
        // arc run from the pole to its cap point, revolved about the concave
        // edge through the pole by the angle between the two ball centres.
        let radial_a = center_a.sub(horn.pole).normalized().or_refuse(KernelStage::Refine, "normalized")?;
        let radial_b = center_b.sub(horn.pole).normalized().or_refuse(KernelStage::Refine, "normalized")?;
        let sweep = radial_a.dot(radial_b).clamp(-1.0, 1.0).acos();
        if sweep < 1e-9 {
            return Err(KernelRefusal::internal(KernelStage::Refine, "horn_torus_sweep", "blend network: degenerate horn-torus sweep"));
        }
        let revolve_axis = if radial_a.cross(radial_b).dot(horn.axis) > 0.0 {
            horn.axis
        } else {
            horn.axis.scale(-1.0)
        };
        // The generatrix IS the stripe's end section, so the closure follows
        // the section's shape: a fillet revolves the ball's ARC and gets the
        // horn torus; a chamfer revolves the CHORD and gets a CONE, apex at
        // the pole. The pole is the same point at every pivot angle — it is
        // where the ball touches the concave edge — so the chord has one end
        // pinned to the axis, and sweeping that is a cone by construction.
        // `make_revolution` already takes a generatrix meeting the axis: the
        // horn torus is degenerate at the pole in exactly the same way.
        let generatrix = if chamfer {
            crate::make_line(horn.pole, cap_point_a).or_refuse(KernelStage::Refine, "make_line")?
        } else {
            corner_section_arc(center_a, radius, horn.pole, cap_point_a)?
        };
        let surface = if horn.tilted {
            tilted_horn_patch(&generatrix, &corner_section_arc(center_b, radius, horn.pole, cap_point_b)?, center_a, center_b, radius, solid)?
        } else {
            crate::make_revolution(horn.pole, revolve_axis, &generatrix, sweep).or_refuse(KernelStage::Refine, "make_revolution")?
        };
        // Sanity: the far meridian lands on the second stripe's cap point.
        let far = surface.evaluate(1.0, 1.0).or_refuse(KernelStage::Refine, "evaluate")?;
        if far.sub(cap_point_b).length() > 1e-6 * (1.0 + radius) {
            return Err(KernelRefusal::internal(KernelStage::Refine, "horn_torus_closure", format!(
                "blend network: the horn torus does not close on the second cap point ({:.3e} off)",
                far.sub(cap_point_b).length()
            )));
        }
        let pole_edge_id = take_id();
        result.edges.push(EdgeRecord {
            id: pole_edge_id,
            curve: crate::make_line(horn.pole, horn.pole).or_refuse(KernelStage::Refine, "make_line")?,
            t0: 0.0,
            t1: 1.0,
            start_vertex_id: horn.pole_vertex,
            end_vertex_id: horn.pole_vertex,
            degenerate: true,
            name: None,
        });
        let pl = |u0, v0, u1, v1| crate::sweep_topology::parameter_line(u0, v0, u1, v1);
        // Every shared edge is used with the sense OPPOSITE to its
        // neighbour: the blends use their section arcs forward (they were
        // stored in the blends' walk direction), the cap uses the cap arc
        // with the sense the splice gave it.  Those three senses fix the
        // walk; the u/v boundaries are: u = 0 meridian = arc_a, v = 1 = the
        // cap arc, u = 1 meridian = arc_b, v = 0 = the pole.
        let a_walks_down = arc_a.start_vertex_id == horn.pole_vertex; // forward=false walks cap_a -> pole
        let b_walks_up = arc_b.end_vertex_id == horn.pole_vertex; // forward=false walks pole -> cap_b
        let cap_walks_back = cap_forward_on_cap; // horn uses !cap_forward: cap_b -> cap_a iff the cap walked a -> b
        if a_walks_down != b_walks_up || a_walks_down != cap_walks_back {
            return Err(
                KernelRefusal::internal(KernelStage::Sew, "horn_boundary_walk", "blend network: the blends and the cap do not walk the horn's boundary \
                 consistently"),
            );
        }
        let coedges = if a_walks_down {
            // cap_a -> pole -> (pole edge) -> cap_b -> cap_a
            vec![
                CoedgeRecord {
                    id: take_id(),
                    edge_id: arc_a.id,
                    forward: false,
                    pcurve: pl(0.0, 1.0, 0.0, 0.0).or_refuse(KernelStage::Refine, "pl")?,
                },
                CoedgeRecord {
                    id: take_id(),
                    edge_id: pole_edge_id,
                    forward: true,
                    pcurve: pl(0.0, 0.0, 1.0, 0.0).or_refuse(KernelStage::Refine, "pl")?,
                },
                CoedgeRecord {
                    id: take_id(),
                    edge_id: arc_b.id,
                    forward: false,
                    pcurve: pl(1.0, 0.0, 1.0, 1.0).or_refuse(KernelStage::Refine, "pl")?,
                },
                CoedgeRecord {
                    id: take_id(),
                    edge_id: cap_arc_id,
                    forward: false,
                    pcurve: pl(1.0, 1.0, 0.0, 1.0).or_refuse(KernelStage::Refine, "pl")?,
                },
            ]
        } else {
            // pole -> cap_a -> cap_b -> pole -> (pole edge)
            vec![
                CoedgeRecord {
                    id: take_id(),
                    edge_id: arc_a.id,
                    forward: false,
                    pcurve: pl(0.0, 0.0, 0.0, 1.0).or_refuse(KernelStage::Refine, "pl")?,
                },
                CoedgeRecord {
                    id: take_id(),
                    edge_id: cap_arc_id,
                    forward: true,
                    pcurve: pl(0.0, 1.0, 1.0, 1.0).or_refuse(KernelStage::Refine, "pl")?,
                },
                CoedgeRecord {
                    id: take_id(),
                    edge_id: arc_b.id,
                    forward: false,
                    pcurve: pl(1.0, 1.0, 1.0, 0.0).or_refuse(KernelStage::Refine, "pl")?,
                },
                CoedgeRecord {
                    id: take_id(),
                    edge_id: pole_edge_id,
                    forward: true,
                    pcurve: pl(1.0, 0.0, 0.0, 0.0).or_refuse(KernelStage::Refine, "pl")?,
                },
            ]
        };
        // Orient at the tangency with the common cap. This works for both
        // material sides of the rolling ball and for every radius.
        let contact = surface.evaluate(0.5, 1.0).or_refuse(KernelStage::Refine, "evaluate")?;
        let cap = solid.shells.iter().flat_map(|shell| &shell.faces)
            .find(|face| face.id == horn.cap_face)
            .ok_or(KernelRefusal::internal(KernelStage::Refine, "cap_face", "blend network: missing horn cap"))?;
        let projection = crate::project_point_to_surface(&cap.surface, contact)
            .or_refuse(KernelStage::Refine, "project")?;
        let cap_normal = cap.surface.normal(projection.u, projection.v)
            .or_refuse(KernelStage::Refine, "normal")?;
        let outward = if cap.same_sense { cap_normal } else { cap_normal.scale(-1.0) };
        let surface_normal = surface.normal(0.5, 1.0).or_refuse(KernelStage::Refine, "normal")?;
        let same_sense = surface_normal.dot(outward) > 0.0;
        let loop_id = take_id();
        let face = FaceRecord {
            id: take_id(),
            surface,
            same_sense,
            loops: vec![crate::topology::LoopRecord {
                id: loop_id,
                coedges,
            }],
            name: horn.name,
        };
        let shell_index = result
            .shells
            .iter()
            .position(|shell| !shell.faces.is_empty())
            .ok_or(KernelRefusal::internal(KernelStage::Sew, "shell", "blend network: the solid has no shell to sew the horn torus into"))?;
        result.shells[shell_index].faces.push(face);
    }
    for pending in pending_mixed {
        sew_mixed_star(&mut result, solid, &mut take_id, &stripes, &sewn, pending.vertex, &pending.mixed, &pending.arcs, [pending.v_a, pending.v_b, pending.w_a, pending.w_b], pending.name)?;
    }
    for flush in pending_flush {
        for (seam_id, parameter, rim) in flush.seam_trims {
            trim_edge_at(&mut result, seam_id, parameter, flush.vertex, rim)?;
        }
    }
    for cap in pending_caps {
        sew_cap(&mut result, &mut take_id, cap)?;
    }
    super::taper_runout::sew_taper_ends(&mut result, &mut take_id, pending_tapers)?;
    // A miter at a revolved pole cuts away its degenerate boundary as well
    // as the two selected edges. The replacement rails already meet at their
    // new rim; retaining the old point edge would reopen that face's loop.
    let mut consumed_poles = Vec::new();
    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
        for ring in &face.loops {
            let n = ring.coedges.len();
            for (i, coedge) in ring.coedges.iter().enumerate() {
                let edge = result.edges.iter().find(|e| e.id == coedge.edge_id)
                    .ok_or(KernelRefusal::internal(KernelStage::Sew, "pole_edge",
                        "blend network: pole cleanup references a missing edge"))?;
                if !edge.degenerate || n < 3 {
                    continue;
                }
                let (_, before) = coedge_walk(&result, &ring.coedges[(i + n - 1) % n])?;
                let (after, _) = coedge_walk(&result, &ring.coedges[(i + 1) % n])?;
                if before == after && before != edge.start_vertex_id {
                    consumed_poles.push(edge.id);
                }
            }
        }
    }
    for edge in consumed_poles {
        // A shared degenerate edge may still bound another face's chart.
        // Only this face's isolated pole is known to have been consumed.
        let uses = result.shells.iter().flat_map(|shell| &shell.faces)
            .flat_map(|face| &face.loops).flat_map(|ring| &ring.coedges)
            .filter(|coedge| coedge.edge_id == edge).count();
        if uses == 1 {
            consume_sharp_edge(&mut result, edge);
        }
    }
    // Full-width corners: every collapsed rail's rims are one vertex, and the
    // faces that identification leaves without area go.  The passes below see
    // the collapsed body, so a mate or a rail that went is left out of them
    // exactly as a consumed one is.
    let identified: Vec<(u64, u64)> =
        sewn.iter().flat_map(|stripe| stripe.identified.iter().copied()).collect();
    let collapse = collapse_full_width(
        solid,
        &mut result,
        &identified,
        consumed_sharp_edge,
        consumed_band(solid),
    )?;
    let face_exists = |result: &BrepSolid, id: u64| {
        result.shells.iter().flat_map(|shell| &shell.faces).any(|face| face.id == id)
    };
    for stripe in &mut sewn {
        stripe.cr_edge_id = stripe.cr_edge_id.map(|id| collapse.edge(id));
        stripe.cs_edge_id = stripe.cs_edge_id.map(|id| collapse.edge(id));
    }
    for (index, stripe) in stripes.iter().enumerate() {
        for (side, face) in [stripe.first.face.id, stripe.second.face.id].into_iter().enumerate() {
            sewn[index].consumed[side] |= !face_exists(&result, face);
        }
    }
    // A rail that wrapped a PERIODIC mate crosses that carrier's seam
    // meridian; split it there and trim the seam edge the blend just ate the
    // end of, so the carrier keeps its seam-in-one-loop structure.
    //
    // A mate the stripe CONSUMED whole is gone, and its rail is the existing
    // edge the blend was sewn onto: there is no carrier left to split and no
    // rail this operation built, so both are left out.  The face across that
    // edge keeps the loop it had, which already closed.
    let mut rail_faces: Vec<(u64, u64)> = Vec::with_capacity(sewn.len() * 2);
    for (index, stripe) in stripes.iter().enumerate() {
        for (side, face, rail) in [
            (0, stripe.first.face.id, sewn[index].cr_edge_id),
            (1, stripe.second.face.id, sewn[index].cs_edge_id),
        ] {
            if let (false, Some(rail)) = (sewn[index].consumed[side], rail) {
                rail_faces.push((face, rail));
            }
        }
    }
    let mut rail_edges: Vec<u64> = rail_faces.iter().map(|(_, rail)| *rail).collect();
    let mut seam_faces: Vec<u64> = rail_faces.iter().map(|(face, _)| *face).collect();
    seam_faces.sort_unstable();
    seam_faces.dedup();
    for face_id in seam_faces {
        // One seam pair per periodic direction, so a second pass only ever
        // finds the u-and-v case; the bound keeps a mis-detection from looping.
        for _ in 0..2 {
            let Some(plan) = plan_carrier_seam_split(&result, &rail_edges, face_id)? else {
                break;
            };
            if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                match &plan {
                    CarrierSeamRepair::Split(plan) => eprintln!(
                        "carrier seam: face {face_id} seam {} crossed by rail {} — split",
                        plan.seam_edge, plan.rail_edge
                    ),
                    CarrierSeamRepair::Trim(plan) => eprintln!(
                        "carrier seam: face {face_id} seam {} met by rails at vertex {} — re-footed",
                        plan.seam_edge, plan.rim_vertex
                    ),
                }
            }
            match plan {
                CarrierSeamRepair::Split(plan) => {
                    let original_rail = plan.rail_edge;
                    let pieces = apply_carrier_seam_split(&mut result, &mut take_id, plan)?;
                    // Both descendants retain this operation's constructed-rail
                    // provenance. A second retained meridian can cross one piece of
                    // the very rail the first seam split replaced.
                    rail_edges.retain(|&edge| edge != original_rail);
                    rail_edges.extend(pieces);
                }
                // The rails already meet on the meridian: no rail changes, the
                // seam is re-footed on their shared rim vertex.
                CarrierSeamRepair::Trim(plan) => apply_carrier_seam_trim(&mut result, plan)?,
            }
        }
    }
    closures_timing.stop();
    surgery_timing.stop();
    let restriction_timing = super::BlendTimer::start("timing.restriction_ms");
    // Restrict every stripe against the THIRD faces it crosses. ---- The
    // surgery above re-trimmed each stripe's two MATES and nothing else, which
    // is complete only while the swept volume touches nothing but them. Where a
    // third face crosses it, the stripe is trimmed against that face directly
    // here — rails located from the blend face's own loop, because the seam
    // split above may already have replaced the ids `sewn` recorded. A crossing
    // this lane does not construct refuses BY NAME, and the group falls to the
    // cutter exactly as it did before (item 1). A stripe whose blend face
    // collapsed (a full-width star's bevel) swept no area, so nothing can cross
    // it.
    let stripe_faces: Vec<StripeFaces> = stripes
        .iter()
        .enumerate()
        .filter(|(index, _)| face_exists(&result, sewn[*index].blend_face_id))
        .map(|(index, stripe)| {
            Ok(StripeFaces {
                blend_face: sewn[index].blend_face_id,
                mates: [stripe.first.face.id, stripe.second.face.id],
                consumed: sewn[index].consumed,
                convex: edge_is_convex(stripe.edge, &stripe.first, &stripe.second)?,
                size: stripe.law.largest(),
            })
        })
        .collect::<Result<Vec<_>, KernelRefusal>>()?;
    if std::env::var("BREP_NO_THIRD_FACE_TRIM").is_err() {
        let policy = crate::KernelTolerances::for_solid(solid, 1e-7);
        let third_faces_timing = super::BlendTimer::start("timing.restriction.third_faces_ms");
        let fragments = restrict_third_faces(&mut result, &mut take_id, &stripe_faces, &policy)?;
        third_faces_timing.stop();
        // The closures — every face the network built that is not a stripe's
        // wall — against the voids under them (`restrict_closures`).  A piece
        // a restriction cut off a mate is an input face, not a closure.
        let original_faces: Vec<u64> = solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .map(|face| face.id)
            .chain(fragments)
            .collect();
        let walls: Vec<u64> = sewn.iter().map(|stripe| stripe.blend_face_id).collect();
        let closures: Vec<u64> = result
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .map(|face| face.id)
            .filter(|id| !original_faces.contains(id) && !walls.contains(id))
            .collect();
        let closures_timing = super::BlendTimer::start("timing.restriction.closures_ms");
        super::restrict::restrict_closures(&mut result, &mut take_id, &closures, solid, radius, &policy)?;
        closures_timing.stop();
    }

    restriction_timing.stop();
    let gate_timing = super::BlendTimer::start("timing.network_gate_ms");
    prune_orphan_vertices(&mut result);
    if !collapse.merged_edges.is_empty() {
        let blend_faces: Vec<u64> = sewn.iter().map(|stripe| stripe.blend_face_id).collect();
        result = absorb_cosurface_halves(result, &collapse.merged_edges, &blend_faces)?;
    }
    let snap = sewn.iter().fold(0.0f64, |worst, stripe| worst.max(stripe.snap));
    check_snap_closure(solid, &result, snap)?;
    if collapse.changed() {
        check_collapse_closure(solid, &result)?;
    }
    if let Ok(path) = std::env::var("BREP_DEBUG_NETWORK_DUMP") {
        // Diagnostic: the sewn body before the gate, for an invalid-topology
        // read (stopped-end rollover lane, 2026-11-02).
        if let Ok(text) = serde_json::to_string(&result) {
            let _ = std::fs::write(&path, text);
        }
    }
    let built = crossings.gate(result)?;
    gate_timing.stop();
    // Only a network that BUILT owes its reports. Each binds to its wall on
    // the built body by exact name and exact surface (the consumer's own
    // rule); a wall a later step replaced (absorbed, rebuilt) cannot carry a
    // typed report, so its deficit is named in a note instead -- never
    // dropped, never claimed met.
    for report in owed {
        let carried = built.shells.iter().flat_map(|shell| &shell.faces).any(|face| {
            face.name == report.name && super::same_surface(&face.surface, &report.surface)
        });
        if carried {
            super::record_wall_model_report(super::WallModelReport {
                name: report.name,
                surface: report.surface,
                request: report.bar,
                residual: report.measured,
                detail: Some(report.detail),
                budget: report.reason,
            });
        } else {
            super::record_blend_note(format!(
                "blend network: edge {}'s shipped wall owes a {:?} report ({:.3e} against {:.3e}; {}), but a \
                 later network step replaced its face, so it is named here instead",
                report.edge, report.reason.reason, report.measured, report.bar, report.detail
            ));
        }
    }
    Ok(built)
}

/// A FILLET stripe's shipped-wall report, owed until its face is bound.
struct OwedWallReport {
    edge: u64,
    name: Option<String>,
    surface: crate::NurbsSurface,
    reason: crate::ApproximationBudget,
    bar: f64,
    measured: f64,
    detail: String,
}

/// What one rail of a stripe SHIPS between its two end plans' parameters.
#[derive(Clone, Copy, Debug)]
enum ShippedSpan {
    /// A window `[start, finish]` of the rows' parameters.
    Window([f64; 2]),
    /// A VALIDATED full-width collapse: the stops meet or cross, and the rail
    /// between them is within `consumed_band` (the same rule, read the same
    /// way, as the sewing loop's pinch check, which refuses anything wider).
    Collapsed,
    /// Neither: a stop that is not finite, lies outside the marched rows, or
    /// a strip that cannot be read. Never taken for a collapse.
    Unread,
}

fn shipped_span(parameters: &[f64], row: &NurbsCurve, start: f64, finish: f64, band: f64) -> ShippedSpan {
    let (Some(&first), Some(&last)) = (parameters.first(), parameters.last()) else {
        return ShippedSpan::Unread;
    };
    let inside = |t: f64| t.is_finite() && t >= first && t <= last;
    if !(inside(start) && inside(finish)) {
        return ShippedSpan::Unread;
    }
    if finish > start {
        return ShippedSpan::Window([start, finish]);
    }
    let strip = row.evaluate(finish).ok().zip(row.evaluate(start).ok()).map(|(a, b)| a.sub(b).length());
    match strip {
        Some(strip) if strip.is_finite() && strip <= band => ShippedSpan::Collapsed,
        _ => ShippedSpan::Unread,
    }
}

/// What a stripe's SHIPPED wall owes, read on the spans its end plans trim
/// it to: `None` when nothing ships (BOTH rails a validated collapse:
/// [`ShippedSpan::Collapsed`]) or when it meets its bars (and, a fillet,
/// `model`). An unread span is never a collapse: it is an unread rail.
/// Otherwise the
/// typed budget, the bar and the measured value, and the detail text:
/// - rails or wall over their acceptance bars, or unreadable, on the SHIPPED
///   windows -- whether or not the ladder accepted the vertex window -- is an
///   acceptance deficit (`Unaccepted` / `Unread`, `blend.wall_acceptance`);
/// - an accepted shipped wall short of `model` is the construction request's
///   (`blend.wall_model`), with the reason its ladder stopped.
/// A chamfer's wall is not judged (rails only). On an edge stationary at a
/// vertex a rail over its bar is reported UNREAD.
fn shipped_wall_report(
    stripe: &Stripe,
    spans: [ShippedSpan; 2],
    radius: f64,
    solid: &BrepSolid,
) -> Option<(crate::ApproximationBudget, f64, f64, String)> {
    if spans.iter().all(|span| matches!(span, ShippedSpan::Collapsed)) {
        return None;
    }
    let windows = spans.map(|span| match span {
        ShippedSpan::Window(window) => Some(window),
        ShippedSpan::Collapsed | ShippedSpan::Unread => None,
    });
    let measure = &stripe.measure;
    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
    let rail_bar = 0.5 * tolerances.intersection_fit;
    let (wall_bar, model) = (tolerances.intersection_fit, tolerances.model);
    let rails_timing = super::BlendTimer::start("timing.surgery.wall_report.rails_ms");
    let (rails, rail_samples) = match measure.rail_reader.as_ref() {
        Some(reader) => reader.borrow_mut().read(windows),
        None => rails_on_shipped_windows(
        &stripe.rows,
        &measure.parameters,
        &measure.stations,
        [&stripe.first.face.surface, &stripe.second.face.surface],
        windows,
    ),
    };
    rails_timing.stop();
    // The wall over the envelope of what ships (a collapsed rail ships no
    // span of its own); with an unread rail, or nothing to envelope, no wall
    // interval is read and the wall is unread.
    let envelope = windows.iter().flatten().fold(None, |envelope: Option<[f64; 2]>, window| {
        Some(envelope.map_or(*window, |known| [known[0].min(window[0]), known[1].max(window[1])]))
    });
    let any_unread = spans.iter().any(|span| matches!(span, ShippedSpan::Unread));
    let walls_timing = super::BlendTimer::start("timing.surgery.wall_report.walls_ms");
    let walls_why = match (measure.wall_check, envelope, any_unread) {
        (true, Some(envelope), false) if stripe.rows.revolution_axis.is_some() => {
            exact_revolution_wall_readings(&stripe.rows, &measure.parameters, envelope, radius)
        }
        (true, Some(envelope), false) if measure.exact_lane => {
            exact_extrusion_wall_readings(&stripe.rows, &measure.parameters, envelope, radius)
        }
        (true, Some(envelope), false) => {
            open_wall_readings_why(&stripe.rows, &measure.parameters, &measure.stations, envelope, &measure.dense, radius)
        }
        _ => Vec::new(),
    };
    walls_timing.stop();
    let first_unread = walls_why.iter().find_map(|wall| wall.as_ref().err().cloned());
    let walls: Vec<Option<f64>> = walls_why.into_iter().map(|wall| wall.ok()).collect();
    let ladder = &measure.ladder_reading;
    let mut shipped = OpenRungReading {
        station_count: ladder.station_count,
        stations: ladder.stations,
        rails,
        rail_samples,
        walls,
        first_unread,
        refine_exit: ladder.refine_exit,
        inserted: ladder.inserted,
    };
    // Rails READ: a finite, nonnegative reading, every shipped window
    // sampled, a validated collapsed rail counting as read with nothing to
    // sample, an unread span never.
    let rails_read = |reading: &OpenRungReading| {
        reading.rails.is_finite()
            && reading.rails >= 0.0
            && spans.iter().zip(reading.rail_samples).all(|(span, samples)| match span {
                ShippedSpan::Window(_) => samples > 0,
                ShippedSpan::Collapsed => true,
                ShippedSpan::Unread => false,
            })
    };
    if measure.stationary_end && !(rails_read(&shipped) && shipped.rails <= rail_bar) {
        shipped.rails = f64::NAN;
    }
    let read = rails_read(&shipped);
    let accepted = read
        && shipped.rails <= rail_bar
        && (!measure.wall_check || shipped.worst_wall().is_some_and(|wall| wall <= wall_bar));
    let rungs_past_first = (ladder.station_count / STATIONS).trailing_zeros() as usize;
    let scope = format!(
        "read on the shipped spans {spans:?}; the ladder {} the vertex window at {} stations a rung (rails {:.3e}, wall {:?}); \
         the shipped rung's local rail refinement ended {:?} with {} stations inserted",
        if measure.ladder_accepted { "accepted" } else { "never accepted" },
        ladder.station_count,
        ladder.rails,
        ladder.worst_wall(),
        ladder.refine_exit,
        ladder.inserted
    );
    let budget = |reason: crate::BudgetReason, rounds_used: usize| crate::ApproximationBudget {
        reason,
        rounds_used,
        rounds_limit: OPEN_REQUEST_RUNGS,
        stations: ladder.stations,
        station_limit: REFINE_STATION_FACTOR * (MAX_OPEN_STATIONS + 1),
        mechanism: crate::BudgetMechanism::StationRungs,
        measured_component: crate::MeasuredComponent::Wall,
        unread: 0,
    };
    if !accepted {
        let (reason, bar, measured, deficit) =
            acceptance_deficit(&shipped, rail_bar, wall_bar, measure.wall_check, read, "the shipped windows fail acceptance");
        let rounds = if measure.ladder_accepted { measure.request_rungs } else { rungs_past_first };
        return Some((budget(reason, rounds), bar, measured, format!("{deficit}; {scope}")));
    }
    if measure.wall_check {
        let declared = shipped.worst_wall()?;
        if !(declared <= model) {
            let reason = measure.unmet.unwrap_or(crate::BudgetReason::StationCeiling);
            return Some((budget(reason, measure.request_rungs), model, declared, scope));
        }
    }
    None
}


/// Where a collapse merged the rails of two blends that ride ONE carrier —
/// the front and back rounds of a full-width channel are the two halves of one
/// cylinder, meeting along the top face's collapsed slit — make them one face,
/// and join the section arcs split at that rail's ends.  The merge is the
/// boolean's own same-carrier merge at its model tolerance
/// (`absorb_faces_into_carriers`, as the cutter scaffold settles its caps),
/// which moves no boundary; a merge its checks refuse leaves the two halves
/// standing, which is a valid body.  The absorbed half's name goes with it.
fn absorb_cosurface_halves(
    result: BrepSolid,
    merged_edges: &[(u64, u64)],
    blend_faces: &[u64],
) -> Result<BrepSolid, KernelRefusal> {
    let tolerance =
        crate::KernelTolerances::for_solid(&result, crate::BooleanOptions::default().tolerance)
            .model;
    let mut absorbed = rustc_hash::FxHashSet::default();
    let mut rail_ends = rustc_hash::FxHashSet::default();
    for &(_, kept) in merged_edges {
        let faces: Vec<&FaceRecord> = result
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter(|face| {
                face.loops
                    .iter()
                    .flat_map(|loop_record| &loop_record.coedges)
                    .any(|coedge| coedge.edge_id == kept)
            })
            .collect();
        let [first, second] = faces[..] else {
            continue;
        };
        if !(blend_faces.contains(&first.id) && blend_faces.contains(&second.id)) {
            continue;
        }
        if !crate::face_merge::faces_are_cosurface(first, second, tolerance)
            ?
        {
            continue;
        }
        absorbed.insert(first.id.max(second.id));
        if let Some(edge) = result.edges.iter().find(|edge| edge.id == kept) {
            rail_ends.insert(edge.start_vertex_id);
            rail_ends.insert(edge.end_vertex_id);
        }
    }
    if absorbed.is_empty() {
        return Ok(result);
    }
    let Ok(merged) = crate::face_merge::absorb_faces_into_carriers(&result, tolerance, &absorbed)
    else {
        return Ok(result);
    };
    Ok(match crate::coalesce::merge_curve_continuation_edges_at(&merged, tolerance, &rail_ends) {
        Ok(joined) if joined.validate().is_empty() => joined,
        _ => merged,
    })
}

/// Delete a sharp edge a full-width miter consumed whole: the seam closed on
/// its far vertex, so both faces it bordered lose it (and, consumed to their
/// far edges, collapse with it in `collapse_full_width`).
fn consume_sharp_edge(result: &mut BrepSolid, edge_id: u64) {
    for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
        for loop_record in &mut face.loops {
            loop_record.coedges.retain(|coedge| coedge.edge_id != edge_id);
        }
    }
    result.edges.retain(|edge| edge.id != edge_id);
}

/// A cap's bulkhead, waiting for the stripes to be in so its arc and legs
/// exist: the plane's frame and the three edges in the bulkhead's own walk.
struct PendingCap {
    plane_origin: Vec3,
    plane_u: Vec3,
    plane_v: Vec3,
    plane_normal: Vec3,
    /// (edge id, stored start vertex, stored end vertex)
    arc: (u64, u64, u64),
    /// Each leg as a chain rim -> sharp vertex: one piece on the mate, or
    /// (stopped-end rollover) a piece per neighbour face the cap plane
    /// crosses on its way to the vertex.
    first_leg: Vec<(u64, u64, u64)>,
    second_leg: Vec<(u64, u64, u64)>,
    /// The bulkhead's outward normal must point along this (away from the
    /// stripe): the sliver's cross-section faces the continuing edge.
    outward: Vec3,
    name: Option<String>,
}

/// Plan a cap at `vertex`: commit the section curve and its two carrier
/// legs to the sharp vertex, and record the planar bulkhead. The boolean
/// requires validation when the curved-carrier construction was used.
#[allow(clippy::too_many_arguments)]
/// A stripe's stopped-end rollover: its re-marched rows, the crossing per
/// side and the cap's leg chains (filled once the cap is planned).
struct RolledEnd {
    rows: FittedRows,
    sides: [Option<super::rollover::RolledSide>; 2],
    chains: [Vec<super::rollover::LegPiece>; 2],
}

/// The stopped-end rollover of `stripe`'s finish end (switch on, the end the
/// network caps): `None` when no track leaves its carrier across a tangent
/// edge before the vertex; else the rows refitted over the re-marched tail
/// (`rollover::stopped_end_tail`), parameter points of the tail read on the
/// mates' extensions, broken at the crossing stations, and the crossing per
/// side with its row parameter.
fn plan_stopped_end_rollover(
    solid: &BrepSolid,
    stripe: &Stripe,
    chamfer: bool,
) -> Result<Option<(FittedRows, [Option<super::rollover::RolledSide>; 2])>, KernelRefusal> {
    let edge = stripe.edge;
    let measure = &stripe.measure;
    let radius = stripe.end_radius[1].abs().max(stripe.end_radius[0].abs());
    let crossings = super::rollover::stopped_end_crossings(solid, &measure.stations, [&stripe.first, &stripe.second], radius, measure.vertex_indices)?;
    if crossings.is_empty() {
        return Ok(None);
    }
    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
    if debug {
        for crossing in &crossings {
            eprintln!(
                "stopped-end rollover: edge {} side {} leaves face {} across edge {} onto face {} between stations {:?} (vertex station {}) at ({:.6},{:.6},{:.6})",
                edge.id, crossing.side, crossing.mate_face_id, crossing.edge_id, crossing.neighbour_face_id, crossing.stations, measure.vertex_indices[1],
                crossing.point.x, crossing.point.y, crossing.point.z
            );
        }
    }
    let law = &stripe.law;
    let radius_at = |t: f64| -> f64 {
        match law.constant() {
            Some(radius) => radius,
            None => law.at_fraction((t - edge.t0) / (edge.t1 - edge.t0)),
        }
    };
    let scale = super::stations::march_model_scale(&edge.curve, edge.t0, edge.t1, radius)?;
    let mut rolled = super::rollover::stopped_end_tail(
        solid, edge, [&stripe.first, &stripe.second], &radius_at, scale, &measure.stations, &measure.dense.station_ts, measure.vertex_indices, crossings,
    )?;
    // The row parameters are normalised chord fractions; the start end was
    // planned on the stripe's rows, so the untouched stations keep their
    // parameters exactly (the fit breaks at the crossing station, which
    // leaves the rows before it bit-identical) and the domain ends past 1
    // by the tail's change of length.
    let parameters = station_parameters(&rolled.stations);
    let ratio = match rolled.breaks.first() {
        Some(&first_break) if first_break > 1 && parameters[first_break - 1] > 0.0 => measure.parameters[first_break - 1] / parameters[first_break - 1],
        _ => 1.0,
    };
    for side in rolled.sides.iter_mut().flatten() {
        side.row_parameter = parameters[side.station] * ratio;
    }
    // The rows' support pcurves stay on the MATES: a tail station's parameter
    // point is read on the mate's extension (the surgery draws the tail's
    // rail on the neighbour from the 3-D rail).
    let mut on_mates = rolled.stations.clone();
    for (side, mate) in [&stripe.first, &stripe.second].into_iter().enumerate() {
        let Some(rolled_side) = &rolled.sides[side] else { continue };
        for station in on_mates.iter_mut().skip(rolled_side.station) {
            let point = if side == 0 { station.p1 } else { station.p2 };
            let projection = crate::project_point_to_surface(&mate.face.surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
            if side == 0 { station.uv1 = [projection.u, projection.v]; } else { station.uv2 = [projection.u, projection.v]; }
        }
    }
    let extrusion = law.constant().and_then(|_| extrusion_direction(edge, &stripe.first, &stripe.second));
    let mut rows = fit_open_rows_breaking_at(&on_mates, &parameters, chamfer, Some(rolled.vertex_indices), extrusion, &rolled.breaks)?;
    rows.vertex_stations = vertex_stations(&parameters, rolled.vertex_indices);
    // The fit runs on normalised parameters; the rows are then reparameterised
    // by `ratio` so the untouched stations keep the parameters the start end
    // was planned with (affine knot maps change no geometry).
    if (ratio - 1.0).abs() > 0.0 {
        let scale_curve = |curve: &NurbsCurve| -> Result<NurbsCurve, KernelRefusal> {
            NurbsCurve::new(curve.degree, curve.knots.iter().map(|knot| knot * ratio).collect(), curve.control_points.clone()).or_refuse(KernelStage::Refine, "NurbsCurve::new")
        };
        rows.cr = scale_curve(&rows.cr)?;
        rows.cs = scale_curve(&rows.cs)?;
        rows.cr_pcurve = scale_curve(&rows.cr_pcurve)?;
        rows.cs_pcurve = scale_curve(&rows.cs_pcurve)?;
        if let Some(center) = &rows.center {
            rows.center = Some(scale_curve(center)?);
        }
        rows.surface = crate::NurbsSurface::new(
            rows.surface.degree_u,
            rows.surface.degree_v,
            rows.surface.knots_u.iter().map(|knot| knot * ratio).collect(),
            rows.surface.knots_v.clone(),
            rows.surface.control_points.clone(),
        ).or_refuse(KernelStage::Refine, "NurbsSurface::new")?;
        rows.u_domain = [rows.u_domain[0] * ratio, rows.u_domain[1] * ratio];
        rows.vertex_stations = rows.vertex_stations.map(|[a, b]| [a * ratio, b * ratio]);
    }
    if debug {
        for (side, mate) in [&stripe.first, &stripe.second].into_iter().enumerate() {
            let Some(rolled_side) = &rolled.sides[side] else { continue };
            let neighbour = solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == rolled_side.neighbour_face_id);
            let row = if side == 0 { &rows.cr } else { &rows.cs };
            let (a, b) = (parameters[rolled_side.station] * ratio, parameters[rolled.vertex_indices[1]] * ratio);
            let (mut off_neighbour, mut off_mate) = (0.0f64, 0.0f64);
            for k in 0..=20 {
                let u = a + (b - a) * k as f64 / 20.0;
                let point = row.evaluate(u).or_refuse(KernelStage::Refine, "evaluate")?;
                if let Some(neighbour) = neighbour {
                    off_neighbour = off_neighbour.max(crate::project_point_to_surface(&neighbour.surface, point).map(|p| p.distance).unwrap_or(f64::NAN));
                }
                off_mate = off_mate.max(crate::project_point_to_surface(&mate.face.surface, point).map(|p| p.distance).unwrap_or(f64::NAN));
            }
            eprintln!(
                "stopped-end rollover: edge {} side {} tail rail over rows [{a:.6}, {b:.6}] ({} stations, {} in all, vertex station {}): {off_neighbour:.3e} off face {}, {off_mate:.3e} off mate {}",
                edge.id, side, rolled.stations.len() - rolled_side.station, rolled.stations.len(), rolled.vertex_indices[1], rolled_side.neighbour_face_id, mate.face.id
            );
        }
    }
    Ok(Some((rows, rolled.sides)))
}

#[allow(clippy::too_many_arguments)]
fn plan_cap_end(
    solid: &BrepSolid,
    result: &mut BrepSolid,
    take_id: &mut dyn FnMut() -> u64,
    stripe: &Stripe,
    rows: &FittedRows,
    vertex: u64,
    at_start: bool,
    radius: f64,
    pending: &mut Vec<PendingCap>,
    tail: [Option<&super::rollover::RolledSide>; 2],
) -> Result<(CapEnd, bool, [Vec<super::rollover::LegPiece>; 2]), KernelRefusal> {
    // The carrier each leg is drawn on: the mate, or the neighbour the
    // track rolled onto at a stopped end (the rim vertex lies there).
    let face_by_id = |id: u64| -> Result<&FaceRecord, KernelRefusal> {
        solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == id)
            .ok_or_else(|| KernelRefusal::internal(KernelStage::Refine, "cap_carrier", format!("blend network: cap carrier face {id} missing")))
    };
    let carriers: [&FaceRecord; 2] = [
        match tail[0] { Some(rolled) => face_by_id(rolled.neighbour_face_id)?, None => stripe.first.face },
        match tail[1] { Some(rolled) => face_by_id(rolled.neighbour_face_id)?, None => stripe.second.face },
    ];
    let sharp_point = solid
        .vertices
        .iter()
        .find(|candidate| candidate.id == vertex)
        .ok_or(KernelRefusal::internal(KernelStage::Refine, "cap_vertex", "blend network: cap vertex missing"))?
        .point;
    let station = rows
        .vertex_stations
        .ok_or(KernelRefusal::internal(KernelStage::Refine, "vertex_stations", "blend network: stripe rows carry no vertex stations"))?[usize::from(!at_start)];
    if !(station > RIM_MARGIN && station < 1.0 - RIM_MARGIN) {
        return Err(KernelRefusal::internal(KernelStage::Refine, "vertex_section", format!(
            "blend network: edge {}'s vertex section lands at {station:.6}, outside the \
             marched rows",
            stripe.edge.id
        )));
    }
    let first_point = rows.cr.evaluate(station).or_refuse(KernelStage::Refine, "evaluate")?;
    let second_point = rows.cs.evaluate(station).or_refuse(KernelStage::Refine, "evaluate")?;
    let center = rows
        .center
        .as_ref()
        .ok_or(KernelRefusal::internal(KernelStage::Refine, "centre_path", "blend network: stripe rows carry no centre path"))?
        .evaluate(station).or_refuse(KernelStage::Refine, "evaluate")?;
    // The section plane: through the vertex, normal = the edge's tangent.
    let normal = tangent_away_from(stripe.edge, vertex)?;
    // A curved carrier's ball contacts need not lie in the centre's
    // section plane. Intersect that plane with the rails and the carriers
    // instead of mistaking the marched circular section for a planar cut.
    let planar = [first_point, second_point, center].iter().all(|point| {
        point.sub(sharp_point).dot(normal).abs() <= 1e-5 * (1.0 + radius)
    });
    let straight_legs = [(first_point, carriers[0]), (second_point, carriers[1])]
        .into_iter().all(|(point, carrier)| {
            crate::project_point_to_surface(&carrier.surface, point.add(sharp_point).scale(0.5))
                .is_ok_and(|projection| projection.distance <= 1e-6 * (1.0 + radius))
        });
    let section = if planar && straight_legs {
        None
    } else {
        // A split of one continuous rim has the SAME boundary edge on both
        // mates. It is not a face junction: leave it to the tangent-chain
        // lane, which follows the complete rim (and handles its folds).
        // Capping that artificial split would silently shorten the fillet.
        let first_boundary = boundary_edge_at_vertex(solid, stripe.first.face, vertex, stripe.edge.id)?;
        let second_boundary = boundary_edge_at_vertex(solid, stripe.second.face, vertex, stripe.edge.id)?;
        if first_boundary == second_boundary {
            return Err(KernelRefusal::unsupported(
                KernelStage::Classify,
                "cap_continuous_rim",
                "blend network: curved cap on a split continuous rim requires the tangent-chain lane",
            ));
        }
        Some(cap::plane_section(stripe, rows, sharp_point, normal, station, at_start, [tail[0].map(|_| carriers[0]), tail[1].map(|_| carriers[1])])?)
    };
    let (cr_parameter, cs_parameter, first_point, second_point) = match &section {
        Some(section) => (section.cr, section.cs, section.first, section.second),
        None => (station, station, first_point, second_point),
    };
    // The legs meet at the EXISTING vertex — the continuing edge still ends
    // there, and a fresh vertex at the same point would leave every loop
    // through it open.
    let sharp_vertex = vertex;
    let first_vertex = take_id();
    result.vertices.push(VertexRecord {
        id: first_vertex,
        point: first_point,
    });
    let second_vertex = take_id();
    result.vertices.push(VertexRecord {
        id: second_vertex,
        point: second_point,
    });
    // The arc in the blend loop's walk direction.
    let walk_first_to_second = stripe.walk_first_to_second(at_start);
    let (from, to, from_vertex, to_vertex) = if walk_first_to_second {
        (first_point, second_point, first_vertex, second_vertex)
    } else {
        (second_point, first_point, second_vertex, first_vertex)
    };
    let arc = if let Some(section) = &section {
        if walk_first_to_second {
            section.curve.clone()
        } else {
            section.curve.reversed().or_refuse(KernelStage::Refine, "reversed")?
        }
    } else {
        corner_section_arc(center, radius, from, to)?
    };
    let arc_domain = arc.domain().or_refuse(KernelStage::Refine, "domain")?;
    let arc_edge_id = take_id();
    result.edges.push(EdgeRecord {
        id: arc_edge_id,
        curve: arc,
        t0: arc_domain[0],
        t1: arc_domain[1],
        start_vertex_id: from_vertex,
        end_vertex_id: to_vertex,
        degenerate: false,
        name: None,
    });
    let arc_blend_pcurve = if let Some(section) = &section {
        if walk_first_to_second {
            section.pcurve.clone()
        } else {
            section.pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?
        }
    } else if walk_first_to_second {
        crate::sweep_topology::parameter_line(station, 0.0, station, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?
    } else {
        crate::sweep_topology::parameter_line(station, 1.0, station, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?
    };
    // A rolled side's leg is a chain over the neighbours (committed first:
    // the closure below borrows the result); its first piece is what the
    // stripe's surgery references as the leg.
    let mut chains: [Vec<super::rollover::LegPiece>; 2] = [Vec::new(), Vec::new()];
    if tail[0].is_some() {
        chains[0] = cap::leg_chain(result, take_id, carriers[0].id, first_point, first_vertex, sharp_point, sharp_vertex, sharp_point, normal)?;
    }
    if tail[1].is_some() {
        chains[1] = cap::leg_chain(result, take_id, carriers[1].id, second_point, second_vertex, sharp_point, sharp_vertex, sharp_point, normal)?;
    }
    // Legs from rim to vertex. Keep the traced curves and pcurves on curved
    // carriers; the original straight-leg lane uses the projected endpoints.
    let mut leg = |rim_point: Vec3,
                   rim_vertex: u64,
                   face: &FaceRecord,
                   curved: Option<&(NurbsCurve, NurbsCurve)>|
     -> Result<(u64, NurbsCurve), KernelRefusal> {
        let id = take_id();
        result.edges.push(EdgeRecord {
            id,
            curve: match curved {
                Some((curve, _)) => curve.clone(),
                None => crate::make_line(rim_point, sharp_point).or_refuse(KernelStage::Refine, "make_line")?,
            },
            t0: 0.0,
            t1: 1.0,
            start_vertex_id: rim_vertex,
            end_vertex_id: sharp_vertex,
            degenerate: false,
            name: None,
        });
        if let Some((_, pcurve)) = curved {
            return Ok((id, pcurve.clone()));
        }
        let a = crate::project_point_to_surface(&face.surface, rim_point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
        let b = crate::project_point_to_surface(&face.surface, sharp_point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
        Ok((id, crate::sweep_topology::parameter_line(a.u, a.v, b.u, b.v).or_refuse(KernelStage::Refine, "parameter_line")?))
    };
    let first_leg = match chains[0].first() {
        Some(piece) => (piece.edge_id, piece.pcurve.clone()),
        None => leg(first_point, first_vertex, carriers[0], section.as_ref().and_then(|s| s.legs[0].as_ref()))?,
    };
    let second_leg = match chains[1].first() {
        Some(piece) => (piece.edge_id, piece.pcurve.clone()),
        None => leg(second_point, second_vertex, carriers[1], section.as_ref().and_then(|s| s.legs[1].as_ref()))?,
    };
    let chain_or = |chain: &[super::rollover::LegPiece], single: (u64, u64, u64)| -> Vec<(u64, u64, u64)> {
        if chain.is_empty() { vec![single] } else { chain.iter().map(|piece| (piece.edge_id, piece.from, piece.to)).collect() }
    };
    // The bulkhead plane's frame: u along first->second rim, v completing.
    let plane_u = second_point.sub(first_point).normalized().or_refuse(KernelStage::Refine, "normalized")?;
    let plane_v = normal.cross(plane_u).normalized().or_refuse(KernelStage::Refine, "normalized")?;
    pending.push(PendingCap {
        plane_origin: sharp_point,
        plane_u,
        plane_v,
        plane_normal: normal,
        arc: (arc_edge_id, from_vertex, to_vertex),
        first_leg: chain_or(&chains[0], (first_leg.0, first_vertex, sharp_vertex)),
        second_leg: chain_or(&chains[1], (second_leg.0, second_vertex, sharp_vertex)),
        outward: normal.scale(-1.0),
        name: stripe.name.clone(),
    });
    Ok((
        CapEnd {
            cr_parameter,
            cs_parameter,
            first_vertex,
            second_vertex,
            arc_edge_id,
            arc_blend_pcurve,
            first_leg,
            second_leg,
            sharp_vertex,
        },
        section.is_some(),
        chains,
    ))
}

/// Sew a cap's bulkhead: a planar face in the section plane whose loop is
/// leg (vertex -> first rim), arc (first rim -> second rim), leg (second rim
/// -> vertex), each used with the sense OPPOSITE to its neighbour (the blend
/// walks the arc forward; the mates walk the legs rim -> vertex where the
/// rail ends at the rim).
fn sew_cap(
    result: &mut BrepSolid,
    take_id: &mut dyn FnMut() -> u64,
    cap: PendingCap,
) -> Result<(), KernelRefusal> {
    // A plane patch large enough to hold the bulkhead with its origin set
    // back so the cap sits inside the patch's parameter square: the section
    // spans at most a few radii around the vertex.
    let reach = {
        let a = vertex_point_of(result, cap.first_leg[0].1)?;
        let b = vertex_point_of(result, cap.second_leg[0].1)?;
        a.sub(cap.plane_origin)
            .length()
            .max(b.sub(cap.plane_origin).length())
            .max(1e-6)
            * 4.0
    };
    let origin = cap
        .plane_origin
        .sub(cap.plane_u.scale(reach))
        .sub(cap.plane_v.scale(reach));
    let plane = crate::make_plane(origin, cap.plane_u, cap.plane_v, 2.0 * reach, 2.0 * reach).or_refuse(KernelStage::Refine, "make_plane")?;
    let uv_of = |point: Vec3| -> Result<(f64, f64), KernelRefusal> {
        let projection = crate::project_point_to_surface(&plane, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
        Ok((projection.u, projection.v))
    };
    let edge_by_id = |id: u64| -> Result<&EdgeRecord, KernelRefusal> {
        result
            .edges
            .iter()
            .find(|edge| edge.id == id)
            .ok_or_else(|| format!("blend network: cap edge {id} missing")).or_refuse(KernelStage::Refine, "ok_or_else")
    };
    // How the blend uses the arc: forward.  The bulkhead uses it reversed,
    // so its walk runs arc-end -> arc-start; the legs then run start-rim
    // -> vertex ... wait: walk = [leg from vertex to arc-END rim]? Build the
    // loop by chaining vertices: start at the sharp vertex, take the leg
    // ending at the arc's stored END, the arc reversed, then the other leg
    // back to the vertex.
    let (arc_id, arc_start, arc_end) = cap.arc;
    let leg_to = |rim: u64| -> Result<Vec<(u64, u64, u64)>, KernelRefusal> {
        for leg in [&cap.first_leg, &cap.second_leg] {
            if leg.first().is_some_and(|piece| piece.1 == rim) {
                return Ok(leg.clone());
            }
        }
        Err(KernelRefusal::internal(KernelStage::Sew, "cap_leg", "blend network: cap leg for the rim is missing"))
    };
    let leg_in = leg_to(arc_end)?; // stored rim -> vertex; walked vertex -> rim: forward = false
    let leg_out = leg_to(arc_start)?; // stored rim -> vertex; walked rim -> vertex: forward = true
    // Every cap edge lies in this plane. Map the entire curve so curved
    // carrier/plane legs retain their shape and traversal parameterization.
    let mapped_pcurve = |id: u64| -> Result<NurbsCurve, KernelRefusal> {
        let edge = edge_by_id(id)?;
        let mut mapped = Vec::with_capacity(edge.curve.control_points.len());
        for control in &edge.curve.control_points {
            let point = control.point().or_refuse(KernelStage::Refine, "point")?;
            let (u, v) = uv_of(point)?;
            mapped.push(crate::Vec4 { x: u * control.w, y: v * control.w, z: 0.0, w: control.w });
        }
        NurbsCurve::new(edge.curve.degree, edge.curve.knots.clone(), mapped)
            .or_refuse(KernelStage::Refine, "new")
    };
    // Walk: vertex -> (leg_in's pieces, last to first, each reversed) -> arc
    // end, the arc reversed, arc start -> (leg_out's pieces, first to last,
    // forward) -> vertex.
    let mut coedges = Vec::with_capacity(leg_in.len() + leg_out.len() + 1);
    for piece in leg_in.iter().rev() {
        coedges.push(CoedgeRecord {
            id: take_id(),
            edge_id: piece.0,
            forward: false,
            pcurve: mapped_pcurve(piece.0)?.reversed().or_refuse(KernelStage::Refine, "reversed")?,
        });
    }
    coedges.push(CoedgeRecord {
        id: take_id(),
        edge_id: arc_id,
        forward: false,
        pcurve: mapped_pcurve(arc_id)?.reversed().or_refuse(KernelStage::Refine, "reversed")?,
    });
    for piece in &leg_out {
        coedges.push(CoedgeRecord {
            id: take_id(),
            edge_id: piece.0,
            forward: true,
            pcurve: mapped_pcurve(piece.0)?,
        });
    }
    let plane_normal = plane.normal(0.5, 0.5).or_refuse(KernelStage::Refine, "normal")?;
    let same_sense = plane_normal.dot(cap.outward) > 0.0;
    let loop_id = take_id();
    let face = FaceRecord {
        id: take_id(),
        surface: plane,
        same_sense,
        loops: vec![crate::topology::LoopRecord {
            id: loop_id,
            coedges,
        }],
        name: cap.name.map(|name| format!("{name}:CAP")),
    };
    let _ = cap.plane_normal;
    let shell_index = result
        .shells
        .iter()
        .position(|shell| !shell.faces.is_empty())
        .ok_or(KernelRefusal::internal(KernelStage::Sew, "shell", "blend network: the solid has no shell to sew the cap into"))?;
    result.shells[shell_index].faces.push(face);
    Ok(())
}

fn vertex_point_of(solid: &BrepSolid, id: u64) -> Result<Vec3, KernelRefusal> {
    solid
        .vertices
        .iter()
        .find(|vertex| vertex.id == id)
        .map(|vertex| vertex.point)
        .ok_or_else(|| format!("blend network: vertex {id} missing")).or_refuse(KernelStage::Refine, "ok_or_else")
}

/// Why a corner's tangency point is not on a stripe's fitted rail.
enum RailMiss {
    /// The rail passes `f64` away from the point — a fit disagreement, not a
    /// span that stops short.
    OffRail(f64),
    /// The rail passes THROUGH the point, but at a station outside the
    /// marched span (the row would have to be extrapolated to reach it).
    OffSpan(f64),
    Projection(String),
}

/// A fitted rail on a curved carrier reproduces the marched contacts between
/// stations only to its interpolation error, which grows with the carrier's
/// size (a radius-50 rail with 64 stations lands ~3e-5 off), so the bar is the
/// model scale's, not the radius's.
fn corner_station_bar(scale: f64, radius: f64) -> f64 {
    1e-6 * (1.0 + scale.max(radius))
}

/// The row parameter where `row` passes through `point`, or why it does not.
/// The shared vertex sits at the ball's point; the rail end is healed onto it
/// afterwards.
fn rail_station(row: &NurbsCurve, point: Vec3, bar: f64) -> Result<f64, RailMiss> {
    let projection =
        crate::project_point_to_curve(row, point).map_err(RailMiss::Projection)?;
    if projection.distance > bar {
        return Err(RailMiss::OffRail(projection.distance));
    }
    if !(projection.u > RIM_MARGIN && projection.u < 1.0 - RIM_MARGIN) {
        return Err(RailMiss::OffSpan(projection.u));
    }
    Ok(projection.u)
}

/// The overshoot, as a fraction of `edge`'s parameter span, that carries a
/// stripe's rails to the ball of the CONCAVE corner at `vertex` — or `None`
/// where that end asks nothing of the ladder: no corner there, a convex one
/// (its ball sits inside the span), a flush join or a re-entrant closure
/// (their own lanes place the stop), a ball that does not sit past the
/// vertex, or a stationary end (no speed to read the parameter off).
///
/// The march reads the edge past its ends as the straight continuation in
/// the end derivative (`derivatives_extended`), so the station whose section
/// plane holds the ball's centre lies exactly `beyond / |C'(vertex)|` past
/// the vertex in parameter, where `beyond` is the centre's distance past the
/// vertex along the edge's outward tangent.  Every tangency point of the ball
/// is in that section plane, so a rail that reaches it reaches them all.
fn concave_corner_reach(
    edge: &EdgeRecord,
    corners: &[(u64, Vec<usize>, VertexKind<'_>)],
    vertex: u64,
    at_start: bool,
) -> Option<f64> {
    let (_, _, kind) = corners.iter().find(|(id, _, _)| *id == vertex)?;
    let corner = match kind {
        VertexKind::Star { corner } | VertexKind::RibbonStar { corner } | VertexKind::Miter { corner, .. } => corner,
        VertexKind::Flush { .. } | VertexKind::Reentrant { .. } | VertexKind::MixedStar(_) => return None,
    };
    if corner.outward {
        return None;
    }
    let t = if at_start { edge.t0 } else { edge.t1 };
    let derivatives = edge.curve.derivatives(t, 1).ok()?;
    let speed = derivatives[1].length();
    let tangent = derivatives[1].normalized().ok()?;
    // Outward: against the parameter direction at the start of a span that
    // runs up in t, along it at the end — and the reverse on a span that
    // runs down.
    let runs_up = edge.t1 >= edge.t0;
    let away = if at_start == runs_up { tangent.scale(-1.0) } else { tangent };
    let beyond = corner.center.sub(derivatives[0]).dot(away);
    let span = (edge.t1 - edge.t0).abs();
    if !(beyond > 0.0) || !(speed > 0.0) || !(span > 0.0) {
        return None;
    }
    Some(beyond / speed / span)
}

/// The overshoot (as a fraction of the edge's span) that carries the rows
/// past every stop the ends ask for: a concave corner's ball, or a flush
/// join's seam ball (`flush_reach`, read off the stripe's `ends`).
fn ladder_reach(edge: &EdgeRecord, corners: &[(u64, Vec<usize>, VertexKind<'_>)], flush_reach: f64) -> f64 {
    [(edge.start_vertex_id, true), (edge.end_vertex_id, false)]
        .into_iter()
        .filter_map(|(vertex, at_start)| concave_corner_reach(edge, corners, vertex, at_start))
        .fold(flush_reach.max(0.0), f64::max)
}

/// Lane R2 row 6 (2026-10-18): `BREP_BLEND_SHORT_RUNGS=1`/`on` defers the
/// overshoot rungs below [`ladder_reach`] until the rungs that reach have
/// failed to settle (the default since its census at 5aadf921e); `=0`/`off`
/// climbs the ladder in order; `set_short_rungs_deferred_for_test` forces it
/// on a test's own thread.
const SHORT_RUNGS_DEFERRED_DEFAULT: bool = true;

pub(in crate::blend) fn short_rungs_deferred_on() -> bool {
    switch!(live "BREP_BLEND_SHORT_RUNGS", SHORT_RUNGS_DEFERRED_DEFAULT)
}


/// The overshoot ladder for one stripe of the network: [`OVERSHOOTS`], and
/// past its last rung the rungs a concave corner at either end needs
/// ([`concave_corner_reach`]) or a flush join's seam-ball stop needs
/// (`flush_reach`, the stop's distance past the vertex as a fraction of the
/// span; zero when no end has one).  `rail_station` wants the tangency point
/// inside the fitted row by `RIM_MARGIN`, so the needed fraction itself would
/// land it on the row's rim: the rungs stand a quarter and then a whole of
/// the need beyond it.  Two rungs, no more — each is a full march, paid again
/// on every retry of the group's subset search.
fn concave_corner_ladder(
    edge: &EdgeRecord,
    corners: &[(u64, Vec<usize>, VertexKind<'_>)],
    flush_reach: f64,
) -> Vec<f64> {
    let mut ladder = OVERSHOOTS.to_vec();
    let needed = ladder_reach(edge, corners, flush_reach);
    let top = *OVERSHOOTS.last().unwrap_or(&0.0);
    for factor in [1.25, 2.0] {
        let rung = needed * factor;
        if rung > top {
            ladder.push(rung);
        }
    }
    ladder
}

/// Whether `rows` — a stripe marched at one rung of the overshoot ladder —
/// already reaches the tangency points the corner at one of its ends was
/// solved on, which is what the surgery will ask of it (`station_on`).
///
/// A CONVEX corner seats its ball inside the material, so its tangency points
/// sit on the rails INSIDE the edge's own span (the familiar setback) and any
/// rung reaches them.  A CONCAVE one seats it in the air PAST the vertex — the
/// base of a boss, a rib standing on a floor: the two floor rails cross one
/// radius beyond the corner — so the march has to overshoot far enough to
/// carry the rail there.  Reporting that here is what makes the ladder climb
/// for it instead of settling on the first rung and refusing later.
fn corner_rails_reach(
    rows: &FittedRows,
    first: &BlendMate,
    second: &BlendMate,
    kind: &VertexKind,
    bar: f64,
) -> bool {
    let reaches = |face_id: u64, point: Vec3| {
        let row = if first.face.id == face_id {
            &rows.cr
        } else if second.face.id == face_id {
            &rows.cs
        } else {
            return false;
        };
        let station = rail_station(row, point, bar);
        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
            eprintln!(
                "corner reach: face {face_id} point ({:.6}, {:.6}, {:.6}) -> {}",
                point.x,
                point.y,
                point.z,
                match &station {
                    Ok(u) => format!("on the rail at {u:.6}"),
                    Err(RailMiss::OffRail(distance)) => format!("off the rail by {distance:.3e} (bar {bar:.3e})"),
                    Err(RailMiss::OffSpan(u)) => format!("off the span at {u:.6}"),
                    Err(RailMiss::Projection(error)) => format!("projection failed: {error}"),
                }
            );
        }
        station.is_ok()
    };
    let on = |corner: &Corner, face_id: u64| {
        corner
            .tangency_on(face_id)
            .map(|(point, _)| reaches(face_id, point))
            .unwrap_or(false)
    };
    match kind {
        VertexKind::Star { corner } | VertexKind::RibbonStar { corner } => {
            on(corner, first.face.id) && on(corner, second.face.id)
        }
        // A miter only reads the tangency on the SHARED face; its other rim
        // vertices come from the seam.
        VertexKind::Miter { corner, shared, .. } => on(corner, shared.id),
        // A flush join across a seam stops where the rails pass the seam
        // ball's two contacts, which can sit past the vertex — beyond the
        // edge's own span on the stripe whose carrier the ball leaves.
        VertexKind::Flush { join: Some(join) } => [first.face.id, second.face.id]
            .into_iter()
            .all(|face_id| {
                join.contact_on(face_id)
                    .is_some_and(|contact| reaches(face_id, contact.point))
            }),
        // Their own lanes decide where these stop.
        VertexKind::Reentrant { .. } | VertexKind::Flush { join: None } => true,
        // Every stripe of a mixed star stops at two closed-form contacts.
        VertexKind::MixedStar(mixed) => {
            let contact = |face_id: u64| -> Option<Vec3> {
                let (a, b) = (first.face.id, second.face.id);
                let pair = |x: u64, y: u64| (a == x && b == y) || (a == y && b == x);
                if pair(mixed.wall_a, mixed.cap) {
                    Some(if face_id == mixed.wall_a { mixed.v_a } else { mixed.w_a })
                } else if pair(mixed.wall_b, mixed.cap) {
                    Some(if face_id == mixed.wall_b { mixed.v_b } else { mixed.w_b })
                } else if pair(mixed.wall_a, mixed.wall_b) {
                    Some(if face_id == mixed.wall_a { mixed.v_a } else { mixed.v_b })
                } else {
                    None
                }
            };
            [first.face.id, second.face.id]
                .into_iter()
                .all(|face_id| contact(face_id).is_some_and(|point| reaches(face_id, point)))
        }
    }
}

/// Sew a [`VertexKind::MixedStar`]: splice the cap's contact arc W_A..W_B
/// (2r about Q's axis) between the two rims' cap rails, and the exact torus
/// sector — rim A's end section revolved about Q's axis to rim B's — bounded
/// by the two rims' end arcs, Q's inner-equator arc and the cap arc, each
/// shared edge used opposite to its neighbour.
#[allow(clippy::too_many_arguments)]
fn sew_mixed_star(
    result: &mut BrepSolid,
    solid: &BrepSolid,
    take_id: &mut dyn FnMut() -> u64,
    stripes: &[Stripe],
    sewn: &[SewnStripe],
    vertex: u64,
    mixed: &MixedStar,
    arcs: &[EdgeRecord; 3],
    [v_a, v_b, w_a, w_b]: [u64; 4],
    name: Option<String>,
) -> Result<(), KernelRefusal> {
    let r = mixed.radius;
    let cap_rail = |index: usize| -> Result<u64, KernelRefusal> {
        if stripes[index].first.face.id == mixed.cap { sewn[index].cr_edge_id } else { sewn[index].cs_edge_id }
            .ok_or_else(|| KernelRefusal::unsupported(KernelStage::Sew, RAIL_COLLAPSE_WHAT, format!(
                "{RAIL_COLLAPSE_UNSUPPORTED} a cap rail at the mixed star {vertex} collapsed to a point"
            )))
    };
    let (rail_a, rail_b) = (cap_rail(mixed.a)?, cap_rail(mixed.b)?);
    let cap_arc = corner_section_arc(mixed.q_w, 2.0 * r, mixed.w_a, mixed.w_b)?;
    let cap_domain = cap_arc.domain().or_refuse(KernelStage::Refine, "domain")?;
    let cap_arc_id = take_id();
    result.edges.push(EdgeRecord {
        id: cap_arc_id,
        curve: cap_arc.clone(),
        t0: cap_domain[0],
        t1: cap_domain[1],
        start_vertex_id: w_a,
        end_vertex_id: w_b,
        degenerate: false,
        name: None,
    });
    let cap_forward_on_cap = {
        let cap_face = result
            .shells
            .iter_mut()
            .flat_map(|shell| &mut shell.faces)
            .find(|face| face.id == mixed.cap)
            .ok_or(KernelRefusal::internal(KernelStage::Sew, "cap_face", "blend network: the mixed star's cap is missing"))?;
        // The cap is planar (detected): the arc's exact affine image.
        let cap_pcurve = crate::pcurve::build_pcurve_on_surface(&cap_face.surface, &cap_arc).or_refuse(KernelStage::Refine, "build_pcurve")?;
        let mut spliced: Option<bool> = None;
        for loop_record in &mut cap_face.loops {
            let count = loop_record.coedges.len();
            let (Some(at_a), Some(at_b)) = (
                loop_record.coedges.iter().position(|c| c.edge_id == rail_a),
                loop_record.coedges.iter().position(|c| c.edge_id == rail_b),
            ) else {
                continue;
            };
            let (insert_at, forward, pcurve) = if (at_a + 1) % count == at_b {
                (at_a + 1, true, cap_pcurve.clone())
            } else if (at_b + 1) % count == at_a {
                (at_b + 1, false, cap_pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?)
            } else {
                return Err(KernelRefusal::internal(KernelStage::Sew, "mixed_star_cap_rails", "blend network: the mixed star's two cap rails are not adjacent on the cap"));
            };
            loop_record.coedges.insert(insert_at, CoedgeRecord { id: take_id(), edge_id: cap_arc_id, forward, pcurve });
            spliced = Some(forward);
            break;
        }
        spliced.ok_or(KernelRefusal::internal(KernelStage::Sew, "mixed_star_cap_loop", "blend network: no cap loop holds both of the mixed star's cap rails"))?
    };
    // The sector: rim A's end section run V_A -> W_A, revolved about Q's
    // axis through q_v by the angle between the two rims' ball centres.
    let radial_a = mixed.c_a.sub(mixed.q_v).normalized().or_refuse(KernelStage::Refine, "normalized")?;
    let radial_b = mixed.c_b.sub(mixed.q_v).normalized().or_refuse(KernelStage::Refine, "normalized")?;
    let sweep = radial_a.dot(radial_b).clamp(-1.0, 1.0).acos();
    if sweep < 1e-9 {
        return Err(KernelRefusal::internal(KernelStage::Refine, "mixed_star_sweep", "blend network: degenerate mixed star sweep"));
    }
    let revolve_axis = if radial_a.cross(radial_b).dot(mixed.axis) > 0.0 { mixed.axis } else { mixed.axis.scale(-1.0) };
    let generatrix = corner_section_arc(mixed.c_a, r, mixed.v_a, mixed.w_a)?;
    let surface = crate::make_revolution(mixed.q_v, revolve_axis, &generatrix, sweep).or_refuse(KernelStage::Refine, "make_revolution")?;
    let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
    let [g0, g1] = generatrix.domain().or_refuse(KernelStage::Refine, "domain")?;
    let far = surface.evaluate(u1, g1).or_refuse(KernelStage::Refine, "evaluate")?;
    if far.sub(mixed.w_b).length() > 1e-6 * (1.0 + r) {
        return Err(KernelRefusal::internal(KernelStage::Refine, "mixed_star_closure", format!(
            "blend network: the mixed star's torus does not close on W_B ({:.3e} off)",
            far.sub(mixed.w_b).length()
        )));
    }
    let uv = |id: u64| -> Option<(f64, f64)> {
        if id == v_a { Some((u0, g0)) } else if id == w_a { Some((u0, g1)) } else if id == v_b { Some((u1, g0)) } else if id == w_b { Some((u1, g1)) } else { None }
    };
    // Sides with the senses opposite their neighbours: the blends use their
    // end arcs forward, the cap uses the cap arc as spliced.
    let cap_arc_record = result.edges.iter().find(|e| e.id == cap_arc_id).cloned().ok_or(KernelRefusal::internal(KernelStage::Sew, "mixed_star_cap_arc", "blend network: the cap arc vanished"))?;
    let sides: [(EdgeRecord, bool); 4] = [
        (arcs[0].clone(), false),
        (arcs[1].clone(), false),
        (arcs[2].clone(), false),
        (cap_arc_record, !cap_forward_on_cap),
    ];
    let walk = |edge: &EdgeRecord, forward: bool| if forward { (edge.start_vertex_id, edge.end_vertex_id) } else { (edge.end_vertex_id, edge.start_vertex_id) };
    let mut order = vec![0usize];
    let mut cursor = walk(&sides[0].0, sides[0].1).1;
    for _ in 0..3 {
        let next = (0..4)
            .find(|s| !order.contains(s) && walk(&sides[*s].0, sides[*s].1).0 == cursor)
            .ok_or(KernelRefusal::internal(KernelStage::Sew, "mixed_star_walk", "blend network: the blends and the cap do not walk the mixed star's boundary consistently"))?;
        cursor = walk(&sides[next].0, sides[next].1).1;
        order.push(next);
    }
    if cursor != walk(&sides[0].0, sides[0].1).0 {
        return Err(KernelRefusal::internal(KernelStage::Sew, "mixed_star_loop", "blend network: the mixed star's boundary does not close"));
    }
    let mut coedges = Vec::with_capacity(4);
    for s in order {
        let (edge, forward) = &sides[s];
        let (start, end) = walk(edge, *forward);
        let (Some((su, sv)), Some((eu, ev))) = (uv(start), uv(end)) else {
            return Err(KernelRefusal::internal(KernelStage::Sew, "mixed_star_uv", "blend network: a mixed star side ends off the sector's corners"));
        };
        coedges.push(CoedgeRecord {
            id: take_id(),
            edge_id: edge.id,
            forward: *forward,
            pcurve: crate::sweep_topology::parameter_line(su, sv, eu, ev).or_refuse(KernelStage::Refine, "parameter_line")?,
        });
    }
    // Orient at the tangency with the cap, as the horn torus does.
    let (um, gm) = (0.5 * (u0 + u1), g1);
    let contact = surface.evaluate(um, gm).or_refuse(KernelStage::Refine, "evaluate")?;
    let cap = solid.shells.iter().flat_map(|shell| &shell.faces)
        .find(|face| face.id == mixed.cap)
        .ok_or(KernelRefusal::internal(KernelStage::Refine, "cap_face", "blend network: missing mixed star cap"))?;
    let projection = crate::project_point_to_surface(&cap.surface, contact).or_refuse(KernelStage::Refine, "project")?;
    let cap_normal = cap.surface.normal(projection.u, projection.v).or_refuse(KernelStage::Refine, "normal")?;
    let outward = if cap.same_sense { cap_normal } else { cap_normal.scale(-1.0) };
    let surface_normal = surface.normal(um, gm).or_refuse(KernelStage::Refine, "normal")?;
    let same_sense = surface_normal.dot(outward) > 0.0;
    let loop_id = take_id();
    let face = FaceRecord {
        id: take_id(),
        surface,
        same_sense,
        loops: vec![crate::topology::LoopRecord { id: loop_id, coedges }],
        name,
    };
    let shell_index = result
        .shells
        .iter()
        .position(|shell| !shell.faces.is_empty())
        .ok_or(KernelRefusal::internal(KernelStage::Sew, "shell", "blend network: the solid has no shell to sew the mixed star into"))?;
    result.shells[shell_index].faces.push(face);
    Ok(())
}

/// Whether the SHARP edge between `wall_a` and `wall_b` is convex, by the
/// rule `analyze_edge` uses: one wall's into-material direction dives below
/// the other wall's plane.
fn sharp_edge_is_convex(
    solid: &BrepSolid,
    sharp: &EdgeRecord,
    wall_a: &FaceRecord,
    wall_b: &FaceRecord,
    radius: f64,
) -> Result<bool, KernelRefusal> {
    let _ = solid;
    let t = (sharp.t0 + sharp.t1) * 0.5;
    let point = sharp.curve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
    let tangent = sharp
        .curve
        .unit_tangent(t, sharp.t0, sharp.t1)
        .map_err(|error| format!("blend network: sharp edge {}: {error}", sharp.id)).or_refuse(KernelStage::Refine, "unit_tangent")?;
    let probe = (radius * 0.25).max(1e-4);
    let into_a = crate::fillet::into_face_direction(wall_a, point, tangent, point, tangent, probe)?;
    let into_b = crate::fillet::into_face_direction(wall_b, point, tangent, point, tangent, probe)?;
    let outward = |face: &FaceRecord| -> Result<Vec3, KernelRefusal> {
        let projection = crate::project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
        let normal = raw_normal(&face.surface, projection.u, projection.v)?;
        Ok(if face.same_sense { normal } else { normal.scale(-1.0) })
    };
    let (n_a, n_b) = (outward(wall_a)?, outward(wall_b)?);
    Ok(into_a.dot(n_b) < -1e-9 || into_b.dot(n_a) < -1e-9)
}

/// Whether a selected edge is convex: its ball (offset by the signed radii
/// the march uses) sits inside the material on both mates.
pub(super) fn edge_is_convex(edge: &EdgeRecord, first: &BlendMate, second: &BlendMate) -> Result<bool, KernelRefusal> {
    let t = (edge.t0 + edge.t1) * 0.5;
    let mut inside = true;
    for mate in [first, second] {
        let uv = edge_uv_on_face(mate.coedge, edge, t)?;
        let normal = raw_normal(&mate.face.surface, uv[0], uv[1])?;
        let face_outward = if mate.face.same_sense { normal } else { normal.scale(-1.0) };
        // centre = p + rho * n_raw; inside the material iff that offset runs
        // against the outward normal.
        inside &= normal.scale(mate.rho).dot(face_outward) < 0.0;
    }
    Ok(inside)
}

/// The corner ball's cross-section between two of its tangency points: the
/// radius-`radius` arc about `center` running the short way from `from` to
/// `to`.  This is simultaneously the stripe's end section and one side of the
/// spherical corner patch, which is why the two meet exactly.
/// Whether a re-entrant corner whose stop sections sit a little off the
/// meridians of the horn torus (a near-tangent crease) is closed by the ruled
/// patch between them (2026-11-05): OFF unless
/// `BREP_TILTED_HORN=1` (or `on`).
pub(in crate::blend) fn tilted_horn_on() -> bool {
    switch!("BREP_TILTED_HORN", false)
}

/// The largest pivot of the ball about the concave edge (the crease angle,
/// radians) the tilted closure admits: a near-tangent crease only.
const TILTED_HORN_MAX_PIVOT: f64 = 0.02;

/// The largest |stripe direction . concave edge| the tilted closure admits.
const TILTED_HORN_MAX_TILT: f64 = 0.02;

/// The ruled patch between two stop sections of one pivoting ball: u = 0 is
/// `a`, u = 1 is `b`, v runs pole -> cap on both. Accepted only when every
/// sampled point stands on the ball whose centre runs from `center_a` to
/// `center_b`, to the solid's `intersection_fit`; otherwise refused by name.
fn tilted_horn_patch(
    a: &NurbsCurve,
    b: &NurbsCurve,
    center_a: Vec3,
    center_b: Vec3,
    radius: f64,
    solid: &BrepSolid,
) -> Result<crate::NurbsSurface, KernelRefusal> {
    if a.degree != b.degree || a.knots != b.knots || a.control_points.len() != b.control_points.len() {
        return Err(KernelRefusal::unsupported(KernelStage::Refine, "tilted_horn_sections", "blend network: the tilted horn's two stop sections are not alike (different arc spans)"));
    }
    let [v0, v1] = a.domain().or_refuse(KernelStage::Refine, "domain")?;
    let knots_v: Vec<f64> = a.knots.iter().map(|knot| (knot - v0) / (v1 - v0)).collect();
    let surface = crate::NurbsSurface::new(1, a.degree, vec![0.0, 0.0, 1.0, 1.0], knots_v, vec![a.control_points.clone(), b.control_points.clone()])
        .or_refuse(KernelStage::Refine, "tilted_horn_surface")?;
    let bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
    let mut worst: f64 = 0.0;
    for i in 0..=8 {
        let u = i as f64 / 8.0;
        let center = center_a.scale(1.0 - u).add(center_b.scale(u));
        for j in 0..=16 {
            let v = j as f64 / 16.0;
            let point = surface.evaluate(u, v).or_refuse(KernelStage::Refine, "evaluate")?;
            worst = worst.max((point.sub(center).length() - radius).abs());
        }
    }
    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
        eprintln!("tilted horn: ruled closure {worst:.3e} off the pivoting ball (bar {bar:.3e})");
    }
    if worst > bar {
        return Err(KernelRefusal::unsupported(KernelStage::Refine, "tilted_horn_off_ball", format!(
            "blend network: the tilted horn's ruled closure stands {worst:.3e} off the pivoting ball, over the fit tolerance {bar:.3e}"
        )));
    }
    Ok(surface)
}

/// Split cap rail `rail` where its pcurve on the periodic cap `cap_face`
/// leaves the cap's domain across the seam that meets `corner`, and trim that
/// seam edge to the split point. Returns the piece past the seam (now the
/// rail's end at the corner side), or `None` when the cap has no seam at the
/// corner or the rail does not cross it.
fn split_rail_at_cap_seam(
    result: &mut BrepSolid,
    cap_face: u64,
    rail: u64,
    corner: u64,
    take_id: &mut dyn FnMut() -> u64,
) -> Result<Option<u64>, KernelRefusal> {
    let internal = |what: &'static str, message: &str| KernelRefusal::internal(KernelStage::Sew, what, message.to_string());
    let face = result.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == cap_face)
        .ok_or_else(|| internal("tilted_cap", "blend network: the tilted horn's cap is missing"))?;
    // The seam: an edge this face's loop uses twice, incident to the corner.
    let Some((loop_index, seam_id)) = face.loops.iter().enumerate().find_map(|(index, loop_record)| {
        loop_record.coedges.iter().find(|coedge| {
            loop_record.coedges.iter().filter(|other| other.edge_id == coedge.edge_id).count() == 2
                && result.edges.iter().find(|edge| edge.id == coedge.edge_id)
                    .is_some_and(|edge| edge.start_vertex_id == corner || edge.end_vertex_id == corner)
        }).map(|coedge| (index, coedge.edge_id))
    }) else {
        return Ok(None);
    };
    let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
    let period = u1 - u0;
    let Some(position) = face.loops[loop_index].coedges.iter().position(|coedge| coedge.edge_id == rail) else {
        return Ok(None);
    };
    let coedge = face.loops[loop_index].coedges[position].clone();
    let [q0, q1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
    let u_at = |q: f64| coedge.pcurve.evaluate(q).map(|point| point.x);
    let (start_u, end_u) = (u_at(q0).or_refuse(KernelStage::Refine, "evaluate")?, u_at(q1).or_refuse(KernelStage::Refine, "evaluate")?);
    let slack = 1e-9 * period;
    let crosses_at_end = end_u > u1 + slack || end_u < u0 - slack;
    let bound = if end_u > u1 + slack { u1 } else if end_u < u0 - slack { u0 } else if start_u > u1 + slack { u1 } else if start_u < u0 - slack { u0 } else { return Ok(None) };
    // Bisect the pcurve for the crossing u = bound.
    let (mut lo, mut hi) = (q0, q1);
    let side = |q: f64| -> Result<bool, KernelRefusal> { Ok(u_at(q).or_refuse(KernelStage::Refine, "evaluate")? <= bound) };
    let low_side = side(lo)?;
    if side(hi)? == low_side {
        return Ok(None);
    }
    for _ in 0..200 {
        let mid = 0.5 * (lo + hi);
        if side(mid)? == low_side { lo = mid } else { hi = mid }
        if hi - lo <= 1e-15 * (1.0 + (q1 - q0).abs()) { break }
    }
    let q_split = 0.5 * (lo + hi);
    let fraction = (q_split - q0) / (q1 - q0);
    let edge = result.edges.iter().find(|edge| edge.id == rail).cloned()
        .ok_or_else(|| internal("tilted_rail", "blend network: the tilted horn's cap rail is missing"))?;
    // The rail's coedge on the cap runs with the edge (it was sewn forward or
    // reversed; the fraction follows the traversal).
    let t_split = if coedge.forward { edge.t0 + (edge.t1 - edge.t0) * fraction } else { edge.t1 - (edge.t1 - edge.t0) * fraction };
    let point = edge.curve.evaluate(t_split).or_refuse(KernelStage::Refine, "evaluate")?;
    let seam = result.edges.iter().find(|edge| edge.id == seam_id).cloned()
        .ok_or_else(|| internal("tilted_seam", "blend network: the cap's seam is missing"))?;
    let on_seam = crate::project_point_to_curve(&seam.curve, point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
    let band = crate::KernelTolerances::for_solid(result, 1e-7).pcurve_consistency;
    if on_seam.distance > band.max(1e-9) * 10.0 {
        return Err(KernelRefusal::unsupported(KernelStage::Sew, "tilted_horn_seam", format!(
            "blend network: the cap rail crosses the cap's seam {:.3e} off the seam edge", on_seam.distance)));
    }
    let split_vertex = take_id();
    result.vertices.push(VertexRecord { id: split_vertex, point });
    super::edge::trim_edge_at(result, seam_id, on_seam.u, corner, split_vertex)?;
    // The two rail pieces: `near` keeps the traversal's first part on the
    // cap's own side, `past` is carried across the seam by one period.
    let (curve_low, curve_high) = edge.curve.split(t_split).or_refuse(KernelStage::Refine, "split")?;
    let (low_id, high_id) = (take_id(), take_id());
    result.edges.retain(|record| record.id != rail);
    result.edges.push(EdgeRecord { id: low_id, curve: curve_low, t0: edge.t0, t1: t_split, start_vertex_id: edge.start_vertex_id, end_vertex_id: split_vertex, degenerate: false, name: edge.name.clone() });
    result.edges.push(EdgeRecord { id: high_id, curve: curve_high, t0: t_split, t1: edge.t1, start_vertex_id: split_vertex, end_vertex_id: edge.end_vertex_id, degenerate: false, name: edge.name.clone() });
    // Every coedge of the rail becomes two, in traversal order; on the cap the
    // part past the seam is shifted by one period.
    for shell in &mut result.shells {
        for face in &mut shell.faces {
            let is_cap = face.id == cap_face;
            for loop_record in &mut face.loops {
                let Some(at) = loop_record.coedges.iter().position(|coedge| coedge.edge_id == rail) else { continue };
                let old = loop_record.coedges.remove(at);
                let [p0, p1] = old.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
                let p_split = p0 + (p1 - p0) * fraction_of(&edge, t_split, old.forward);
                let (first, second) = old.pcurve.split(p_split).or_refuse(KernelStage::Refine, "split")?;
                // Traversal order: forward walks low then high.
                let (first_edge, second_edge) = if old.forward { (low_id, high_id) } else { (high_id, low_id) };
                let mut pieces = [(first_edge, first, false), (second_edge, second, false)];
                if is_cap {
                    // The piece whose u lies outside the domain is carried
                    // back inside by one period.
                    for (_, pcurve, shifted) in pieces.iter_mut() {
                        let [r0, r1] = pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
                        let mid = pcurve.evaluate(0.5 * (r0 + r1)).or_refuse(KernelStage::Refine, "evaluate")?.x;
                        let shift = if mid > u1 { -period } else if mid < u0 { period } else { 0.0 };
                        if shift != 0.0 {
                            for control in pcurve.control_points.iter_mut() {
                                control.x += shift * control.w;
                            }
                            *shifted = true;
                        }
                    }
                    if pieces[0].2 == pieces[1].2 {
                        return Err(internal("tilted_seam_piece", "blend network: the split cap rail does not straddle the seam"));
                    }
                }
                let forward = old.forward;
                let mut make = |(edge_id, pcurve, shifted): (u64, NurbsCurve, bool)| (CoedgeRecord { id: take_id(), edge_id, forward, pcurve }, shifted);
                let [a, b] = pieces;
                let (a, b) = (make(a), make(b));
                if is_cap {
                    // On the cap the two pieces are no longer neighbours: the
                    // near piece keeps the rail's slot (beside one seam use),
                    // the past piece goes beside the seam's other use.
                    let (near, past, past_first) = if a.1 { (b.0, a.0, true) } else { (a.0, b.0, false) };
                    loop_record.coedges.insert(at, near);
                    let count = loop_record.coedges.len();
                    let neighbour = if past_first { (at + count - 1) % count } else { (at + 1) % count };
                    let uses: Vec<usize> = (0..count).filter(|index| loop_record.coedges[*index].edge_id == seam_id).collect();
                    if uses.len() != 2 || !uses.contains(&neighbour) {
                        return Err(internal("tilted_seam_use", "blend network: the split cap rail is not beside the cap's seam"));
                    }
                    let other = if uses[0] == neighbour { uses[1] } else { uses[0] };
                    // Past-first: the past piece walks INTO the seam's other
                    // use's start; otherwise it leaves that use's end.
                    loop_record.coedges.insert(if past_first { other } else { other + 1 }, past);
                } else {
                    loop_record.coedges.insert(at, a.0);
                    loop_record.coedges.insert(at + 1, b.0);
                }
            }
        }
    }
    // The cap coedge's traversal: forward walks low then high; the past
    // piece is the end that left the domain.
    let (first_edge, second_edge) = if coedge.forward { (low_id, high_id) } else { (high_id, low_id) };
    Ok(Some(if crosses_at_end { second_edge } else { first_edge }))
}

/// The traversal fraction of edge parameter `t` along a coedge of `edge`.
fn fraction_of(edge: &EdgeRecord, t: f64, forward: bool) -> f64 {
    let f = (t - edge.t0) / (edge.t1 - edge.t0);
    if forward { f } else { 1.0 - f }
}

fn corner_section_arc(
    center: Vec3,
    radius: f64,
    from: Vec3,
    to: Vec3,
) -> Result<NurbsCurve, KernelRefusal> {
    let x_axis = from.sub(center).normalized().or_refuse(KernelStage::Refine, "normalized")?;
    let toward = to.sub(center).normalized().or_refuse(KernelStage::Refine, "normalized")?;
    let y_axis = toward.sub(x_axis.scale(toward.dot(x_axis))).normalized().or_refuse(KernelStage::Refine, "normalized")?;
    let sweep = toward.dot(x_axis).clamp(-1.0, 1.0).acos();
    if !(sweep > 1e-9) {
        return Err(KernelRefusal::internal(KernelStage::Refine, "corner_section_arc", "blend network: the corner section arc is degenerate"));
    }
    crate::make_arc(center, x_axis, y_axis, radius, 0.0, sweep).or_refuse(KernelStage::Refine, "make_arc")
}

/// Close a stripe end that runs out into a POLE (`pole_end`): the march
/// stopped on the vertex itself, where both rails arrive at the one point the
/// section has shrunk to, so the end is that vertex — kept, not rebuilt — and
/// the blend face's loop closes across it on a DEGENERATE edge, the way a
/// revolution closes on its pole.  Nothing on either mate is trimmed: each
/// rail simply replaces the blended edge up to the vertex, where the mates'
/// own boundaries still meet.
fn plan_pole_end(
    solid: &BrepSolid,
    result: &mut BrepSolid,
    take_id: &mut dyn FnMut() -> u64,
    stripe: &Stripe,
    vertex: u64,
    at_start: bool,
) -> Result<CornerEnd, KernelRefusal> {
    let point = solid
        .vertices
        .iter()
        .find(|candidate| candidate.id == vertex)
        .ok_or_else(|| format!("blend network: pole vertex {vertex} missing")).or_refuse(KernelStage::Refine, "ok_or_else")?
        .point;
    let station = stripe
        .rows
        .vertex_stations
        .ok_or(KernelRefusal::internal(KernelStage::Refine, "vertex_stations", "blend network: stripe rows carry no vertex stations"))?
        [usize::from(!at_start)];
    let [low, high] = stripe.rows.cr.domain().or_refuse(KernelStage::Refine, "domain")?;
    if station != if at_start { low } else { high } {
        return Err(KernelRefusal::internal(KernelStage::Refine, "pole_station", format!(
            "blend network: edge {}'s pole station {station:.6} is not the end of its rows",
            stripe.edge.id
        )));
    }
    // Both rails must arrive AT the vertex: the rows were marched onto it,
    // so anything past the station bar is a march that did not.
    let bar = corner_station_bar(
        solid
            .vertices
            .iter()
            .fold(0.0f64, |worst, candidate| worst.max(candidate.point.length()))
            .max(1.0),
        stripe.first.rho.abs(),
    );
    for (row, which) in [(&stripe.rows.cr, "first"), (&stripe.rows.cs, "second")] {
        let miss = row.evaluate(station).or_refuse(KernelStage::Refine, "evaluate")?.sub(point).length();
        if miss > bar {
            return Err(KernelRefusal::internal(KernelStage::Refine, "pole_rail", format!(
                "blend network: edge {}'s {which} rail ends {miss:.3e} off its pole vertex                  {vertex}",
                stripe.edge.id
            )));
        }
    }
    let pole_edge_id = take_id();
    result.edges.push(EdgeRecord {
        id: pole_edge_id,
        curve: crate::make_line(point, point).or_refuse(KernelStage::Refine, "make_line")?,
        t0: 0.0,
        t1: 1.0,
        start_vertex_id: vertex,
        end_vertex_id: vertex,
        degenerate: true,
        name: None,
    });
    let arc_blend_pcurve = if stripe.walk_first_to_second(at_start) {
        crate::sweep_topology::parameter_line(station, 0.0, station, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?
    } else {
        crate::sweep_topology::parameter_line(station, 1.0, station, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?
    };
    Ok(CornerEnd {
        cr_parameter: station,
        cs_parameter: station,
        first_vertex: vertex,
        second_vertex: vertex,
        arc_edge_id: pole_edge_id,
        arc_blend_pcurve,
    })
}

/// One of the two contacts of a flush join's ball, and what it lies on.
struct FlushContact {
    /// The faces the contact lies on: the one face both stripes run along, or
    /// the two faces of the seam it sits on (one carrier of each stripe).
    faces: Vec<u64>,
    point: Vec3,
    /// The seam the contact sits on and its parameter there, when the
    /// stripes' carriers change across one: the point where the rolling ball
    /// changes carrier, and where the seam is trimmed.
    seam: Option<(u64, f64)>,
}

/// The ball a flush join seats where its two stripes' carriers change.
struct FlushJoin {
    center: Vec3,
    contacts: [FlushContact; 2],
}

impl FlushJoin {
    /// The ball's contact on `face_id`, a carrier of one of the stripes.
    fn contact_on(&self, face_id: u64) -> Option<&FlushContact> {
        self.contacts.iter().find(|contact| contact.faces.contains(&face_id))
    }
}

/// What a flush join at `vertex_id` stops on: nothing but the vertex section
/// when the two stripes run along the same two faces, else the ball seated on
/// the seam between the side faces that differ — or, when NEITHER face carries
/// over, on both seams at once.
///
/// # Why not the vertex section
///
/// The vertex section is where the two EDGES meet; the ball changes carrier
/// where its CONTACT crosses the seam, and the two coincide only when the seam
/// lies in the vertex's normal plane (a stadium cap's straight wall running
/// into its round, the seam a ruling straight down the wall). A seam that
/// crosses the edge obliquely — a wall standing across a cone whose rim is
/// rounded, the seams being circles — puts the carrier switch past the vertex
/// on one stripe or the other, and the two vertex sections are different balls
/// on carriers that are only G1 there: measured on the 2026-09-15 report
/// (r = 0.1 against an r = 2.5 round), 1.1e-5 apart where the cone meets the
/// round and 3.5e-4 where the round meets the top, which is the ruled
/// continuation's departure `½·d²·κ` over the 0.0425 the plane stripe's contact
/// sits beyond the round's rim. Each stripe's own rail then runs off its face
/// into the other's, and the loops come back crossing themselves.
///
/// # When both carriers change
///
/// A straight edge running on into the crease two rounds leave where they
/// meet (a box edge beside a corner whose other two edges are filleted) hands
/// its ball over on BOTH sides: each plane runs tangent into its own round
/// across its own seam. The ball changes carrier where each contact crosses
/// its seam, and those two crossings are one section only when one ball
/// touches both seams — which the symmetric corner does, both seams being
/// the rounds' tangent rails in the vertex's normal plane. It is solved as
/// the single-seam ball on the first seam and then REQUIRED to touch the
/// second: a ball whose other contact misses its seam crosses the two at
/// different sections, and between them the ball rolls on one face of each
/// pair, a stretch no edge carries and this join does not build.
fn flush_join(
    solid: &BrepSolid,
    a: &(&EdgeRecord, BlendMate, BlendMate),
    b: &(&EdgeRecord, BlendMate, BlendMate),
    vertex_id: u64,
    vertex_point: Vec3,
    scale: f64,
) -> Result<Option<FlushJoin>, KernelRefusal> {
    let shared: Vec<&BlendMate> = [&a.1, &a.2]
        .into_iter()
        .filter(|mate| [&b.1, &b.2].iter().any(|other| other.face.id == mate.face.id))
        .collect();
    if shared.len() == 2 {
        return Ok(None);
    }
    let bounds = |face_id: u64, edge_id: u64| {
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter(|face| face.id == face_id)
            .flat_map(|face| &face.loops)
            .flat_map(|loop_record| &loop_record.coedges)
            .any(|coedge| coedge.edge_id == edge_id)
    };
    // A seam: an edge at the vertex bordering one carrier of each stripe,
    // other than the two selected edges.
    let seam_between = |face_a: u64, face_b: u64| {
        solid.edges.iter().find(|edge| {
            (edge.start_vertex_id == vertex_id || edge.end_vertex_id == vertex_id)
                && edge.id != a.0.id
                && edge.id != b.0.id
                && bounds(face_a, edge.id)
                && bounds(face_b, edge.id)
        })
    };
    // Seated on stripe a's carrier; stripe b's must seat the SAME ball at the
    // seam contact, which is what "the side faces are tangent across the
    // seam" means. A seam with a crease would put b's ball elsewhere, and
    // there is no flush join.
    let bar = corner_station_bar(scale, a.1.rho.abs());
    let across = |mate: &BlendMate, seam_point: Vec3, center: Vec3| -> Result<(), KernelRefusal> {
        let on = crate::project_point_to_surface(&mate.face.surface, seam_point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
        let seated = blend_offset(&mate.face.surface).at(on.u, on.v, mate.rho).or_refuse(KernelStage::Refine, "at")?.point;
        let apart = seated.sub(center).length();
        if on.distance > bar || apart > bar {
            return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join", format!(
                "blend network: the side faces at the smooth vertex {vertex_id} are not tangent \
                 across their seam — the two blends seat balls {apart:.3e} apart on it \
                 ({:.3e} off face {}) — not a flush join",
                on.distance, mate.face.id
            )));
        }
        Ok(())
    };
    if let [shared] = shared.as_slice() {
        let side_of = |first: &BlendMate<'_>, second: &BlendMate<'_>| -> (u64, f64) {
            if first.face.id == shared.face.id {
                (second.face.id, second.rho)
            } else {
                (first.face.id, first.rho)
            }
        };
        let ((side_a_id, rho_a), (side_b_id, _)) = (side_of(&a.1, &a.2), side_of(&b.1, &b.2));
        let side_a = if a.1.face.id == side_a_id { a.1.face } else { a.2.face };
        let side_b = if b.1.face.id == side_b_id { &b.1 } else { &b.2 };
        let seam = seam_between(side_a.id, side_b.face.id).ok_or_else(|| {
            format!(
                "blend network: the side faces at the smooth vertex {vertex_id} differ but \
                 share no seam edge there"
            )
        }).or_refuse(KernelStage::Refine, "ok_or_else")?;
        let ball = solve_flush_seam_ball(
            shared.face,
            shared.rho,
            side_a,
            rho_a,
            seam,
            vertex_id,
            vertex_point,
            scale,
        )?;
        across(side_b, ball.seam_point, ball.center)?;
        return Ok(Some(FlushJoin {
            center: ball.center,
            contacts: [
                FlushContact {
                    faces: vec![shared.face.id],
                    point: ball.shared_point,
                    seam: None,
                },
                FlushContact {
                    faces: vec![side_a.id, side_b.face.id],
                    point: ball.seam_point,
                    seam: Some((seam.id, ball.seam_parameter)),
                },
            ],
        }));
    }
    // Neither carrier carries over: pair each of a's carriers with the one of
    // b's across a seam at the vertex.
    let pair = |mate: &BlendMate| {
        [&b.1, &b.2]
            .into_iter()
            .find_map(|other| seam_between(mate.face.id, other.face.id).map(|seam| (other, seam)))
    };
    let (Some((b_first, seam_first)), Some((b_second, seam_second))) = (pair(&a.1), pair(&a.2))
    else {
        return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join", format!(
            "blend network: both side pairs differ at the smooth vertex {vertex_id}, and not \
             each carrier runs into the other blend's across a seam there"
        )));
    };
    if b_first.face.id == b_second.face.id || seam_first.id == seam_second.id {
        return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join", format!(
            "blend network: both side pairs differ at the smooth vertex {vertex_id}, and both \
             carriers run into one face of the other blend"
        )));
    }
    // The first switch: the ball touching a's second carrier and its first ON
    // the first seam — the single-seam ball.
    let ball = solve_flush_seam_ball(
        a.2.face,
        a.2.rho,
        a.1.face,
        a.1.rho,
        seam_first,
        vertex_id,
        vertex_point,
        scale,
    )?;
    // The second switch must be the same ball: its contact on a's second
    // carrier sits ON the second seam, strictly inside it.
    let on_second = crate::project_point_to_curve(&seam_second.curve, ball.shared_point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
    let span = seam_second.t1 - seam_second.t0;
    let fraction = (on_second.u - seam_second.t0) / span;
    if on_second.distance > bar {
        return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join", format!(
            "blend network: both carriers change at the smooth vertex {vertex_id}, and the ball \
             crosses their seams at different sections — seated on seam edge {}, its contact on \
             face {} stands {:.3e} off seam edge {} — so between the two switches it rolls on \
             one face of each pair, which this join does not build",
            seam_first.id, a.2.face.id, on_second.distance, seam_second.id
        )));
    }
    if !(fraction > 1e-9 && fraction < 1.0 - 1e-9) {
        return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join_seam", format!(
            "blend network: the flush join's ball at the smooth vertex {vertex_id} touches seam \
             edge {} at fraction {fraction:.6}, off the edge itself",
            seam_second.id
        )));
    }
    across(b_first, ball.seam_point, ball.center)?;
    across(b_second, on_second.point, ball.center)?;
    Ok(Some(FlushJoin {
        center: ball.center,
        contacts: [
            FlushContact {
                faces: vec![a.1.face.id, b_first.face.id],
                point: ball.seam_point,
                seam: Some((seam_first.id, ball.seam_parameter)),
            },
            FlushContact {
                faces: vec![a.2.face.id, b_second.face.id],
                point: on_second.point,
                seam: Some((seam_second.id, on_second.u)),
            },
        ],
    }))
}

/// The parameter of `edge`'s (extended) curve whose normal plane holds
/// `point` — the march's section plane through a known ball centre — by
/// Newton from `seed`.
fn section_parameter_through(
    edge: &EdgeRecord,
    point: Vec3,
    seed: f64,
    scale: f64,
) -> Result<f64, KernelRefusal> {
    let mut t = seed;
    let tolerance = 1e-11 * (1.0 + scale);
    for _ in 0..NEWTON_ITERATIONS {
        let derivatives = edge.curve.derivatives_extended(t, 2).or_refuse(KernelStage::Refine, "derivatives_extended")?;
        let offset = point.sub(derivatives[0]);
        let speed = derivatives[1].length();
        if !(speed > 0.0) {
            return Err(KernelRefusal::internal(KernelStage::Refine, "stationary_tangent", "the edge has a stationary tangent there"));
        }
        let plane = offset.dot(derivatives[1]) / speed;
        if plane.abs() <= tolerance {
            return Ok(t);
        }
        let slope = offset.dot(derivatives[2]) - derivatives[1].dot(derivatives[1]);
        if !(slope.abs() > 0.0) {
            return Err(KernelRefusal::non_convergence(KernelStage::Refine, "section_newton", "the section Newton is singular"));
        }
        t -= offset.dot(derivatives[1]) / slope;
    }
    Err(KernelRefusal::non_convergence(KernelStage::Refine, "section_newton", "the section Newton did not converge"))
}

/// A ball seated by [`solve_flush_seam_ball`]: its centre, its contact on the
/// shared carrier, and its contact on the seam with the seam's parameter
/// there.
struct SeamBall {
    center: Vec3,
    shared_point: Vec3,
    seam_parameter: f64,
    seam_point: Vec3,
}

/// Seat the radius-`|rho_shared|` ball touching `shared` and touching `side`
/// ON the seam edge, by Newton on (the seam's pcurve parameter on `side`, the
/// shared face's (u, v)): the side carrier's offset from the seam point must
/// land on the shared carrier's offset — the station solve's own equation
/// (`tangency_state`) with the section plane replaced by the seam.
///
/// The seam is walked through its PCURVE on the side face, so every contact
/// is a point of the side carrier and the residual is smooth; a projection
/// inside the loop stalls at its own stopping bar, above this one.  The curve
/// (the side offset along the seam) meets the surface (the shared offset)
/// transversally whenever the seam leaves the shared face, so the root is
/// isolated; seeded at the vertex, it is one radius away.
#[allow(clippy::too_many_arguments)]
fn solve_flush_seam_ball(
    shared: &FaceRecord,
    rho_shared: f64,
    side: &FaceRecord,
    rho_side: f64,
    seam: &EdgeRecord,
    vertex_id: u64,
    vertex_point: Vec3,
    scale: f64,
) -> Result<SeamBall, KernelRefusal> {
    const ITERATIONS: usize = 40;
    let coedge = side
        .loops
        .iter()
        .flat_map(|loop_record| &loop_record.coedges)
        .find(|coedge| coedge.edge_id == seam.id)
        .ok_or_else(|| {
            format!("blend network: the seam edge {} is not on face {}", seam.id, side.id)
        }).or_refuse(KernelStage::Refine, "ok_or_else")?;
    // The pcurve parameter at the vertex, running with the coedge's walk.
    let [q0, q1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
    let at_start_of_edge = seam.start_vertex_id == vertex_id;
    let from_vertex = if at_start_of_edge == coedge.forward { q0 } else { q1 };
    let on_shared = crate::project_point_to_surface(&shared.surface, vertex_point).or_refuse(KernelStage::Refine, "project_point_to_surface")?;
    let mut x = [from_vertex, on_shared.u, on_shared.v];
    // (residual, centre, side contact, shared contact)
    let state = |x: &[f64; 3]| -> Result<([f64; 3], Vec3, Vec3, Vec3), KernelRefusal> {
        let uv = coedge.pcurve.evaluate(x[0]).or_refuse(KernelStage::Refine, "evaluate")?;
        let side_offset = blend_offset(&side.surface).at(uv.x, uv.y, rho_side).or_refuse(KernelStage::Refine, "at")?;
        let shared_offset = blend_offset(&shared.surface).at(x[1], x[2], rho_shared).or_refuse(KernelStage::Refine, "at")?;
        let mismatch = side_offset.point.sub(shared_offset.point);
        Ok((
            [mismatch.x, mismatch.y, mismatch.z],
            shared_offset.point,
            side_offset.source,
            shared_offset.source,
        ))
    };
    let tolerance = 1e-11 * (1.0 + scale);
    for _ in 0..ITERATIONS {
        let (residual, center, side_point, shared_point) = state(&x)?;
        if residual.iter().fold(0.0f64, |worst, value| worst.max(value.abs())) <= tolerance {
            let fraction = (x[0] - q0) / (q1 - q0);
            if !(fraction > 1e-9 && fraction < 1.0 - 1e-9) {
                return Err(KernelRefusal::unsupported(KernelStage::Refine, "flush_join_seam", format!(
                    "blend network: the flush join's ball at the smooth vertex {vertex_id} \
                     touches the seam's carrier at fraction {fraction:.6}, off the seam edge \
                     {} itself",
                    seam.id
                )));
            }
            if vertex_point.sub(center).length() < rho_shared.abs() * (1.0 - 1e-6) {
                return Err(KernelRefusal::internal(KernelStage::Refine, "flush_join_branch", format!(
                    "blend network: the flush join's ball at the smooth vertex {vertex_id} \
                     swallows the vertex — wrong branch"
                )));
            }
            // The seam is trimmed at the contact, so the rim vertex is the
            // edge's own point there, and the pcurve must agree with it.
            let on_seam = crate::project_point_to_curve(&seam.curve, side_point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
            let bar = corner_station_bar(scale, rho_shared.abs());
            if on_seam.distance > bar {
                return Err(KernelRefusal::internal(KernelStage::Refine, "seam_pcurve", format!(
                    "blend network: the seam edge {}'s pcurve on face {} runs {:.3e} off the \
                     edge at the flush join's contact (smooth vertex {vertex_id})",
                    seam.id, side.id, on_seam.distance
                )));
            }
            return Ok(SeamBall {
                center,
                shared_point,
                seam_parameter: on_seam.u,
                seam_point: on_seam.point,
            });
        }
        let step = 1e-7;
        let mut jacobian = [[0.0f64; 3]; 3];
        for column in 0..3 {
            let mut probe = x;
            // The pcurve parameter starts at an END of its domain; probe inward.
            let signed = if column == 0 && x[0] + step > q0.max(q1) {
                -step
            } else {
                step
            };
            probe[column] += signed;
            let (probed, ..) = state(&probe)?;
            for row in 0..3 {
                jacobian[row][column] = (probed[row] - residual[row]) / signed;
            }
        }
        let delta = crate::fit::solve_small::<3>(jacobian, residual, 3).map_err(|error| {
            format!(
                "blend network: the flush join's seam ball at the smooth vertex {vertex_id} is \
                 singular ({error})"
            )
        }).or_refuse(KernelStage::Refine, "map_err")?;
        for (value, correction) in x.iter_mut().zip(delta) {
            *value -= correction;
        }
        x[0] = x[0].clamp(q0.min(q1), q0.max(q1));
    }
    Err(KernelRefusal::non_convergence(KernelStage::Refine, "flush_join_ball", format!(
        "blend network: the flush join's seam ball at the smooth vertex {vertex_id} did not \
         converge"
    )))
}

/// How a PERIODIC mate's loop, left open at both seam coedges by a blend
/// that ate the seam's rim end, is closed again: by splitting the rail that
/// CROSSES the seam meridian, or — when this operation's rails already MEET
/// on the meridian — by re-footing the seam on their shared rim vertex.
pub(in crate::blend) enum CarrierSeamRepair {
    Split(CarrierSeamSplit),
    Trim(CarrierSeamTrim),
}

/// One planned re-footing of a PERIODIC mate's seam edge on the rim vertex
/// two of this operation's rails share ON the seam meridian.
///
/// A flush join whose vertex section contains the seam line — a bore's flat
/// mouth, where the top face is normal to the bore's axis, so the section
/// at the rim's seam vertex is the plane through the axis — puts the rim
/// vertex both stripes stop at exactly on the meridian: the rail leaving the
/// arriving seam coedge starts there and the rail reaching the leaving seam
/// coedge ends there, no rail crosses the meridian, and the seam edge still
/// ends at the vertex the blend ate.  The loop is open at the two seam
/// coedges exactly as in the crossing case, and the repair is the split's
/// without the split.
pub(in crate::blend) struct CarrierSeamTrim {
    face_id: u64,
    loop_index: usize,
    /// Position in the loop of the rail coedge that LEAVES the arriving seam
    /// coedge's meridian, and of the one that ARRIVES on the leaving seam
    /// coedge's meridian; one and the same when a single closed rail wraps
    /// the carrier.
    leaving_position: usize,
    arriving_position: usize,
    seam_edge: u64,
    /// The vertex the blend ate, which the seam edge still ends at.
    dangling_vertex: u64,
    /// The rim vertex the two rails share, on the meridian.
    rim_vertex: u64,
    /// The mate's u level each seam coedge rides.
    level_in: f64,
    level_out: f64,
    period: f64,
}

/// One planned split of a blend rail on a PERIODIC mate's seam meridian.
pub(in crate::blend) struct CarrierSeamSplit {
    face_id: u64,
    loop_index: usize,
    /// Position in the loop of the coedge that crosses the meridian.
    crossing_position: usize,
    /// Positions of the two seam coedges, the one ARRIVING at the eaten
    /// vertex and the one LEAVING it.
    seam_in_position: usize,
    seam_out_position: usize,
    seam_edge: u64,
    /// The vertex the blend ate, which the seam edge still ends at.
    dangling_vertex: u64,
    /// The mate's u level each seam coedge rides.
    level_in: f64,
    level_out: f64,
    period: f64,
    rail_edge: u64,
    /// Parameter on the rail edge's own curve where it crosses the meridian.
    rail_parameter: f64,
    // A capped rail can cross the seam while the vertex walk stays closed.
    // These cap coedges move with its wrapped piece to the other seam image.
    wrapped: Vec<usize>,
    wrapped_before: bool,
}

/// The traversal endpoints of a coedge: its walk runs start -> end, which is
/// the edge's t0 -> t1 only when the coedge is forward.
fn coedge_walk(solid: &BrepSolid, coedge: &CoedgeRecord) -> Result<(u64, u64), KernelRefusal> {
    let edge = solid
        .edges
        .iter()
        .find(|edge| edge.id == coedge.edge_id)
        .ok_or(KernelRefusal::internal(KernelStage::Refine, "missing_edge", "blend network: loop references a missing edge"))?;
    Ok(if coedge.forward {
        (edge.start_vertex_id, edge.end_vertex_id)
    } else {
        (edge.end_vertex_id, edge.start_vertex_id)
    })
}

/// The u range a coedge's pcurve covers, sampled (a fitted rail is not
/// monotone in its control points).
fn pcurve_u_range(pcurve: &NurbsCurve) -> Result<(f64, f64), KernelRefusal> {
    let [q0, q1] = pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
    let (mut low, mut high) = (f64::INFINITY, f64::NEG_INFINITY);
    for index in 0..=SEAM_SAMPLES {
        let q = q0 + (q1 - q0) * index as f64 / SEAM_SAMPLES as f64;
        let u = pcurve.evaluate(q).or_refuse(KernelStage::Refine, "evaluate")?.x;
        low = low.min(u);
        high = high.max(u);
    }
    Ok((low, high))
}

/// Sample count for the seam-crossing bracket and its bisection budget: the
/// rail is a cubic fit, so a 256-interval bracket cannot step over a single
/// crossing, and 64 bisections take the bracket to double precision.
const SEAM_SAMPLES: usize = 256;
const SEAM_BISECTIONS: usize = 64;

/// The pcurve parameter where `pcurve`'s u reaches `level`, bracketed on a
/// dense sample and bisected — no derivative, so a fitted rail that grazes the
/// meridian cannot send a Newton off the end of the row.
fn pcurve_u_crossing(pcurve: &NurbsCurve, level: f64) -> Result<Option<f64>, KernelRefusal> {
    let [q0, q1] = pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
    let at = |q: f64| -> Result<f64, KernelRefusal> { Ok(pcurve.evaluate(q).or_refuse(KernelStage::Refine, "evaluate")?.x - level) };
    // An already split rail ends on this meridian. Its endpoint is not a
    // new seam split; keep searching for an interior crossing. Use the same
    // normalized interior guard as apply_carrier_seam_split.
    let interior = |q: f64| (1e-9..=1.0 - 1e-9).contains(&((q - q0) / (q1 - q0)));
    let mut previous = (q0, at(q0)?);
    for index in 1..=SEAM_SAMPLES {
        let q = q0 + (q1 - q0) * index as f64 / SEAM_SAMPLES as f64;
        let value = at(q)?;
        if previous.1 == 0.0 && interior(previous.0) {
            return Ok(Some(previous.0));
        }
        if (previous.1 < 0.0) != (value < 0.0) {
            let (mut low, mut high) = (previous, (q, value));
            for _ in 0..SEAM_BISECTIONS {
                let mid = 0.5 * (low.0 + high.0);
                let value = at(mid)?;
                if (low.1 < 0.0) != (value < 0.0) {
                    high = (mid, value);
                } else {
                    low = (mid, value);
                }
            }
            let crossing = 0.5 * (low.0 + high.0);
            if interior(crossing) {
                return Ok(Some(crossing));
            }
        }
        previous = (q, value);
    }
    Ok(None)
}


/// Plan the seam split for one mate face, or `None` when its loops close.
///
/// A carrier closed in u carries its seam as ONE edge used TWICE by the same
/// loop, running from the far rim up to a vertex on the rim being blended.
/// When the selection blends the WHOLE of that rim, the new contact rail wraps
/// the carrier and crosses the meridian, while the seam edge still ends at the
/// vertex the blend ate: the loop is then open at both seam coedges.  The
/// repair keeps the carrier's seam-in-one-loop structure — the same structure
/// `edge/closed.rs` preserves for a closed blended rim — by splitting the
/// crossing rail at the meridian and trimming the seam to it.
pub(in crate::blend) fn plan_carrier_seam_split(
    result: &BrepSolid,
    rail_edges: &[u64],
    face_id: u64,
) -> Result<Option<CarrierSeamRepair>, KernelRefusal> {
    let face = result
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .find(|face| face.id == face_id)
        .ok_or(KernelRefusal::internal(
            KernelStage::Sew,
            "mate_face",
            "blend network: mate face lost before the seam split",
        ))?;
    if !face
        .surface
        .closed_directions()
        .or_refuse(KernelStage::Refine, "closed_directions")?
        .0
    {
        return Ok(None);
    }
    let [u0, u1] = face
        .surface
        .domain_u()
        .or_refuse(KernelStage::Refine, "domain_u")?;
    let period = u1 - u0;
    if !(period > 0.0) {
        return Ok(None);
    }
    for (loop_index, loop_record) in face.loops.iter().enumerate() {
        let count = loop_record.coedges.len();
        if count < 3 {
            continue;
        }
        let mut walks = Vec::with_capacity(count);
        for coedge in &loop_record.coedges {
            walks.push(coedge_walk(result, coedge)?);
        }
        let breaks: Vec<usize> = (0..count)
            .filter(|&index| walks[index].1 != walks[(index + 1) % count].0)
            .collect();
        if breaks.is_empty() {
            if let Some(plan) = plan_capped_seam_split(result, rail_edges, face, loop_index, &walks, period)? {
                return Ok(Some(CarrierSeamRepair::Split(plan)));
            }
        }
        // Each eaten seam end leaves two breaks. A split carrier can have
        // more than one such end in this loop; require every break to belong
        // to exactly one identifiable, double-used seam before repairing any.
        if breaks.len() < 2 || breaks.len() % 2 != 0 {
            continue;
        }
        // One break follows the seam coedge ARRIVING at the eaten vertex, the
        // other precedes the one LEAVING it.  Which of the two comes first in
        // the stored array depends on where the loop happens to start, so try
        // both readings rather than assuming the arriving one leads.
        let read = |arriving_break: usize, leaving_break: usize| {
            let seam_in_position = arriving_break;
            let seam_out_position = (leaving_break + 1) % count;
            let seam_edge = loop_record.coedges[seam_in_position].edge_id;
            let paired = loop_record.coedges[seam_out_position].edge_id == seam_edge
                && loop_record
                    .coedges
                    .iter()
                    .filter(|coedge| coedge.edge_id == seam_edge)
                    .count()
                    == 2
                && walks[seam_in_position].1 == walks[seam_out_position].0;
            paired.then_some((seam_in_position, seam_out_position, seam_edge))
        };
        let mut pairs = Vec::new();
        for &arriving in &breaks {
            for &leaving in &breaks {
                if arriving != leaving {
                    if let Some(pair) = read(arriving, leaving) {
                        pairs.push(pair);
                    }
                }
            }
        }
        if breaks.iter().any(|&index| {
            pairs
                .iter()
                .filter(|&&(incoming, outgoing, _)| {
                    incoming == index || (outgoing + count - 1) % count == index
                })
                .count()
                != 1
        }) {
            continue;
        }
        for (seam_in_position, seam_out_position, seam_edge) in pairs {
            let dangling_vertex = walks[seam_in_position].1;
            // The u level each seam coedge rides, read at the eaten end.
            let level_at = |position: usize| -> Result<f64, KernelRefusal> {
                let coedge = &loop_record.coedges[position];
                let [q0, q1] = coedge
                    .pcurve
                    .domain()
                    .or_refuse(KernelStage::Refine, "domain")?;
                // The end that meets the eaten vertex: the walk's END for the
                // arriving coedge, its START for the leaving one.  A coedge's walk
                // runs its pcurve domain low -> high only when it is forward.
                let at_walk_end = position == seam_in_position;
                Ok(coedge
                    .pcurve
                    .evaluate(if at_walk_end == coedge.forward {
                        q1
                    } else {
                        q0
                    })
                    .or_refuse(KernelStage::Refine, "evaluate")?
                    .x)
            };
            let level_in = level_at(seam_in_position)?;
            let level_out = level_at(seam_out_position)?;
            // This operation's rails may already MEET on the meridian instead
            // of crossing it (`CarrierSeamTrim`): the rail right after the
            // arriving seam coedge and the one right before the leaving seam
            // coedge share one rim vertex, and that vertex lies ON the seam
            // curve.  The decision is the 3D one, at `seam_meeting_reach`: a
            // rim vertex genuinely off the meridian — a mouth tilted a hair
            // off normal — is a crossing for the search below, not a meeting,
            // however close its rail's uv end reads to the level, because the
            // trim re-foots the seam on the vertex and so inherits the whole
            // offset as an endpoint off its curve.  Asked before the crossing
            // search, not after it, so that a split is never cut closer to a
            // rail's end than the reach (the piece it would leave is an edge
            // of that length).  The uv ends are then required within the
            // split's own snap band, the row's uv fit being what the trim
            // commits to the level.
            let leaving_position = (seam_in_position + 1) % count;
            let arriving_position = (seam_out_position + count - 1) % count;
            let leaving = &loop_record.coedges[leaving_position];
            let arriving = &loop_record.coedges[arriving_position];
            let rim_vertex = walks[leaving_position].0;
            let on_seam = if rail_edges.contains(&leaving.edge_id)
                && rail_edges.contains(&arriving.edge_id)
                && rim_vertex == walks[arriving_position].1
                && rim_vertex != dangling_vertex
            {
                let seam = result
                    .edges
                    .iter()
                    .find(|edge| edge.id == seam_edge)
                    .ok_or(KernelRefusal::internal(KernelStage::Sew, "carrier_seam_edge", "blend network: the carrier seam edge vanished"))?;
                let point = result
                    .vertices
                    .iter()
                    .find(|vertex| vertex.id == rim_vertex)
                    .ok_or(KernelRefusal::internal(KernelStage::Sew, "seam_rim_vertex", "blend network: the rails' shared rim vertex vanished"))?
                    .point;
                let off = crate::project_point_to_curve(&seam.curve, point).or_refuse(KernelStage::Refine, "project_point_to_curve")?.distance;
                let reach = seam_meeting_reach(result);
                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
                    eprintln!("carrier seam: rim vertex {rim_vertex} off the seam curve by {off:.3e} (reach {reach:.3e})");
                }
                off <= reach
            } else {
                false
            };
            if on_seam {
                let walk_end_u = |coedge: &CoedgeRecord, at_end: bool| -> Result<f64, KernelRefusal> {
                    let [q0, q1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
                    Ok(coedge
                        .pcurve
                        .evaluate(if at_end { q1 } else { q0 })
                        .or_refuse(KernelStage::Refine, "evaluate")?
                        .x)
                };
                let snap_band = 1e-3 * period;
                if (walk_end_u(leaving, false)? - level_in).abs() <= snap_band
                    && (walk_end_u(arriving, true)? - level_out).abs() <= snap_band
                {
                    return Ok(Some(CarrierSeamRepair::Trim(CarrierSeamTrim {
                        face_id,
                        loop_index,
                        leaving_position,
                        arriving_position,
                        seam_edge,
                        dangling_vertex,
                        rim_vertex,
                        level_in,
                        level_out,
                        period,
                    })));
                }
            }
            // The rail that crosses one of those meridians, strictly inside its
            // own u range.  Only a rail this operation just built is eligible:
            // pre-existing trims are never re-cut here.
            let band = 1e-9 * period;
            for (position, coedge) in loop_record.coedges.iter().enumerate() {
                if !rail_edges.contains(&coedge.edge_id) {
                    continue;
                }
                let (low, high) = pcurve_u_range(&coedge.pcurve)?;
                for level in [level_in, level_out] {
                    if low >= level - band || high <= level + band {
                        continue;
                    }
                    let Some(q) = pcurve_u_crossing(&coedge.pcurve, level)? else {
                        continue;
                    };
                    let edge = result
                        .edges
                        .iter()
                        .find(|edge| edge.id == coedge.edge_id)
                        .ok_or(KernelRefusal::internal(
                            KernelStage::Sew,
                            "crossing_rail",
                            "blend network: the crossing rail vanished",
                        ))?;
                    let [q0, q1] = coedge
                        .pcurve
                        .domain()
                        .or_refuse(KernelStage::Refine, "domain")?;
                    let walked = (q - q0) / (q1 - q0);
                    let along = if coedge.forward { walked } else { 1.0 - walked };
                    return Ok(Some(CarrierSeamRepair::Split(CarrierSeamSplit {
                        face_id,
                        loop_index,
                        crossing_position: position,
                        seam_in_position,
                        seam_out_position,
                        seam_edge,
                        dangling_vertex,
                        level_in,
                        level_out,
                        period,
                        rail_edge: edge.id,
                        rail_parameter: edge.t0 + (edge.t1 - edge.t0) * along,
                        wrapped: Vec::new(),
                        wrapped_before: false,
                    })));
                }
            }
        }
    }
    Ok(None)
}

/// A cap returns a rail to the original sharp vertex, so its loop stays
/// connected even when the rail crosses a periodic seam. Move the short
/// out-of-chart cap walk with the split rail, then re-foot the seam on the
/// crossing. Only a newly built rail and a wholly wrapped adjacent walk are
/// eligible; pre-existing crossings and walks crossing back are not repaired.
fn plan_capped_seam_split(
    result: &BrepSolid,
    rail_edges: &[u64],
    face: &FaceRecord,
    loop_index: usize,
    walks: &[(u64, u64)],
    period: f64,
) -> Result<Option<CarrierSeamSplit>, KernelRefusal> {
    let coedges = &face.loops[loop_index].coedges;
    let count = coedges.len();
    let band = 1e-9 * period;
    let endpoint = |coedge: &CoedgeRecord, end: bool| -> Result<f64, KernelRefusal> {
        let [a, b] = coedge
            .pcurve
            .domain()
            .or_refuse(KernelStage::Refine, "domain")?;
        Ok(coedge
            .pcurve
            .evaluate(if end { b } else { a })
            .or_refuse(KernelStage::Refine, "evaluate")?
            .x)
    };
    for incoming in 0..count {
        let seam_edge = coedges[incoming].edge_id;
        if coedges.iter().filter(|ce| ce.edge_id == seam_edge).count() != 2 {
            continue;
        }
        let outgoing = (0..count)
            .find(|&i| i != incoming && coedges[i].edge_id == seam_edge)
            .unwrap();
        if walks[incoming].1 != walks[outgoing].0 {
            continue;
        }
        let level_in = endpoint(&coedges[incoming], true)?;
        let level_out = endpoint(&coedges[outgoing], false)?;
        if ((level_in - level_out).abs() - period).abs() > band {
            continue;
        }
        let mut meridians = true;
        for (position, level) in [(incoming, level_in), (outgoing, level_out)] {
            let (low, high) = pcurve_u_range(&coedges[position].pcurve)?;
            meridians &= (low - level).abs() <= band && (high - level).abs() <= band;
        }
        if !meridians {
            continue;
        }
        let lower = level_in.min(level_out);
        let upper = level_in.max(level_out);
        let mut path = Vec::new();
        let mut i = (incoming + 1) % count;
        while i != outgoing {
            path.push(i);
            i = (i + 1) % count;
        }
        for (offset, &position) in path.iter().enumerate() {
            let coedge = &coedges[position];
            if !rail_edges.contains(&coedge.edge_id) {
                continue;
            }
            let start = endpoint(coedge, false)?;
            let end = endpoint(coedge, true)?;
            let outside = |u: f64| u < lower - band || u > upper + band;
            let before = outside(start);
            if before == outside(end) {
                continue;
            }
            let level = if before { level_in } else { level_out };
            let off = if before { start } else { end };
            if (off - level).abs() >= period * 0.5 {
                continue;
            }
            let wrapped = if before {
                &path[..offset]
            } else {
                &path[offset + 1..]
            };
            if wrapped.is_empty() {
                continue;
            }
            let mut eligible = true;
            for &at in wrapped {
                let (low, high) = pcurve_u_range(&coedges[at].pcurve)?;
                eligible &= if off < level {
                    high <= level + band && low > level - period * 0.5
                } else {
                    low >= level - band && high < level + period * 0.5
                };
            }
            if !eligible {
                continue;
            }
            let Some(q) = pcurve_u_crossing(&coedge.pcurve, level)? else {
                continue;
            };
            let edge = result
                .edges
                .iter()
                .find(|edge| edge.id == coedge.edge_id)
                .ok_or(KernelRefusal::internal(
                    KernelStage::Sew,
                    "crossing_rail",
                    "blend network: capped rail vanished",
                ))?;
            let [q0, q1] = coedge
                .pcurve
                .domain()
                .or_refuse(KernelStage::Refine, "domain")?;
            let walked = (q - q0) / (q1 - q0);
            let along = if coedge.forward { walked } else { 1.0 - walked };
            return Ok(Some(CarrierSeamSplit {
                face_id: face.id,
                loop_index,
                crossing_position: position,
                seam_in_position: incoming,
                seam_out_position: outgoing,
                seam_edge,
                dangling_vertex: walks[incoming].1,
                level_in,
                level_out,
                period,
                rail_edge: edge.id,
                rail_parameter: edge.t0 + (edge.t1 - edge.t0) * along,
                wrapped: wrapped.to_vec(),
                wrapped_before: before,
            }));
        }
    }
    Ok(None)
}

/// Split one coedge of `edge` at `along` (a fraction of the edge's own t
/// range) into the two pieces its walk meets first and second.
fn split_coedge(
    coedge: &CoedgeRecord,
    along: f64,
    low_edge: u64,
    high_edge: u64,
    take_id: &mut dyn FnMut() -> u64,
) -> Result<[CoedgeRecord; 2], KernelRefusal> {
    let [q0, q1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
    let walked = if coedge.forward { along } else { 1.0 - along };
    let (first_pcurve, second_pcurve) = coedge.pcurve.split(q0 + (q1 - q0) * walked).or_refuse(KernelStage::Refine, "split")?;
    // The walk meets the LOW piece of the edge first only when forward.
    let (first_edge, second_edge) = if coedge.forward {
        (low_edge, high_edge)
    } else {
        (high_edge, low_edge)
    };
    Ok([
        CoedgeRecord {
            id: coedge.id,
            edge_id: first_edge,
            forward: coedge.forward,
            pcurve: first_pcurve,
        },
        CoedgeRecord {
            id: take_id(),
            edge_id: second_edge,
            forward: coedge.forward,
            pcurve: second_pcurve,
        },
    ])
}

/// Carry out one [`plan_carrier_seam_split`]: split the rail edge at the
/// meridian (3D curve, both faces' pcurves), fold the wrapped piece back into
/// the carrier's domain, re-order the mate loop around the seam, and trim the
/// seam edge to the crossing.
pub(in crate::blend) fn apply_carrier_seam_split(
    result: &mut BrepSolid,
    take_id: &mut dyn FnMut() -> u64,
    plan: CarrierSeamSplit,
) -> Result<[u64; 2], KernelRefusal> {
    let rail = result
        .edges
        .iter()
        .find(|edge| edge.id == plan.rail_edge)
        .ok_or(KernelRefusal::internal(KernelStage::Sew, "crossing_rail", "blend network: the crossing rail vanished before its split"))?
        .clone();
    let seam_curve = result
        .edges
        .iter()
        .find(|edge| edge.id == plan.seam_edge)
        .ok_or(KernelRefusal::internal(KernelStage::Sew, "carrier_seam_edge", "blend network: the carrier seam edge vanished"))?
        .curve
        .clone();
    // The pcurve seed is only as good as the row's uv fit agrees with its 3D
    // fit — the `pcurve_consistency` drift, 1.5e-4 on this carrier.  Both the
    // rail and the seam meridian are on the carrier, so their 3D distance has
    // a genuine zero: refine the parameter onto it rather than trimming the
    // seam to a point 1.5e-4 off itself.
    let rail_parameter =
        refine_seam_crossing(&rail, &seam_curve, plan.rail_parameter)?;
    let span = rail.t1 - rail.t0;
    let along = (rail_parameter - rail.t0) / span;
    if !(1e-9..=1.0 - 1e-9).contains(&along) {
        return Err(KernelRefusal::internal(KernelStage::Refine, "seam_crossing", format!(
            "blend network: the seam crossing on rail {} lands at {along:.9} of its own span — \
             the rail does not cross the carrier's meridian inside itself",
            rail.id
        )));
    }
    let crossing_point = rail.curve.evaluate(rail_parameter).or_refuse(KernelStage::Refine, "evaluate")?;
    let (low_curve, high_curve) = rail.curve.split(rail_parameter).or_refuse(KernelStage::Refine, "split")?;
    let crossing_vertex = take_id();
    result.vertices.push(VertexRecord {
        id: crossing_vertex,
        point: crossing_point,
    });
    let low_edge = take_id();
    let high_edge = take_id();
    result.edges.push(EdgeRecord {
        id: low_edge,
        curve: low_curve,
        t0: rail.t0,
        t1: rail_parameter,
        start_vertex_id: rail.start_vertex_id,
        end_vertex_id: crossing_vertex,
        degenerate: false,
        name: rail.name.clone(),
    });
    result.edges.push(EdgeRecord {
        id: high_edge,
        curve: high_curve,
        t0: rail_parameter,
        t1: rail.t1,
        start_vertex_id: crossing_vertex,
        end_vertex_id: rail.end_vertex_id,
        degenerate: false,
        name: rail.name.clone(),
    });

    // Every OTHER loop that uses the rail — the blend face's own, and any
    // neighbour that was sewn onto it — takes the two pieces in place; only
    // the carrier's loop below needs re-ordering, because only it rides the
    // seam.  Splicing everywhere means no loop is left holding an edge id
    // that no longer exists.
    let mut spliced_elsewhere = false;
    for shell in &mut result.shells {
        for face in &mut shell.faces {
            let on_carrier = face.id == plan.face_id;
            for (loop_index, loop_record) in face.loops.iter_mut().enumerate() {
                if on_carrier && loop_index == plan.loop_index {
                    continue;
                }
                let Some(position) = loop_record
                    .coedges
                    .iter()
                    .position(|coedge| coedge.edge_id == plan.rail_edge)
                else {
                    continue;
                };
                let pieces = split_coedge(
                    &loop_record.coedges[position],
                    along,
                    low_edge,
                    high_edge,
                    take_id,
                )?;
                loop_record.coedges.splice(position..=position, pieces);
                spliced_elsewhere = true;
            }
        }
    }
    if !spliced_elsewhere {
        return Err(KernelRefusal::internal(KernelStage::Refine, "rail_blend_face", format!(
            "blend network: rail {} is used only by the carrier — its blend face is missing",
            rail.id
        )));
    }

    // The mate: split, fold the out-of-domain piece one period, then place the
    // piece that leaves the arriving meridian right after the seam and the one
    // that reaches the leaving meridian right before it.
    let face = result
        .shells
        .iter_mut()
        .flat_map(|shell| &mut shell.faces)
        .find(|face| face.id == plan.face_id)
        .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend network: mate face lost during the seam split"))?;
    let loop_record = &mut face.loops[plan.loop_index];
    let mut pieces = split_coedge(
        &loop_record.coedges[plan.crossing_position],
        along,
        low_edge,
        high_edge,
        take_id,
    )?;
    let centre = 0.5 * (plan.level_in + plan.level_out);
    for piece in &mut pieces {
        let [q0, q1] = piece.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
        let middle = piece.pcurve.evaluate(0.5 * (q0 + q1)).or_refuse(KernelStage::Refine, "evaluate")?.x;
        let shift = plan.period * ((middle - centre) / plan.period).round();
        if shift != 0.0 {
            for control in piece.pcurve.control_points.iter_mut() {
                control.x -= shift * control.w;
            }
        }
    }
    // The split parameter came from the 3D crossing, which the row's uv fit
    // reproduces only to `pcurve_consistency`; commit the endpoint the two
    // pieces provably share to the meridian exactly, so the mate's loop closes
    // in parameter space as well as in space.  The correction is the fit's own
    // residual, and a larger one means this is not the meridian at all.
    let band = 1e-6 * plan.period;
    let snap_band = 1e-3 * plan.period;
    for (index_of_piece, at_end) in [(0usize, true), (1usize, false)] {
        let controls = &mut pieces[index_of_piece].pcurve.control_points;
        let index = if at_end { controls.len() - 1 } else { 0 };
        let u = controls[index].x / controls[index].w;
        let level = if (u - plan.level_in).abs() <= (u - plan.level_out).abs() {
            plan.level_in
        } else {
            plan.level_out
        };
        if (u - level).abs() > snap_band {
            return Err(KernelRefusal::internal(KernelStage::Refine, "seam_split", format!(
                "blend network: the split of rail {} lands {:.3e} from the carrier's meridian \
                 — the crossing is not on the seam",
                rail.id,
                (u - level).abs()
            )));
        }
        controls[index].x = level * controls[index].w;
    }
    // Which piece leaves the arriving meridian: the walk goes seam -> piece.
    // A coedge's pcurve is parameterized in its WALK direction whatever its
    // `forward` flag (the split above and the snap below already rely on
    // that), so the walk's start is the pcurve's start.  This used to read
    // the far end of a reversed coedge, which a rail built by the network
    // never was; the third-face trim that eats a rim's seam foot
    // (`restrict.rs`, 2026-09-26) hands this split a reversed crossing
    // coedge, and read that way neither piece "started" on the meridian.
    let walk_start_u = |piece: &CoedgeRecord| -> Result<f64, KernelRefusal> {
        let [q0, _] = piece.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
        Ok(piece.pcurve.evaluate(q0).or_refuse(KernelStage::Refine, "evaluate")?.x)
    };
    let leaving_first = (walk_start_u(&pieces[0])? - plan.level_in).abs() <= band;
    let (leaving, arriving) = if leaving_first {
        (pieces[0].clone(), pieces[1].clone())
    } else {
        (pieces[1].clone(), pieces[0].clone())
    };
    if (walk_start_u(&leaving)? - plan.level_in).abs() > band {
        return Err(KernelRefusal::internal(KernelStage::Refine, "seam_split", format!(
            "blend network: neither piece of rail {} starts on the carrier's meridian at \
             {:.6}",
            rail.id, plan.level_in
        )));
    }
    let wrapped: Vec<_> = plan.wrapped.iter().map(|&position| {
        let mut coedge = loop_record.coedges[position].clone();
        let shift = if plan.wrapped_before { plan.level_out - plan.level_in }
                    else { plan.level_in - plan.level_out };
        for control in &mut coedge.pcurve.control_points { control.x += shift * control.w; }
        coedge
    }).collect();
    let mut rebuilt = Vec::with_capacity(loop_record.coedges.len() + 1);
    for (position, coedge) in loop_record.coedges.iter().enumerate() {
        if position == plan.crossing_position || plan.wrapped.contains(&position) {
            continue;
        }
        if position == plan.seam_out_position {
            if plan.wrapped_before { rebuilt.extend(wrapped.iter().cloned()); }
            rebuilt.push(arriving.clone());
        }
        rebuilt.push(coedge.clone());
        if position == plan.seam_in_position {
            rebuilt.push(leaving.clone());
            if !plan.wrapped_before { rebuilt.extend(wrapped.iter().cloned()); }
        }
    }
    loop_record.coedges = rebuilt;

    // The seam edge now ends on the crossing instead of the eaten vertex.
    let projection = crate::project_point_to_curve(&seam_curve, crossing_point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
    // The rail is a fit; the meridian is not.  Judge their meeting against the
    // kernel's named contract for how far a fitted edge may sit from the
    // carrier it belongs to, exactly as `support_crossing_uv` does.
    let reach = crate::KernelTolerances::for_solid(result, 1e-7)
        .pcurve_consistency
        .max(1e-6 * (1.0 + crossing_point.length()));
    if projection.distance > reach {
        return Err(KernelRefusal::internal(KernelStage::Refine, "carrier_seam_edge", format!(
            "blend network: the carrier seam edge {} does not pass through the rail's meridian \
             crossing (off by {:.3e})",
            plan.seam_edge, projection.distance
        )));
    }
    trim_edge_at(
        result,
        plan.seam_edge,
        projection.u,
        plan.dangling_vertex,
        crossing_vertex,
    )?;
    result.edges.retain(|edge| edge.id != plan.rail_edge);
    Ok([low_edge, high_edge])
}

/// How far the rim vertex two rails share may sit from the carrier's seam
/// curve and still be a MEETING on the meridian (`CarrierSeamTrim`) rather
/// than a crossing to split at: the kernel's `intersection_fit`, the accuracy
/// a fitted intersection — which is what a blend rail is — is held to.
///
/// The two repairs tile at this bar.  Below it the trim re-foots the seam on
/// the vertex and the result inherits the offset as an endpoint off its curve,
/// which a fit is allowed anyway; above it the crossing search finds the rail
/// crossing the meridian (its band is `1e-9 * period` in u, `6.3e-9 * radius`
/// in 3D, under `intersection_fit`'s own `1e-8 * scale` floor for any bore
/// the solid holds — `scale` is at least the bore's diameter — and 3.8e-8
/// against 2e-6 on the report's bore) and the piece it cuts off is at least
/// this long, so never a sliver (`sliver` is a fifth of it).  Measured on the 2026-10-11
/// report's bore tilted off normal by 1e-8 .. 5e-2 rad (the rim vertex leaves
/// the seam by 0.857 * tilt): with `pcurve_consistency` (4e-3) here, tilts
/// 1e-7 .. 1e-3 took the trim and read pcurve ends 8.6e-7 .. 8.6e-4 off their
/// vertex; with no 3D reading at all, tilt 1e-2 refused in the apply step;
/// with `model` (1e-7), tilts 1e-7 and 1e-6 were split into 8.6e-8 and
/// 8.6e-7 pieces.  At this bar every tilt from 1e-5 up is split and reads
/// 1.9e-11, and the untilted report (1.8e-15 off) is still a meeting.
fn seam_meeting_reach(solid: &BrepSolid) -> f64 {
    crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit
}

/// Carry out one [`CarrierSeamTrim`]: commit the two rail ends to the
/// meridian exactly, so the mate's loop closes in parameter space as the
/// split's pieces do, and re-foot the seam edge on the rim vertex the rails
/// share.  Nothing is split and no edge is built.
pub(in crate::blend) fn apply_carrier_seam_trim(
    result: &mut BrepSolid,
    plan: CarrierSeamTrim,
) -> Result<(), KernelRefusal> {
    let seam_curve = result
        .edges
        .iter()
        .find(|edge| edge.id == plan.seam_edge)
        .ok_or(KernelRefusal::internal(KernelStage::Sew, "carrier_seam_edge", "blend network: the carrier seam edge vanished"))?
        .curve
        .clone();
    let rim_point = result
        .vertices
        .iter()
        .find(|vertex| vertex.id == plan.rim_vertex)
        .ok_or(KernelRefusal::internal(KernelStage::Sew, "seam_rim_vertex", "blend network: the rails' shared rim vertex vanished before the seam trim"))?
        .point;
    // The seam edge must pass through the rim vertex, at the reach the plan
    // was admitted on (`seam_meeting_reach`): the foot the seam is re-footed
    // on is the vertex itself, so whatever the vertex sits off the seam curve
    // by is what the seam edge's end will sit off its own curve by.
    let projection = crate::project_point_to_curve(&seam_curve, rim_point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
    let reach = seam_meeting_reach(result);
    if projection.distance > reach {
        return Err(KernelRefusal::internal(KernelStage::Refine, "carrier_seam_edge", format!(
            "blend network: the carrier seam edge {} does not pass through the rim vertex its \
             rails meet on (off by {:.3e})",
            plan.seam_edge, projection.distance
        )));
    }
    let face = result
        .shells
        .iter_mut()
        .flat_map(|shell| &mut shell.faces)
        .find(|face| face.id == plan.face_id)
        .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend network: mate face lost during the seam trim"))?;
    let loop_record = &mut face.loops[plan.loop_index];
    // The rails' ends sit on the meridian to the row's uv consistency; commit
    // them to it exactly, as the split commits its pieces' shared endpoint.
    let snap_band = 1e-3 * plan.period;
    for (position, at_end, level) in [
        (plan.leaving_position, false, plan.level_in),
        (plan.arriving_position, true, plan.level_out),
    ] {
        let controls = &mut loop_record.coedges[position].pcurve.control_points;
        let index = if at_end { controls.len() - 1 } else { 0 };
        let u = controls[index].x / controls[index].w;
        if (u - level).abs() > snap_band {
            return Err(KernelRefusal::internal(KernelStage::Refine, "seam_trim", format!(
                "blend network: the rail of edge {} ends {:.3e} from the carrier's meridian — \
                 the rails do not meet on the seam",
                loop_record.coedges[position].edge_id,
                (u - level).abs()
            )));
        }
        controls[index].x = level * controls[index].w;
    }
    trim_edge_at(
        result,
        plan.seam_edge,
        projection.u,
        plan.dangling_vertex,
        plan.rim_vertex,
    )
}

/// Refine a seam crossing seeded from the row's uv fit onto the 3D meeting of
/// the rail and the carrier's seam meridian.  Both curves lie on the carrier,
/// so their distance has a genuine minimum of zero there; a ternary search
/// over a bracket around the seed converges on it without a derivative (the
/// distance is V-shaped at a transversal crossing, and a fitted rail's
/// derivative is not worth trusting at 1e-9).
fn refine_seam_crossing(
    rail: &EdgeRecord,
    seam: &NurbsCurve,
    seed: f64,
) -> Result<f64, KernelRefusal> {
    let span = rail.t1 - rail.t0;
    let distance = |t: f64| -> Result<f64, KernelRefusal> {
        let point = rail.curve.evaluate(t).or_refuse(KernelStage::Refine, "evaluate")?;
        Ok(crate::project_point_to_curve(seam, point).or_refuse(KernelStage::Refine, "project_point_to_curve")?.distance)
    };
    // The uv fit and the 3D fit agree to the row's own accuracy, so the true
    // crossing is a small fraction of the rail away from the seed.
    let reach = (span.abs() * 0.05).max(1e-12);
    let (mut low, mut high) = (
        (seed - reach).max(rail.t0.min(rail.t1)),
        (seed + reach).min(rail.t0.max(rail.t1)),
    );
    for _ in 0..96 {
        if high - low <= 1e-15 * (1.0 + span.abs()) {
            break;
        }
        let a = low + (high - low) / 3.0;
        let b = high - (high - low) / 3.0;
        if distance(a)? <= distance(b)? {
            high = b;
        } else {
            low = a;
        }
    }
    let refined = 0.5 * (low + high);
    // Never take a refinement that is worse than the seed.
    if distance(refined)? <= distance(seed)? {
        Ok(refined)
    } else {
        Ok(seed)
    }
}