BREP_kernel 0.3.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
use super::*;

// ---------------------------------------------------------------------------
// Push a CURVED analytic face (cylinder / cone) by OFFSETTING its carrier.
//
// The methodology (user directive 2026-08-28, the architecture principle made
// literal): a face is a TRIMMED region of an infinite carrier surface. To push
// a curved face we OFFSET its untrimmed carrier surface, then re-derive the trim
// as the INTERSECTIONS of that offset surface with the (unchanged) untrimmed
// carriers of the neighbour faces — `intersect_analytic_pair` does the surface ∩
// surface, `build_pcurve_on_surface` re-trims. This is the same engine the
// boolean imprint uses; here one surface (the pushed face's) is replaced by its
// offset and the incident edges are recut.
//
// Slice 1 scope (honest refusals, never a bad solid): the PUSHED face is a
// cylinder or cone (`RuledRevolution`); its neighbours across each boundary edge
// are PLANAR. Ruled/sphere/torus neighbours and free-form pushed faces are
// deferred.
// ---------------------------------------------------------------------------

/// The exact analytic offset of a ruled-revolution CARRIER surface (cylinder or
/// cone) by `signed_distance` along its OUTWARD normal — the untrimmed surface
/// S′ whose re-intersection with the neighbour carriers gives the new trim.
///
/// A normal offset of a ruled revolution is another ruled revolution with the
/// SAME axis and half-angle: in the (axial z, radial ρ) meridian, the generatrix
/// line `ρ = rho0 + m·z` (m = dρ/dz = (rho1−rho0)/height; m = 0 for a cylinder)
/// offsets to the PARALLEL line `ρ = rho0 + m·z + δ·√(1+m²)` — a uniform radial
/// growth `grow = δ·√(1+m²)` at every z. So S′ is built by revolving the grown
/// generatrix about the SAME frame, over the SAME axial span `[0, height]` and
/// seam azimuth (`frame.x_axis`) as the source — the span keeps the neighbour
/// caps IN the surface's domain (an axis-translation offset would slide the
/// finite patch off them) and the shared seam meridian stays put.
///
/// `signed_distance > 0` grows the surface outward (radius increases). Refuses a
/// carrier whose grown radius reaches/crosses the axis at either end.
fn offset_ruled_carrier(
    surface: &NurbsSurface,
    signed_distance: f64,
    tolerance: f64,
) -> Result<NurbsSurface, String> {
    let Some(AnalyticSurface::RuledRevolution {
        frame,
        rho0,
        rho1,
        height,
    }) = surface.analytic()
    else {
        return Err("offset_ruled_carrier: face carrier is not a ruled revolution".into());
    };
    let (frame, rho0, rho1, height) = (frame.clone(), *rho0, *rho1, *height);
    let slope = (rho1 - rho0) / height;
    let grow = signed_distance * (1.0 + slope * slope).sqrt();
    let rho0_new = rho0 + grow;
    let rho1_new = rho1 + grow;
    if rho0_new <= tolerance || rho1_new <= tolerance {
        return Err(
            "offset (push): the ruled carrier collapses to or past its axis — refusing".into(),
        );
    }
    // Revolve the grown generatrix over the SAME axial span + seam azimuth.
    let start = frame.origin.add(frame.x_axis.scale(rho0_new));
    let end = frame
        .origin
        .add(frame.axis.scale(height))
        .add(frame.x_axis.scale(rho1_new));
    let generatrix = make_line(start, end)?;
    make_revolution(frame.origin, frame.axis, &generatrix, std::f64::consts::TAU)
}

/// The face's OUTWARD unit normal at its parameter-domain midpoint, oriented by
/// `same_sense` (the convention `push_face::planar_face_normal` uses).
fn outward_normal_mid(face: &FaceRecord) -> Result<(Vec3, Vec3), String> {
    let [u0, u1] = face.surface.domain_u()?;
    let [v0, v1] = face.surface.domain_v()?;
    let (um, vm) = (0.5 * (u0 + u1), 0.5 * (v0 + v1));
    let point = face.surface.evaluate(um, vm)?;
    let mut normal = face.surface.normal(um, vm)?;
    if !face.same_sense {
        normal = normal.scale(-1.0);
    }
    Ok((point, normal))
}

/// Push a CYLINDER or CONE face along its outward normal by `distance` (positive
/// grows the solid) by OFFSETTING its carrier surface and re-deriving the trim as
/// the intersection of that offset surface with the neighbour carriers.
///
/// Slice-1 scope (honest refusal, never a bad solid): a full-revolution
/// cylinder/cone SIDE face whose neighbour across every non-seam boundary edge is
/// PLANAR (its end caps). The pushed face's own periodic SEAM edge rides the
/// offset carrier's meridian; each rim edge re-intersects its cap
/// (`intersect_analytic_pair`, exact circle); the caps re-trim as planar faces.
/// Ruled/curved neighbours and non-full-revolution ruled faces are deferred.
pub fn offset_ruled_face(
    solid: &BrepSolid,
    face_id: u64,
    distance: f64,
) -> Result<BrepSolid, String> {
    if !distance.is_finite() {
        return Err("offset_ruled_face: distance must be finite".into());
    }
    let scale = solid_model_scale(solid);
    let tolerance = (scale * 1e-7).max(1e-9);
    let plane_tolerance = (scale * 1e-6).max(1e-7);

    let (pshell, pface) =
        find_face(solid, face_id).ok_or_else(|| format!("offset_ruled_face: no face {face_id}"))?;
    let pushed = &solid.shells[pshell].faces[pface];
    let Some(AnalyticSurface::RuledRevolution { frame, .. }) = pushed.surface.analytic() else {
        return Err("offset_ruled_face: the pushed face is not a cylinder or cone".into());
    };
    let (frame_origin, frame_axis) = (frame.origin, frame.axis);

    // Sign the offset: the carrier grows outward (radius +) along the face's
    // OUTWARD normal. If that normal points radially inward (a hole wall), a
    // positive push shrinks the radius.
    let (mid_point, mid_normal) = outward_normal_mid(pushed)?;
    let radial = {
        let d = mid_point.sub(frame_origin);
        d.sub(frame_axis.scale(d.dot(frame_axis)))
    };
    if radial.length() <= tolerance {
        return Err("offset_ruled_face: degenerate radial direction (face on the axis)".into());
    }
    let outward_sign = if mid_normal.dot(radial) >= 0.0 { 1.0 } else { -1.0 };
    let signed_distance = distance * outward_sign;

    let s_prime = offset_ruled_carrier(&pushed.surface, signed_distance, tolerance)?;

    // Edge -> incident faces, to classify each of the pushed face's boundary
    // edges as a SEAM (both incidences are the pushed face) or a RIM (the other
    // face is the fixed neighbour cap).
    let mut faces_of_edge: HashMap<u64, Vec<u64>> = HashMap::default();
    for shell in &solid.shells {
        for face in &shell.faces {
            for loop_record in &face.loops {
                for coedge in &loop_record.coedges {
                    faces_of_edge
                        .entry(coedge.edge_id)
                        .or_default()
                        .push(face.id);
                }
            }
        }
    }
    let edge_by_id: HashMap<u64, &EdgeRecord> =
        solid.edges.iter().map(|edge| (edge.id, edge)).collect();

    let mut new_curve: HashMap<u64, NurbsCurve> = HashMap::default();
    let mut new_vertex: HashMap<u64, Vec3> = HashMap::default();
    let mut cap_faces: HashSet<u64> = HashSet::default();
    // Coaxial ruled neighbours (a stepped/telescoping bore or boss: a cylinder
    // meeting a coaxial cone, or two coaxial cones) — retrimmed on their own
    // (axially-grown) carriers rather than as planar caps.
    let mut ruled_faces: HashSet<u64> = HashSet::default();
    // CURVED neighbours re-intersected through the shared generic lane — a
    // sphere dome, a fillet torus, a general revolution, a non-coaxial
    // cylinder. Their carriers do NOT move and need no growth (unlike a plane's
    // finite patch or a ruled band's axial span, a sphere's and a torus's
    // domains are already closed over their whole surface, and a re-intersected
    // rim by construction lands on the carrier it was intersected with), so
    // they are re-trimmed in place: pcurves rebuilt around the moved rim, and
    // every OTHER edge they own re-trimmed by parameter on the curve it already
    // carries — see `retrim_curved_neighbour_ranges`.
    let mut curved_faces: HashSet<u64> = HashSet::default();
    let mut seam_edges: Vec<u64> = Vec::new();
    // Current vertex positions, for rebuilding a ruled neighbour's seam whose
    // far endpoint (its unmoved rim vertex) is not relocated by any rim.
    let vertex_pos: HashMap<u64, Vec3> =
        solid.vertices.iter().map(|v| (v.id, v.point)).collect();

    // OPEN rim arcs (a multi-loop pushed face: a window / slot cut through the
    // wall). Collected here and trimmed in a second pass, once every corner
    // vertex has been solved, so both arcs meeting at a corner agree on it.
    let mut open_rims: Vec<OpenRim> = Vec::new();
    // Every RIM edge rebuilt below, closed circles and open arcs alike: the
    // pushed face's pcurves for these are refitted when a multi-loop rebuild
    // ran, because the replacement conic carries its own parameterization.
    let mut rim_edges: Vec<u64> = Vec::new();

    // PRE-PASS — a HOLE cut clean through the wall by ONE crossing carrier.
    //
    // A window bored by a crossing cylinder, a dome or a torus leaves an
    // interior loop every one of whose edges is shared with the SAME neighbour
    // face, and whose corner vertices have valence two: no third face meets
    // there, so no triple point determines them and `resolve_open_rim_end` —
    // which solves a triple point against a PLANE — has nothing to solve. The
    // loop is one closed section that the arrangement stored as arcs, and the
    // right rebuild is to re-intersect once and cut the section at the samples
    // nearest the vertices it replaces. Handled here, ahead of the per-edge
    // loop, because the decision is a property of the whole loop.
    let mut hole_edges: HashSet<u64> = HashSet::default();
    for loop_record in &pushed.loops {
        let Some(hole) = single_neighbour_hole(
            loop_record,
            face_id,
            solid,
            &faces_of_edge,
            &edge_by_id,
            frame_origin,
            frame_axis,
            scale,
        )?
        else {
            continue;
        };
        rebuild_single_neighbour_hole(
            solid,
            &s_prime,
            &hole,
            &edge_by_id,
            &vertex_pos,
            tolerance,
            scale,
            &mut new_curve,
            &mut new_vertex,
        )?;
        for edge_id in &hole.edge_ids {
            hole_edges.insert(*edge_id);
            if !rim_edges.contains(edge_id) {
                rim_edges.push(*edge_id);
            }
        }
        curved_faces.insert(hole.neighbour);
    }

    for loop_record in &pushed.loops {
        let coedge_count = loop_record.coedges.len();
        for coedge_index in 0..coedge_count {
            let coedge = &loop_record.coedges[coedge_index];
            let edge = *edge_by_id
                .get(&coedge.edge_id)
                .ok_or_else(|| format!("offset_ruled_face: missing edge {}", coedge.edge_id))?;
            if hole_edges.contains(&edge.id) {
                continue; // rebuilt whole, by the pre-pass above.
            }
            let incident = faces_of_edge.get(&edge.id).cloned().unwrap_or_default();
            let is_seam = incident.iter().all(|f| *f == face_id);
            if is_seam {
                if !seam_edges.contains(&edge.id) {
                    seam_edges.push(edge.id);
                }
                continue;
            }
            // RIM: the fixed neighbour is the other face. Three lanes, in
            // decreasing exactness and increasing generality:
            //
            //   * a PLANE (an end cap) or a ruled revolution COAXIAL with the
            //     pushed carrier (a stepped/telescoping bore or boss) — the two
            //     original lanes, whose closed forms are reached by the exact
            //     call this function has always made, unchanged;
            //   * ANY OTHER carrier — sphere, torus, general revolution,
            //     non-coaxial cylinder/cone, free-form — through the shared
            //     re-intersection service (`offset/reintersect.rs`), which tries
            //     the same closed forms first and marches the pair when they
            //     decline. This is the lane the audit's §2.3 says push-face
            //     lacks and offset-shell has.
            //
            // The generic lane is admitted only where THIS rebuild can express
            // the answer: a CLOSED rim, whose single vertex is a bookkeeping
            // seam point rather than a triple point. An open arc against a
            // curved neighbour needs `resolve_open_rim_end` to solve a triple
            // point against a curved `N'`, which it cannot (it takes a plane),
            // so that stays a refusal with its own reason.
            let neighbour = *incident
                .iter()
                .find(|f| **f != face_id)
                .ok_or_else(|| format!("offset_ruled_face: edge {} has no neighbour", edge.id))?;
            let (nshell, nface) = find_face(solid, neighbour)
                .ok_or_else(|| format!("offset_ruled_face: missing neighbour {neighbour}"))?;
            let neighbour_surface = &solid.shells[nshell].faces[nface].surface;
            let is_plane =
                matches!(neighbour_surface.analytic(), Some(AnalyticSurface::Plane { .. }));
            let is_coaxial_ruled =
                ruled_neighbour_is_coaxial(neighbour_surface, frame_origin, frame_axis, scale);
            let is_curved = !is_plane && !is_coaxial_ruled;
            let separated = || {
                "offset_ruled_face: the pushed carrier no longer meets a neighbour \
                 (the push separated them, or the rim left the neighbour's domain) — refusing"
                    .to_string()
            };
            // New rim = offset carrier ∩ neighbour carrier, the branch nearest
            // the old edge.
            let old_mid = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1))?;
            let mut marched = false;
            let curves = if is_curved {
                if edge.start_vertex_id != edge.end_vertex_id {
                    return Err(format!(
                        "offset_ruled_face: the rim against curved neighbour {neighbour} is an \
                         OPEN arc (edge {}); an arc's corner is a triple point solved against a \
                         PLANE only — deferred (refusing)",
                        edge.id
                    ));
                }
                let policy = MarchPolicy {
                    tolerance,
                    // The rebuilt rim must sit on BOTH carriers tightly enough
                    // that its pcurves build and `validate` accepts them; the
                    // free-form push's own residual gate (0.05% of model scale)
                    // is the in-tree precedent for "how far an approximate
                    // offset result may be off".
                    residual_tolerance: (scale * 5e-4).max(5e-6),
                    // The boundary being replaced is the best seed set for the
                    // boundary replacing it.
                    seeds: edge_seeds(edge, 9)?,
                };
                match reintersect_carriers(&s_prime, neighbour_surface, &policy) {
                    Ok(found) => {
                        marched = found.lane == RimLane::Marched;
                        if std::env::var("BREP_PUSH_HOLE_DEBUG").is_ok() {
                            eprintln!(
                                "RIM neighbour {neighbour}: lane {:?}, {} branch(es), \
                                 residual {:.3e} (gate {:.3e})",
                                found.lane,
                                found.sections.len(),
                                found.residual,
                                policy.residual_tolerance
                            );
                        }
                        found.curves()
                    }
                    Err(ReintersectRefusal::Separated) => return Err(separated()),
                    Err(other) => {
                        return Err(format!("offset_ruled_face: {}", other.describe()));
                    }
                }
            } else {
                // UNCHANGED: the exact call, with the same arguments in the same
                // order, so every pair this function answered before is answered
                // bit-identically now.
                intersect_analytic_pair(&s_prime, neighbour_surface, tolerance)
                    .filter(|curves| !curves.is_empty())
                    .ok_or_else(separated)?
            };
            let rim = nearest_curve(&curves, old_mid)?;
            if !rim_edges.contains(&edge.id) {
                rim_edges.push(edge.id);
            }
            if edge.start_vertex_id == edge.end_vertex_id {
                // A closed rim is a whole conic, so it must also run the way the
                // edge it replaces ran — see `match_closed_rim_direction`.
                let rim = if marched {
                    // A MARCHED section begins wherever the trace was seeded,
                    // not on the carrier's seam, so the start-tangent test would
                    // compare two unrelated places. Ask the same question at the
                    // old curve's nearest parameter instead.
                    match_marched_rim_direction(rim, edge)?
                } else {
                    match_closed_rim_direction(rim, edge)?
                };
                // CLOSED rim (the canonical cap circle of a single-loop push):
                // its seam-azimuth point is the relocated corner and matches the
                // offset carrier's meridian. A recognized carrier's u = 0 IS its
                // seam, and the shared rim's one seam vertex sits on both
                // carriers' seams, so this placement keeps the coaxial
                // neighbour's straight meridian on its carrier too. A marched
                // section has no such convention, so its own domain start is
                // where its single vertex goes — the vertex is a bookkeeping
                // split of a closed curve, not a geometric corner.
                let seam_point = if marched {
                    let [d0, _] = rim.domain()?;
                    rim.evaluate(d0)?
                } else {
                    rim.evaluate(0.0)?
                };
                new_vertex.insert(edge.start_vertex_id, seam_point);
                new_vertex.insert(edge.end_vertex_id, seam_point);
                new_curve.insert(edge.id, rim);
            } else {
                // OPEN rim: an arc / generatrix bounding a window cut through
                // the wall. `rim` is the WHOLE conic the two carriers share, so
                // each endpoint must be re-solved (it is the triple point
                // `S' ∩ N ∩ N'` against the ADJACENT rim's neighbour, or the
                // pushed carrier's own seam) and the conic trimmed between them.
                // Collapsing both onto `rim.evaluate(0.0)` — the closed-rim rule
                // — is what used to tear a multi-loop push apart.
                let previous =
                    &loop_record.coedges[(coedge_index + coedge_count - 1) % coedge_count];
                let next = &loop_record.coedges[(coedge_index + 1) % coedge_count];
                let (at_start, at_end) = if coedge.forward {
                    (previous, next)
                } else {
                    (next, previous)
                };
                let mut resolve = |adjacent_coedge: &CoedgeRecord,
                                   vertex_id: u64|
                 -> Result<RimEnd, String> {
                    let adjacent = *edge_by_id.get(&adjacent_coedge.edge_id).ok_or_else(|| {
                        format!(
                            "offset_ruled_face: missing edge {}",
                            adjacent_coedge.edge_id
                        )
                    })?;
                    let old_point = vertex_pos
                        .get(&vertex_id)
                        .copied()
                        .ok_or_else(|| format!("offset_ruled_face: missing vertex {vertex_id}"))?;
                    let (end, point) = resolve_open_rim_end(
                        solid,
                        face_id,
                        &faces_of_edge,
                        &rim,
                        adjacent,
                        old_point,
                        plane_tolerance,
                    )?;
                    // Both arcs meeting at a corner solve the SAME triple point
                    // from their own conic; a disagreement means the branch pick
                    // went to different roots, so refuse rather than tear.
                    match new_vertex.get(&vertex_id).copied() {
                        Some(existing) if existing.sub(point).length() > plane_tolerance => {
                            return Err(
                                "offset_ruled_face: the two rims meeting at a multi-loop corner \
                                 disagree on its new position — refusing"
                                    .into(),
                            )
                        }
                        Some(_) => {}
                        None => {
                            new_vertex.insert(vertex_id, point);
                        }
                    }
                    Ok(end)
                };
                let start = resolve(at_start, edge.start_vertex_id)?;
                let end = resolve(at_end, edge.end_vertex_id)?;
                open_rims.push(OpenRim {
                    edge_id: edge.id,
                    conic: rim,
                    start,
                    end,
                    old_mid,
                    start_vertex_id: edge.start_vertex_id,
                    end_vertex_id: edge.end_vertex_id,
                });
            }
            if is_plane {
                cap_faces.insert(neighbour);
            } else if is_coaxial_ruled {
                ruled_faces.insert(neighbour);
            } else {
                curved_faces.insert(neighbour);
            }
        }
    }

    // Second pass: trim each open rim's conic to the arc BETWEEN its two solved
    // corners — the one that contains the old edge, picked by the old midpoint's
    // parameter — and orient it start-vertex → end-vertex.
    for rim in &open_rims {
        let [d0, d1] = rim.conic.domain()?;
        let middle = project_point_to_curve(&rim.conic, rim.old_mid)?.u;
        let (from, to) = match (rim.start, rim.end) {
            (RimEnd::Corner(a), RimEnd::Corner(b)) => {
                let (low, high) = if a <= b { (a, b) } else { (b, a) };
                if middle < low || middle > high {
                    return Err(
                        "offset_ruled_face: a multi-loop rim arc wraps the pushed carrier's \
                         periodic seam — deferred (refusing)"
                            .into(),
                    );
                }
                (low, high)
            }
            (RimEnd::Seam, RimEnd::Corner(corner)) | (RimEnd::Corner(corner), RimEnd::Seam) => {
                if middle < corner {
                    (d0, corner)
                } else {
                    (corner, d1)
                }
            }
            (RimEnd::Seam, RimEnd::Seam) => {
                return Err(
                    "offset_ruled_face: a multi-loop rim arc ends on the seam at BOTH ends — \
                     refusing"
                        .into(),
                )
            }
        };
        let mut trimmed = subcurve(&rim.conic, from, to)?;
        let start_point = *new_vertex.get(&rim.start_vertex_id).ok_or_else(|| {
            "offset_ruled_face: a multi-loop rim corner was not relocated — refusing".to_string()
        })?;
        let end_point = *new_vertex.get(&rim.end_vertex_id).ok_or_else(|| {
            "offset_ruled_face: a multi-loop rim corner was not relocated — refusing".to_string()
        })?;
        let [t0, _] = trimmed.domain()?;
        let head = trimmed.evaluate(t0)?;
        if head.sub(start_point).length() > head.sub(end_point).length() {
            trimmed = trimmed.reversed()?;
        }
        new_curve.insert(rim.edge_id, trimmed);
    }

    let pos = |vid: u64| -> Vec3 {
        new_vertex
            .get(&vid)
            .copied()
            .unwrap_or_else(|| vertex_pos[&vid])
    };

    // Seam edge(s): the straight generatrix segment of the offset carrier, from
    // the relocated bottom seam vertex to the top one. Both endpoints were placed
    // on S′'s seam meridian by the rim re-intersections above, so a line between
    // them rides u = 0 of S′ over the SAME axial range the seam had — using the
    // full `iso_curve_u` meridian would wrongly span the untrimmed carrier (a
    // boolean-drilled wall's surface runs past the plate faces).
    for seam_id in &seam_edges {
        let seam = *edge_by_id
            .get(seam_id)
            .ok_or_else(|| format!("offset_ruled_face: missing seam edge {seam_id}"))?;
        let start = *new_vertex.get(&seam.start_vertex_id).ok_or_else(|| {
            "offset_ruled_face: seam endpoint was not relocated by a rim — refusing".to_string()
        })?;
        let end = *new_vertex.get(&seam.end_vertex_id).ok_or_else(|| {
            "offset_ruled_face: seam endpoint was not relocated by a rim — refusing".to_string()
        })?;
        new_curve.insert(*seam_id, make_line(start, end)?);
    }

    // A COAXIAL ruled neighbour also has its own straight seam meridian ending
    // at the shared rim's (now moved) seam vertex. Rebuild it as the chord
    // between its endpoints — one relocated by the rim, the other its unmoved
    // rim vertex — which, both lying on the neighbour's straight generatrix, is
    // exactly the meridian segment.
    for ruled in &ruled_faces {
        let (nshell, nface) = find_face(solid, *ruled)
            .ok_or_else(|| format!("offset_ruled_face: missing ruled neighbour {ruled}"))?;
        for loop_record in &solid.shells[nshell].faces[nface].loops {
            for coedge in &loop_record.coedges {
                let edge = *edge_by_id.get(&coedge.edge_id).ok_or_else(|| {
                    format!("offset_ruled_face: missing edge {}", coedge.edge_id)
                })?;
                let incident = faces_of_edge.get(&edge.id).cloned().unwrap_or_default();
                let is_seam = incident.iter().all(|f| *f == *ruled);
                let touches_moved = new_vertex.contains_key(&edge.start_vertex_id)
                    || new_vertex.contains_key(&edge.end_vertex_id);
                if is_seam && touches_moved && !new_curve.contains_key(&edge.id) {
                    new_curve.insert(
                        edge.id,
                        make_line(pos(edge.start_vertex_id), pos(edge.end_vertex_id))?,
                    );
                }
            }
        }
    }

    // A CURVED neighbour keeps its surface, so it keeps every 3D CURVE it owns
    // — a sphere's seam meridian is the same great-circle arc after the push as
    // before it. What changes is where that curve is TRIMMED: the endpoint the
    // moved rim carried with it slides along the curve to a new parameter.
    // Re-solving it as a parameter on the existing curve is EXACT, and it is
    // strictly better than rebuilding: the coaxial-ruled lane above can chord
    // its seam only because a ruled revolution's meridian is straight, and a
    // sphere's is not.
    let mut new_range: HashMap<u64, (f64, f64)> = HashMap::default();
    for curved in &curved_faces {
        let (nshell, nface) = find_face(solid, *curved)
            .ok_or_else(|| format!("offset_ruled_face: missing curved neighbour {curved}"))?;
        for loop_record in &solid.shells[nshell].faces[nface].loops {
            for coedge in &loop_record.coedges {
                let edge = *edge_by_id.get(&coedge.edge_id).ok_or_else(|| {
                    format!("offset_ruled_face: missing edge {}", coedge.edge_id)
                })?;
                if new_curve.contains_key(&edge.id) || new_range.contains_key(&edge.id) {
                    continue;
                }
                let start_moved = new_vertex.get(&edge.start_vertex_id).copied();
                let end_moved = new_vertex.get(&edge.end_vertex_id).copied();
                if start_moved.is_none() && end_moved.is_none() {
                    continue;
                }
                if edge.start_vertex_id == edge.end_vertex_id {
                    // A closed or degenerate edge of the neighbour (its own
                    // opposite rim, or a pole) whose vertex a rim relocated:
                    // the whole curve would have to move, which this lane does
                    // not do.
                    return Err(format!(
                        "offset_ruled_face: the push moved the vertex of curved neighbour \
                         {curved}'s CLOSED edge {} — deferred (refusing)",
                        edge.id
                    ));
                }
                let mut range = (edge.t0, edge.t1);
                for (moved, slot) in [(start_moved, 0usize), (end_moved, 1usize)] {
                    let Some(point) = moved else { continue };
                    let projection = project_point_to_curve(&edge.curve, point)?;
                    if projection.distance > plane_tolerance {
                        return Err(format!(
                            "offset_ruled_face: a relocated rim vertex left curved neighbour \
                             {curved}'s edge {} (off by {:.3e}) — refusing",
                            edge.id, projection.distance
                        ));
                    }
                    if slot == 0 {
                        range.0 = projection.u;
                    } else {
                        range.1 = projection.u;
                    }
                }
                new_range.insert(edge.id, range);
            }
        }
    }
    // Fail-safe: every relocated vertex must belong only to edges this push
    // rebuilt or re-trimmed. A vertex that also ends an edge of some other face
    // would leave that face's boundary behind, which is exactly the silent
    // tear the ruled lane's own corner guard refuses.
    if !curved_faces.is_empty() {
        for edge in &solid.edges {
            if new_curve.contains_key(&edge.id) || new_range.contains_key(&edge.id) {
                continue;
            }
            if new_vertex.contains_key(&edge.start_vertex_id)
                || new_vertex.contains_key(&edge.end_vertex_id)
            {
                return Err(format!(
                    "offset_ruled_face: relocating a curved neighbour's rim moved the end of \
                     edge {}, which this push does not rebuild — refusing",
                    edge.id
                ));
            }
        }
    }

    // A multi-loop window's corner is a TRIPLE point, so it is also the end of a
    // third edge that belongs to neither the pushed face nor a rim: the two
    // fixed neighbour planes' own shared edge (a slot floor meeting a slot
    // side wall). Both carriers are fixed, so that edge stays on their
    // intersection line and the chord between its (possibly relocated)
    // endpoints IS the rebuilt edge. Skipped entirely when no open rim was
    // rebuilt, so the single-loop paths are untouched.
    if !open_rims.is_empty() {
        let mut corner_edges: Vec<(u64, NurbsCurve)> = Vec::new();
        for edge in &solid.edges {
            if new_curve.contains_key(&edge.id) {
                continue;
            }
            if !new_vertex.contains_key(&edge.start_vertex_id)
                && !new_vertex.contains_key(&edge.end_vertex_id)
            {
                continue;
            }
            if edge.curve.degree != 1 || edge.curve.control_points.len() != 2 {
                return Err(
                    "offset_ruled_face: the push moved the end of a CURVED edge that is not a \
                     rebuilt rim — refusing"
                        .into(),
                );
            }
            let start = pos(edge.start_vertex_id);
            let end = pos(edge.end_vertex_id);
            for neighbour in faces_of_edge.get(&edge.id).cloned().unwrap_or_default() {
                if !cap_faces.contains(&neighbour) {
                    return Err(
                        "offset_ruled_face: a relocated corner borders a face this push does not \
                         re-trim — refusing"
                            .into(),
                    );
                }
                let (nshell, nface) = find_face(solid, neighbour).ok_or_else(|| {
                    format!("offset_ruled_face: missing neighbour {neighbour}")
                })?;
                let plane = plane_of_surface(
                    &solid.shells[nshell].faces[nface].surface,
                    plane_tolerance,
                    "offset_ruled_face",
                )?;
                for point in [start, end] {
                    if point.sub(plane.origin).dot(plane.normal).abs() > plane_tolerance {
                        return Err(
                            "offset_ruled_face: a relocated corner left one of its fixed \
                             neighbour planes — refusing"
                                .into(),
                        );
                    }
                }
            }
            corner_edges.push((edge.id, make_line(start, end)?));
        }
        for (edge_id, curve) in corner_edges {
            new_curve.insert(edge_id, curve);
        }
    }

    // Every edge this push touched, by curve or by trim range — the selective
    // re-fit's work list.
    let changed_edges: HashSet<u64> = new_curve
        .keys()
        .chain(new_range.keys())
        .copied()
        .collect();

    // --- Apply to a fresh clone (the input is never mutated) ---------------
    let mut result = solid.clone();
    for edge in &mut result.edges {
        if let Some(curve) = new_curve.get(&edge.id) {
            // A trimmed rim arc carries its PARENT conic's parameter range
            // (`NurbsCurve::split` preserves knot values), so the edge range
            // comes from the curve. Every whole-curve rebuild — the closed rims,
            // the seam lines — still lands on [0, 1] exactly as before.
            let [d0, d1] = curve.domain()?;
            edge.curve = curve.clone();
            edge.t0 = d0;
            edge.t1 = d1;
        } else if let Some((t0, t1)) = new_range.get(&edge.id) {
            // A curved neighbour's own edge: same curve, new trim.
            edge.t0 = *t0;
            edge.t1 = *t1;
        }
    }
    for vertex in &mut result.vertices {
        if let Some(point) = new_vertex.get(&vertex.id) {
            vertex.point = *point;
        }
    }
    // The pushed face rides the offset carrier. S′ shares the source's parameter
    // domain + seam azimuth (same make_revolution frame/span), so the face's
    // existing (u, v) pcurves stay valid when every rim stayed at its axial
    // station (the planar-cap push) — only the surface swaps.
    result.shells[pshell].faces[pface].surface = s_prime;

    let final_edges: HashMap<u64, EdgeRecord> =
        result.edges.iter().map(|e| (e.id, e.clone())).collect();

    // A COAXIAL ruled neighbour moves the shared rim ALONG the axis, so the
    // pushed face's pcurve for that rim (and the seam whose endpoint moved) is
    // no longer at its old v — refit both the pushed face and every ruled
    // neighbour on their (axially-grown-if-needed) carriers. The planar-only
    // push skips this and keeps the exact pcurve reuse above.
    //
    // A CURVED neighbour moves the shared rim just as much (a dome's rim climbs
    // the sphere as the rod it caps grows), so it joins the same pass — but its
    // own carrier neither moves nor grows: a sphere, a torus and a full
    // revolution are already closed over their whole surface, and the rim was
    // intersected WITH that surface, so it is on it by construction. Its retrim
    // is therefore the same driver with a growth that does nothing.
    if !ruled_faces.is_empty() {
        retrim_offset_ruled_face(&mut result, face_id, &final_edges, tolerance)?;
        for ruled in &ruled_faces {
            retrim_offset_ruled_face(&mut result, *ruled, &final_edges, tolerance)?;
        }
        for curved in &curved_faces {
            refit_changed_pcurves(&mut result, *curved, &final_edges, &changed_edges, tolerance)?;
        }
    } else if !curved_faces.is_empty() {
        // The pushed carrier still has to GROW where the rim climbed past its
        // axial span — the same exact prolongation the ruled lane uses — but its
        // pcurves are re-fitted selectively, not wholesale.
        let (gshell, gface) = find_face(&result, face_id)
            .ok_or_else(|| format!("offset_ruled_face: missing face {face_id}"))?;
        let samples = boundary_samples(
            &result.shells[gshell].faces[gface],
            &final_edges,
            "offset_ruled_face",
        )?;
        extend_ruled_neighbour_over(&mut result, face_id, &samples, tolerance)?;
        refit_changed_pcurves(&mut result, face_id, &final_edges, &changed_edges, tolerance)?;
        for curved in &curved_faces {
            refit_changed_pcurves(&mut result, *curved, &final_edges, &changed_edges, tolerance)?;
        }
    } else if !open_rims.is_empty() {
        // Every rebuilt RIM needs a fresh pcurve on S'. An open rim because its
        // azimuth span (an arc) or station (a generatrix) genuinely moved; a
        // CLOSED rim because the replacement circle carries the INTERSECTOR's
        // parameterization, which need not be the one the incoming curve had —
        // a boolean-cut cylinder's cap circle comes back re-parameterized, and
        // `validate` pairs pcurve to curve by FRACTION of their domains, so a
        // pointwise-identical circle with a different parameter distribution
        // still reads as a gross deviation (measured 5.96 and 12.0 on the slot
        // fixture, against a 0.394 limit).
        //
        // The SEAM edges are deliberately left alone: each is rebuilt as a
        // straight chord over the same axial range, so fraction ↦ height is
        // unchanged and their exact (u, v) — including the two coedges sitting
        // on OPPOSITE sides of the periodic seam — survives untouched.
        let rebuilt: HashSet<u64> = rim_edges.iter().copied().collect();
        let surface = result.shells[pshell].faces[pface].surface.clone();
        let [u_start, u_end] = surface.domain_u()?;
        let u_period = u_end - u_start;
        for loop_record in &mut result.shells[pshell].faces[pface].loops {
            for coedge in &mut loop_record.coedges {
                if !rebuilt.contains(&coedge.edge_id) {
                    continue;
                }
                let edge = final_edges
                    .get(&coedge.edge_id)
                    .ok_or_else(|| format!("offset_ruled_face: missing edge {}", coedge.edge_id))?;
                let mut pcurve = build_pcurve_on_surface(&surface, &edge.curve)?;
                if !coedge.forward {
                    pcurve = pcurve.reversed()?;
                }
                coedge.pcurve = reanchor_pcurve_u(&pcurve, &coedge.pcurve, u_period)?;
            }
        }
    }

    // The fixed caps re-trim as planar faces around their grown rim circles.
    for cap in &cap_faces {
        let (cshell, cface) = find_face(&result, *cap)
            .ok_or_else(|| format!("offset_ruled_face: missing cap {cap}"))?;
        let plane = plane_of_surface(
            &result.shells[cshell].faces[cface].surface,
            plane_tolerance,
            "offset_ruled_face",
        )?;
        retrim_planar_face(
            &mut result.shells[cshell].faces[cface],
            &plane,
            &final_edges,
            scale,
            "offset_ruled_face",
        )?;
    }

    let issues = result.validate();
    if !issues.is_empty() {
        return Err(format!(
            "offset_ruled_face: pushed solid failed validation: {issues:?}"
        ));
    }
    if let (Ok(before), Ok(after)) =
        (solid_signed_volume(solid), solid_signed_volume(&result))
    {
        if before * after <= 0.0 {
            return Err("offset_ruled_face: the push inverts the solid — refusing".into());
        }
    }
    Ok(result)
}

/// Where an OPEN rim arc's endpoint sits on the rebuilt conic.
#[derive(Clone, Copy)]
enum RimEnd {
    /// A genuine corner: the TRIPLE point `offset carrier ∩ this rim's
    /// neighbour ∩ the ADJACENT rim's neighbour`, carried as the conic
    /// parameter that lands on it.
    Corner(f64),
    /// The pushed carrier's periodic SEAM split this rim in two, so the
    /// endpoint rides the offset carrier's seam meridian — which is exactly
    /// parameter 0 (== 1) of the conic, because `S'` is revolved about the
    /// SAME frame and seam azimuth as the source carrier.
    Seam,
}

/// One open rim arc, held between the two passes of the rebuild.
struct OpenRim {
    edge_id: u64,
    /// The WHOLE conic `S' ∩ N`, before trimming.
    conic: NurbsCurve,
    start: RimEnd,
    end: RimEnd,
    /// The OLD edge's midpoint: picks which of the two complementary arcs
    /// between the corners is the one this edge actually was.
    old_mid: Vec3,
    start_vertex_id: u64,
    end_vertex_id: u64,
}

/// Resolve ONE endpoint of an open rim arc against the edge that follows it
/// around the loop.
///
/// Two cases, and nothing else is admitted:
/// * the adjacent edge is the pushed face's own SEAM — the endpoint rides the
///   offset carrier's seam meridian;
/// * the adjacent edge's fixed neighbour `N'` is a PLANE — the endpoint is the
///   triple point `S' ∩ N ∩ N'`, i.e. where this rim's conic (already the
///   `S' ∩ N` curve) crosses `N'`. The crossing nearest the old vertex is the
///   branch, so a conic that meets `N'` twice picks the right corner.
///
/// A conic that LIES IN `N'` means the boolean merely split one rim in two
/// (`N == N'`); there is no triple point, and the split simply keeps its
/// azimuth on the rebuilt conic. Any other adjacent neighbour (a curved
/// carrier) makes `plane_of_surface` refuse, which is the fail-safe.
fn resolve_open_rim_end(
    solid: &BrepSolid,
    face_id: u64,
    faces_of_edge: &HashMap<u64, Vec<u64>>,
    conic: &NurbsCurve,
    adjacent: &EdgeRecord,
    old_point: Vec3,
    plane_tolerance: f64,
) -> Result<(RimEnd, Vec3), String> {
    let incident = faces_of_edge.get(&adjacent.id).cloned().unwrap_or_default();
    if incident.iter().all(|f| *f == face_id) {
        let [d0, _] = conic.domain()?;
        return Ok((RimEnd::Seam, conic.evaluate(d0)?));
    }
    let other = *incident
        .iter()
        .find(|f| **f != face_id)
        .ok_or_else(|| format!("offset_ruled_face: edge {} has no neighbour", adjacent.id))?;
    let (nshell, nface) = find_face(solid, other)
        .ok_or_else(|| format!("offset_ruled_face: missing neighbour {other}"))?;
    let plane = plane_of_surface(
        &solid.shells[nshell].faces[nface].surface,
        plane_tolerance,
        "offset_ruled_face",
    )?;
    if curve_lies_in_plane(conic, &plane, plane_tolerance)? {
        let projection = project_point_to_curve(conic, old_point)?;
        return Ok((RimEnd::Corner(projection.u), conic.evaluate(projection.u)?));
    }
    let mut best: Option<(f64, f64)> = None;
    for parameter in plane_crossing_params(conic, &plane)? {
        let distance = conic.evaluate(parameter)?.sub(old_point).length();
        if best.map(|(best, _)| distance < best).unwrap_or(true) {
            best = Some((distance, parameter));
        }
    }
    let (_, parameter) = best.ok_or_else(|| {
        "offset_ruled_face: a multi-loop rim corner no longer meets its adjacent neighbour \
         (the push pulled the window off it) — refusing"
            .to_string()
    })?;
    Ok((RimEnd::Corner(parameter), conic.evaluate(parameter)?))
}

/// TRUE when the whole curve lies in the plane (so it cannot cross it): the
/// adjacent rim shares this rim's carrier plane and the shared vertex is a
/// SPLIT point, not a triple point.
fn curve_lies_in_plane(
    curve: &NurbsCurve,
    plane: &Plane,
    plane_tolerance: f64,
) -> Result<bool, String> {
    let [d0, d1] = curve.domain()?;
    for step in 0..=16 {
        let t = d0 + (d1 - d0) * step as f64 / 16.0;
        if curve
            .evaluate(t)?
            .sub(plane.origin)
            .dot(plane.normal)
            .abs()
            > plane_tolerance
        {
            return Ok(false);
        }
    }
    Ok(true)
}

/// Every parameter at which `curve` crosses `plane`, by dense sampling of the
/// signed plane distance plus bisection on each sign change. The curves here
/// are conics (a circle crosses a slot wall twice, a generatrix line crosses a
/// slot floor once), so a sampled sign-change sweep finds every root; bisection
/// then drives it to the last bit rather than to a fit tolerance.
fn plane_crossing_params(curve: &NurbsCurve, plane: &Plane) -> Result<Vec<f64>, String> {
    let [d0, d1] = curve.domain()?;
    let signed = |t: f64| -> Result<f64, String> {
        Ok(curve.evaluate(t)?.sub(plane.origin).dot(plane.normal))
    };
    const SAMPLES: usize = 512;
    let mut roots = Vec::new();
    let mut previous = (d0, signed(d0)?);
    for index in 1..=SAMPLES {
        let t = d0 + (d1 - d0) * index as f64 / SAMPLES as f64;
        let value = signed(t)?;
        if previous.1 == 0.0 {
            roots.push(previous.0);
        } else if (previous.1 < 0.0) != (value < 0.0) {
            let (mut low, mut high) = (previous.0, t);
            let mut low_value = previous.1;
            for _ in 0..100 {
                let middle = 0.5 * (low + high);
                if middle <= low || middle >= high {
                    break;
                }
                let middle_value = signed(middle)?;
                if (low_value < 0.0) != (middle_value < 0.0) {
                    high = middle;
                } else {
                    low = middle;
                    low_value = middle_value;
                }
            }
            roots.push(0.5 * (low + high));
        }
        previous = (t, value);
    }
    if previous.1 == 0.0 {
        roots.push(previous.0);
    }
    Ok(roots)
}

/// The piece of `curve` over `[from, to]`. `NurbsCurve::split` keeps the parent
/// parameterization, so the result's own domain IS `[from, to]` — which is what
/// the edge's `t0`/`t1` are then set from.
fn subcurve(curve: &NurbsCurve, from: f64, to: f64) -> Result<NurbsCurve, String> {
    let [d0, d1] = curve.domain()?;
    let span = (d1 - d0).max(1e-12);
    if to - from <= 1e-9 * span {
        return Err("offset_ruled_face: a rebuilt rim arc collapsed to a point — refusing".into());
    }
    let mut trimmed = curve.clone();
    if to < d1 - 1e-9 * span {
        trimmed = trimmed.split(to)?.0;
    }
    if from > d0 + 1e-9 * span {
        trimmed = trimmed.split(from)?.1;
    }
    Ok(trimmed)
}

/// Orient a rebuilt CLOSED rim the way the edge it replaces ran.
///
/// `intersect_analytic_pair` always emits its conics in its OWN direction
/// (increasing azimuth about the carrier frame). The edge being replaced need
/// not run that way: a wall's top and bottom cap circles are traversed in
/// OPPOSITE directions around the face loop, so one of them arrives decreasing.
/// Both are the same point set and a closed rim's two endpoints are the same
/// vertex, so `validate` cannot tell them apart — but the face's pcurve for the
/// reversed one runs `u: 1 → 0`, and handing the loop an increasing rim tears it
/// open in parameter space, which the Green's-theorem volume integral reads as a
/// completely different solid (measured 138.18 against a true 1024.11).
///
/// Decided on the START TANGENT, which is local and exact: a closed rim starts
/// on the carrier's seam and so does the rebuilt conic, so the two tangents
/// there either agree or oppose. OPEN rims are not orientated here — they are
/// trimmed to their solved corners first and then turned to run
/// start-vertex → end-vertex.
fn match_closed_rim_direction(
    rim: NurbsCurve,
    previous: &EdgeRecord,
) -> Result<NurbsCurve, String> {
    let [d0, _] = rim.domain()?;
    let incoming = previous.curve.derivatives(previous.t0, 1)?;
    let rebuilt = rim.derivatives(d0, 1)?;
    if incoming[1].dot(rebuilt[1]) < 0.0 {
        return rim.reversed();
    }
    Ok(rim)
}

/// Put a freshly fitted pcurve back on the periodic BRANCH of `u` that the
/// pcurve it replaces used, by the whole-period shift that aligns their starts.
///
/// This is not cosmetic. `build_pcurve_on_surface` CLAMPS an analytic carrier's
/// parameters into `[u0, u1]`, but a face loop on a full revolution legitimately
/// carries `u` one period PAST the domain: the two coedges of the periodic seam
/// sit on opposite sides of it, so the coedge that closes the loop across the
/// seam runs (say) `u: 1 → 2`. `validate` accepts either branch — it evaluates
/// the surface with `evaluate_extended`, which wraps — but the Green's-theorem
/// area/volume integral does NOT: it integrates the wire as drawn in parameter
/// space, and a rim dropped back to `u: 0 → 1` tears the loop open and yields a
/// nonsense volume (measured 138.18 for a solid whose true volume is 1024.11).
///
/// The replacement rim traverses the same path in the same direction as the edge
/// it replaces — only its parameter DISTRIBUTION and (for an open arc) its
/// endpoints change — so aligning the starts fixes the branch, and the endpoint
/// check refuses anything that is not merely re-anchored.
fn reanchor_pcurve_u(
    pcurve: &NurbsCurve,
    previous: &NurbsCurve,
    u_period: f64,
) -> Result<NurbsCurve, String> {
    if !(u_period.is_finite() && u_period > 0.0) {
        return Ok(pcurve.clone());
    }
    let [a0, a1] = pcurve.domain()?;
    let [b0, b1] = previous.domain()?;
    let shift = ((previous.evaluate(b0)?.x - pcurve.evaluate(a0)?.x) / u_period).round() * u_period;
    let shifted = if shift == 0.0 {
        pcurve.clone()
    } else {
        let controls = pcurve
            .control_points
            .iter()
            .map(|control| {
                let mut point = control.point()?;
                point.x += shift;
                Ok(crate::Vec4::from_point(point, control.w))
            })
            .collect::<Result<Vec<_>, String>>()?;
        NurbsCurve::new(pcurve.degree, pcurve.knots.clone(), controls)?
    };
    // Both ends must land within a quarter period of the ones they replace: a
    // rim that reversed direction, or that jumped a branch mid-curve, is not a
    // re-anchoring and must not be silently accepted.
    let end_drift = (shifted.evaluate(a1)?.x - previous.evaluate(b1)?.x).abs();
    if end_drift > 0.25 * u_period {
        return Err(format!(
            "offset_ruled_face: a rebuilt rim traverses the carrier's periodic parameter \
             differently from the edge it replaces (end drift {end_drift}) — refusing"
        ));
    }
    Ok(shifted)
}

/// TRUE when `neighbour` is a ruled revolution (cylinder or cone) sharing the
/// pushed carrier's axis LINE — same axis direction (up to sign) and the axes
/// coincident. Only such a neighbour has a closed-form re-intersection with the
/// offset carrier (`intersect_coaxial_revolutions`); the tolerances mirror that
/// intersector so an accepted neighbour is one it can actually solve.
pub(super) fn ruled_neighbour_is_coaxial(
    neighbour: &NurbsSurface,
    axis_origin: Vec3,
    axis_dir: Vec3,
    scale: f64,
) -> bool {
    let Some(AnalyticSurface::RuledRevolution { frame, .. }) = neighbour.analytic() else {
        return false;
    };
    if frame.axis.dot(axis_dir).abs() < 1.0 - 1e-9 {
        return false;
    }
    let offset = frame.origin.sub(axis_origin);
    let perpendicular = offset.sub(axis_dir.scale(offset.dot(axis_dir)));
    perpendicular.length() <= 1e-9 * scale.max(1.0)
}

/// Re-trim a ruled-revolution face (the pushed carrier itself, now S′, or a
/// coaxial ruled neighbour) whose boundary moved axially: grow the carrier along
/// its axis to cover the updated boundary (`extend_ruled_neighbour_over`, exact),
/// then rebuild every pcurve from the already-updated edge curves. The offset
/// analogue of `retrim_planar_face` — all loops are visited, so holes carry.
///
/// The three-phase body is `crate::offset_retrim::retrim_face_in_solid`; this is
/// the ruled growth strategy and the `offset_ruled_face` refusal prefix.
pub(super) fn retrim_offset_ruled_face(
    result: &mut BrepSolid,
    face_id: u64,
    final_edges: &HashMap<u64, EdgeRecord>,
    tolerance: f64,
) -> Result<(), String> {
    let (shell, face_pos) = find_face(result, face_id)
        .ok_or_else(|| format!("offset_ruled_face: missing ruled face {face_id}"))?;
    retrim_face_in_solid(
        result,
        shell,
        face_pos,
        final_edges,
        |solid, points| extend_ruled_neighbour_over(solid, face_id, points, tolerance),
        PcurveFit::SubrangeAware { tolerance },
        "offset_ruled_face",
    )
}

/// A window through the wall bounded entirely by ONE crossing carrier.
struct SingleNeighbourHole {
    neighbour: u64,
    /// Every edge of the loop, in loop order, de-duplicated.
    edge_ids: Vec<u64>,
    /// Corner vertices that are ALSO the end of one of the neighbour's own
    /// edges — its seam meridian, in every case the corpus reaches. Such a
    /// corner is NOT a free bookkeeping split: it is pinned to that meridian,
    /// so it moves along it rather than to the nearest point of the new
    /// section. `(vertex id, the neighbour edge it is pinned to)`.
    pinned: Vec<(u64, u64)>,
}

/// The axial half-plane a revolution carrier's SEAM meridian lies in.
///
/// Every seam of every revolution carrier this lane admits — a cylinder, a
/// cone, a sphere, a torus, a general revolution — is a meridian, and a
/// meridian lies in the half-plane spanned by the axis and its own radial
/// direction. So "where does the new section cross the neighbour's seam" is a
/// curve × plane crossing, in closed form, for all five at once. Returns `None`
/// for a carrier that is not a revolution or a seam that runs ON the axis.
fn seam_axial_plane(surface: &NurbsSurface, seam: &EdgeRecord) -> Option<Plane> {
    let structure = crate::revolution_structure(surface)?;
    let midpoint = seam
        .curve
        .evaluate(0.5 * (seam.t0 + seam.t1))
        .ok()?;
    let offset = midpoint.sub(structure.frame.origin);
    let radial = offset
        .sub(structure.frame.axis.scale(offset.dot(structure.frame.axis)))
        .normalized()
        .ok()?;
    let normal = structure.frame.axis.cross(radial).normalized().ok()?;
    Some(Plane {
        origin: structure.frame.origin,
        u_dir: structure.frame.axis,
        v_dir: radial,
        normal,
    })
}

/// Recognise a loop that is a hole cut by ONE crossing carrier, or say why not.
///
/// Four conditions, each of which the rebuild depends on and none of which it
/// can check afterwards:
///
/// * every coedge's other face is the SAME neighbour — otherwise a corner IS a
///   triple point and belongs to `resolve_open_rim_end`;
/// * that neighbour is neither planar nor coaxial-ruled — the two lanes with
///   their own exact rebuilds, which must keep them (bit-identity);
/// * every edge is OPEN (a closed edge is the single-rim lane's business);
/// * every corner vertex has valence two across the WHOLE solid, so relocating
///   it cannot strand a third face's boundary. This is what rules out the hole
///   that straddles the pushed carrier's periodic seam: its arcs are stitched
///   into the outer loop, so the loop fails the first condition long before the
///   valence test — and either way it is refused rather than torn.
///
/// Returns `Ok(None)` for a loop that is simply not this shape (the outer loop
/// of any ordinary push), so the caller falls through to the lanes it always
/// used.
#[allow(clippy::too_many_arguments)]
fn single_neighbour_hole(
    loop_record: &crate::topology::LoopRecord,
    face_id: u64,
    solid: &BrepSolid,
    faces_of_edge: &HashMap<u64, Vec<u64>>,
    edge_by_id: &HashMap<u64, &EdgeRecord>,
    frame_origin: Vec3,
    frame_axis: Vec3,
    scale: f64,
) -> Result<Option<SingleNeighbourHole>, String> {
    let debug = std::env::var("BREP_PUSH_HOLE_DEBUG").is_ok();
    let mut neighbour: Option<u64> = None;
    let mut edge_ids: Vec<u64> = Vec::new();
    for coedge in &loop_record.coedges {
        let edge = *edge_by_id
            .get(&coedge.edge_id)
            .ok_or_else(|| format!("offset_ruled_face: missing edge {}", coedge.edge_id))?;
        if edge.start_vertex_id == edge.end_vertex_id {
            if debug { eprintln!("HOLE reject: edge {} is closed", edge.id); }
            return Ok(None); // a closed rim: the single-rim lane owns it.
        }
        let incident = faces_of_edge.get(&edge.id).cloned().unwrap_or_default();
        let others: Vec<u64> = incident.into_iter().filter(|f| *f != face_id).collect();
        if others.len() != 1 {
            if debug { eprintln!("HOLE reject: edge {} has {} others", edge.id, others.len()); }
            return Ok(None); // a seam, or a non-manifold edge.
        }
        match neighbour {
            Some(known) if known != others[0] => {
                if debug { eprintln!("HOLE reject: mixed neighbours {known} / {}", others[0]); }
                return Ok(None);
            }
            Some(_) => {}
            None => neighbour = Some(others[0]),
        }
        if !edge_ids.contains(&edge.id) {
            edge_ids.push(edge.id);
        }
    }
    let Some(neighbour) = neighbour else {
        return Ok(None);
    };
    if edge_ids.len() < 2 {
        if debug { eprintln!("HOLE reject: only {} edges", edge_ids.len()); }
        return Ok(None);
    }
    let (nshell, nface) = find_face(solid, neighbour)
        .ok_or_else(|| format!("offset_ruled_face: missing neighbour {neighbour}"))?;
    let surface = &solid.shells[nshell].faces[nface].surface;
    if matches!(surface.analytic(), Some(AnalyticSurface::Plane { .. }))
        || ruled_neighbour_is_coaxial(surface, frame_origin, frame_axis, scale)
    {
        if debug { eprintln!("HOLE reject: neighbour {neighbour} is planar/coaxial"); }
        return Ok(None); // the two lanes that already have exact rebuilds.
    }
    // Every corner is either a free bookkeeping split (nothing else ends there)
    // or PINNED to one edge of the neighbour — its seam. Anything else ending
    // at a corner makes it a genuine junction of three or more faces, which
    // this lane does not solve.
    let neighbour_edges: HashSet<u64> = solid.shells[nshell].faces[nface]
        .loops
        .iter()
        .flat_map(|loop_record| &loop_record.coedges)
        .map(|coedge| coedge.edge_id)
        .collect();
    let mut pinned: Vec<(u64, u64)> = Vec::new();
    for edge_id in &edge_ids {
        let edge = *edge_by_id
            .get(edge_id)
            .ok_or_else(|| format!("offset_ruled_face: missing edge {edge_id}"))?;
        for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
            for other in &solid.edges {
                if other.start_vertex_id != vertex_id && other.end_vertex_id != vertex_id {
                    continue;
                }
                if edge_ids.contains(&other.id) {
                    continue;
                }
                if !neighbour_edges.contains(&other.id) {
                    if debug {
                        eprintln!("HOLE reject: vertex {vertex_id} also on foreign edge {}", other.id);
                    }
                    return Ok(None);
                }
                if pinned
                    .iter()
                    .any(|(known, pin)| *known == vertex_id && *pin != other.id)
                {
                    if debug {
                        eprintln!("HOLE reject: vertex {vertex_id} pinned by two neighbour edges");
                    }
                    return Ok(None);
                }
                if !pinned.iter().any(|(known, _)| *known == vertex_id) {
                    pinned.push((vertex_id, other.id));
                }
            }
        }
    }
    if debug {
        eprintln!("HOLE accept: neighbour {neighbour} edges {edge_ids:?} pinned {pinned:?}");
    }
    Ok(Some(SingleNeighbourHole {
        neighbour,
        edge_ids,
        pinned,
    }))
}

/// Rebuild a single-neighbour hole: re-intersect once, then cut the section.
#[allow(clippy::too_many_arguments)]
fn rebuild_single_neighbour_hole(
    solid: &BrepSolid,
    s_prime: &NurbsSurface,
    hole: &SingleNeighbourHole,
    edge_by_id: &HashMap<u64, &EdgeRecord>,
    vertex_pos: &HashMap<u64, Vec3>,
    tolerance: f64,
    scale: f64,
    new_curve: &mut HashMap<u64, NurbsCurve>,
    new_vertex: &mut HashMap<u64, Vec3>,
) -> Result<(), String> {
    let (nshell, nface) = find_face(solid, hole.neighbour)
        .ok_or_else(|| format!("offset_ruled_face: missing neighbour {}", hole.neighbour))?;
    let neighbour_surface = &solid.shells[nshell].faces[nface].surface;

    // Seed the march with the WHOLE old loop: the section replacing it runs
    // near it for any push small against the feature, and a blind seed grid on
    // two large carriers can miss a small window entirely.
    let mut seeds: Vec<Vec3> = Vec::new();
    let mut reference: Vec<Vec3> = Vec::new();
    for edge_id in &hole.edge_ids {
        let edge = *edge_by_id
            .get(edge_id)
            .ok_or_else(|| format!("offset_ruled_face: missing edge {edge_id}"))?;
        let samples = edge_seeds(edge, 9)?;
        reference.extend(samples.iter().copied());
        seeds.extend(samples);
    }
    let policy = MarchPolicy {
        tolerance,
        residual_tolerance: (scale * 5e-4).max(5e-6),
        seeds,
    };
    let found = match reintersect_carriers(s_prime, neighbour_surface, &policy) {
        Ok(found) => found,
        Err(ReintersectRefusal::Separated) => {
            return Err(
                "offset_ruled_face: the pushed carrier no longer meets a neighbour \
                 (the push separated them, or the rim left the neighbour's domain) — refusing"
                    .into(),
            )
        }
        Err(other) => return Err(format!("offset_ruled_face: {}", other.describe())),
    };
    if found.lane != RimLane::Marched {
        // An analytic section has no polyline to cut, and the exact lanes that
        // produce one already have their own arc rebuild. Refusing here keeps
        // this lane from re-deciding a case the closed forms own.
        return Err(format!(
            "offset_ruled_face: the window bounded by face {} re-intersects in CLOSED FORM, \
             whose arc rebuild is the analytic lane's — deferred (refusing)",
            hole.neighbour
        ));
    }
    if std::env::var("BREP_PUSH_HOLE_DEBUG").is_ok() {
        eprintln!(
            "HOLE rebuild neighbour {}: lane {:?}, {} branch(es), residual {:.3e} \
             (gate {:.3e})",
            hole.neighbour,
            found.lane,
            found.sections.len(),
            found.residual,
            policy.residual_tolerance
        );
    }
    // Which branch is THIS window: two windows cut by one crossing carrier
    // share a surface and so come back as two branches of one section set.
    let section = found
        .nearest_section(&reference)
        .map_err(|error| format!("offset_ruled_face: {error}"))?;

    // Corners first, so every arc is cut against the same relocated vertices.
    //
    // A corner PINNED to the neighbour's seam is not free to go to the nearest
    // sample: it must stay on that meridian, so it goes where the new section
    // CROSSES the meridian's axial half-plane. Placing it at the nearest sample
    // instead leaves it off the seam by the amount the section drifted, which
    // the neighbour's own re-trim then reports as "a relocated rim vertex left
    // curved neighbour N's edge" — a refusal where a correct answer exists.
    for edge_id in &hole.edge_ids {
        let edge = *edge_by_id
            .get(edge_id)
            .ok_or_else(|| format!("offset_ruled_face: missing edge {edge_id}"))?;
        for vertex_id in [edge.start_vertex_id, edge.end_vertex_id] {
            if new_vertex.contains_key(&vertex_id) {
                continue;
            }
            let old = *vertex_pos
                .get(&vertex_id)
                .ok_or_else(|| format!("offset_ruled_face: missing vertex {vertex_id}"))?;
            let point = match hole
                .pinned
                .iter()
                .find(|(known, _)| *known == vertex_id)
                .map(|(_, pin)| *pin)
            {
                Some(pin) => {
                    let seam = *edge_by_id
                        .get(&pin)
                        .ok_or_else(|| format!("offset_ruled_face: missing edge {pin}"))?;
                    let plane = seam_axial_plane(neighbour_surface, seam).ok_or_else(|| {
                        format!(
                            "offset_ruled_face: the window's corner is pinned to edge {pin} of a \
                             neighbour that is not a surface of revolution — refusing"
                        )
                    })?;
                    // The correct crossing is inside the window itself, so the
                    // search reach is the window's own extent about this corner
                    // — the opposite meridian cannot win.
                    let reach = reference
                        .iter()
                        .map(|point| point.sub(old).length())
                        .fold(0.0f64, f64::max)
                        .max(tolerance * 100.0);
                    curve_plane_crossing_near(&section.curve, &plane, old, reach)
                        .map(|(_, point)| point)
                        .ok_or_else(|| {
                            format!(
                                "offset_ruled_face: the rebuilt window never crosses the seam \
                                 (edge {pin}) its corner is pinned to — refusing"
                            )
                        })?
                }
                None => section_corner(section, old)
                    .map_err(|error| format!("offset_ruled_face: {error}"))?,
            };
            new_vertex.insert(vertex_id, point);
        }
    }
    for edge_id in &hole.edge_ids {
        let edge = *edge_by_id
            .get(edge_id)
            .ok_or_else(|| format!("offset_ruled_face: missing edge {edge_id}"))?;
        let from = new_vertex[&edge.start_vertex_id];
        let to = new_vertex[&edge.end_vertex_id];
        let through = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1))?;
        let arc = arc_of_section(section, from, to, through, tolerance)
            .map_err(|error| format!("offset_ruled_face: {error}"))?;
        new_curve.insert(edge.id, arc);
    }
    Ok(())
}

/// Re-fit ONLY the pcurves whose edge actually changed, each back onto the
/// periodic branch of `u` the pcurve it replaces was on.
///
/// This is the CURVED-neighbour lane's re-trim, and it is deliberately not
/// [`crate::offset_retrim::retrim_face_in_solid`]. That driver rebuilds *every*
/// pcurve of the face, which is right for a ruled revolution (whose seam
/// coedges are straight generatrices whose rebuilt pcurves land back on their
/// own sides by luck of the parameterization) and **measurably wrong** for a
/// sphere or a torus. Measured on the ball-capped rod, `d = +0.5`:
///
/// | face | rebuilt-all | correct (independently built r = 3.5 solid) |
/// |---|---|---|
/// | wall seam coedge | `u: 0 → 0` | `u: 1 → 1` |
/// | dome seam coedge | `u: 0 → 0` | `u: 1 → 1` |
/// | dome pole coedge | `(0,1) → (0,1)` | `(1,1) → (0,1)` |
///
/// with a resulting solid that `validate()` accepts and whose Green's-theorem
/// volume reads **207.86 against the true 534.10** — the dome's parameter-space
/// loop collapsed to zero area because both of its seam sides ended up on the
/// same branch. Exactly the failure [`reanchor_pcurve_u`] was written for.
///
/// Two rules together fix it, and both are needed:
/// * **touch only what moved.** A neighbour that keeps its surface keeps every
///   pcurve whose edge did not change; rebuilding one is a chance to land on
///   the wrong branch for no gain.
/// * **re-anchor what is rebuilt**, by the whole-period shift that aligns its
///   start with the pcurve it replaces — the rebuilt rim traverses the same path
///   in the same direction, so aligning the starts fixes the branch, and
///   [`reanchor_pcurve_u`]'s end-drift check refuses anything that is not
///   merely re-anchored.
fn refit_changed_pcurves(
    result: &mut BrepSolid,
    face_id: u64,
    final_edges: &HashMap<u64, EdgeRecord>,
    changed: &HashSet<u64>,
    tolerance: f64,
) -> Result<(), String> {
    let (shell, face_pos) = find_face(result, face_id)
        .ok_or_else(|| format!("offset_ruled_face: missing face {face_id}"))?;
    let surface = result.shells[shell].faces[face_pos].surface.clone();
    let [u_start, u_end] = surface.domain_u()?;
    let u_period = u_end - u_start;
    for loop_record in &mut result.shells[shell].faces[face_pos].loops {
        for coedge in &mut loop_record.coedges {
            if !changed.contains(&coedge.edge_id) {
                continue;
            }
            let edge = final_edges
                .get(&coedge.edge_id)
                .ok_or_else(|| format!("offset_ruled_face: missing edge {}", coedge.edge_id))?;
            // Same subrange rule as `PcurveFit::SubrangeAware`, so a rim that is
            // a strict piece of a full-domain curve keeps the range-aware fit it
            // has always had.
            let [d0, d1] = edge.curve.domain()?;
            let span = (d1 - d0).max(1e-12);
            let is_subrange =
                (edge.t0 - d0).abs() > 1e-9 * span || (edge.t1 - d1).abs() > 1e-9 * span;
            let pcurve = if is_subrange {
                build_pcurve_on_surface_range(
                    &surface,
                    &edge.curve,
                    edge.t0,
                    edge.t1,
                    coedge.forward,
                    tolerance,
                )?
            } else {
                let mut pcurve = build_pcurve_on_surface(&surface, &edge.curve)?;
                if !coedge.forward {
                    pcurve = pcurve.reversed()?;
                }
                pcurve
            };
            coedge.pcurve = reanchor_pcurve_u(&pcurve, &coedge.pcurve, u_period)?;
        }
    }
    Ok(())
}

/// The curve in `curves` whose midpoint is nearest `reference` (branch selection
/// for a surface∩surface intersection that returns more than one component).
fn nearest_curve(curves: &[NurbsCurve], reference: Vec3) -> Result<NurbsCurve, String> {
    let mut best: Option<(f64, &NurbsCurve)> = None;
    for curve in curves {
        let mid = curve.evaluate(0.5)?;
        let d = mid.sub(reference).length();
        if best.map(|(best_d, _)| d < best_d).unwrap_or(true) {
            best = Some((d, curve));
        }
    }
    best.map(|(_, curve)| curve.clone())
        .ok_or_else(|| "offset_ruled_face: empty intersection".into())
}

#[cfg(test)]
mod probe_tests {
    use super::*;
    use crate::{make_cone_brep, make_cylinder_brep};

    /// The radial distance of `point` from the `axis` through `origin`.
    fn radial(point: Vec3, origin: Vec3, axis: Vec3) -> f64 {
        let d = point.sub(origin);
        d.sub(axis.scale(d.dot(axis))).length()
    }

    fn side_surface(solid: &BrepSolid) -> NurbsSurface {
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .find(|face| matches!(face.surface.analytic(), Some(AnalyticSurface::RuledRevolution { .. })))
            .expect("a ruled side face")
            .surface
            .clone()
    }

    fn side_face_id(solid: &BrepSolid) -> u64 {
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .find(|face| matches!(face.surface.analytic(), Some(AnalyticSurface::RuledRevolution { .. })))
            .expect("a ruled side face")
            .id
    }

    // Push a solid cylinder's side face OUT (radius grows) and IN (radius
    // shrinks): the carrier offsets, the two caps re-trim to the new circle, and
    // the volume is exactly π r'² h.
    #[test]
    fn push_solid_cylinder_side_changes_radius() {
        let axis = Vec3::new(0.0, 0.0, 1.0);
        for (d, r_new) in [(2.0_f64, 7.0_f64), (-2.0, 3.0)] {
            let cyl = make_cylinder_brep(Vec3::default(), axis, 5.0, 10.0).unwrap();
            let side = side_face_id(&cyl);
            let pushed = offset_ruled_face(&cyl, side, d)
                .unwrap_or_else(|e| panic!("push cylinder side by {d}: {e}"));
            assert!(pushed.validate().is_empty(), "validate {d}: {:?}", pushed.validate());
            let got = solid_signed_volume(&pushed).unwrap().abs();
            let expected = std::f64::consts::PI * r_new * r_new * 10.0;
            assert!((got - expected).abs() < 1e-3, "push {d}: vol {got}, want {expected}");
        }
    }

    // A DRILLED HOLE's cylindrical wall: pushing it grows/shrinks the hole. The
    // wall's outward normal points radially INWARD (into the void), so a positive
    // push shrinks the hole (more material). The plate faces (planar, with the
    // hole as an internal loop) re-trim around the new circle.
    #[test]
    fn push_drilled_hole_wall_resizes_the_hole() {
        let plate = crate::make_box_brep(Vec3::new(0.0, 0.0, 0.0), 20.0, 20.0, 4.0).unwrap();
        let cutter = make_cylinder_brep(Vec3::new(10.0, 10.0, -1.0), Vec3::new(0.0, 0.0, 1.0), 3.0, 6.0)
            .unwrap();
        let options = crate::BooleanOptions {
            merge_coplanar_faces: true,
            ..crate::BooleanOptions::default()
        };
        let drilled =
            crate::boolean_operation(&plate, &cutter, crate::BooleanOperation::Subtract, &options)
                .unwrap();
        let v0 = solid_signed_volume(&drilled).unwrap().abs();
        let wall = side_face_id(&drilled);
        // Push the wall +1 → hole radius 3 → 2 (outward normal points inward).
        let pushed = offset_ruled_face(&drilled, wall, 1.0)
            .unwrap_or_else(|e| panic!("push drilled-hole wall: {e}"));
        assert!(pushed.validate().is_empty(), "validate: {:?}", pushed.validate());
        let got = solid_signed_volume(&pushed).unwrap().abs();
        // Material grows by the annulus π(3² − 2²)·4.
        let expected = std::f64::consts::PI * (9.0 - 4.0) * 4.0;
        assert!(
            (got - v0 - expected).abs() < 1e-3,
            "hole-shrink volume delta {}, expected {expected}",
            got - v0
        );
    }

    // Pushing the side IN by the full radius (or past it) must refuse, not emit a
    // degenerate solid.
    #[test]
    fn push_cylinder_side_through_axis_refuses() {
        let cyl = make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 10.0).unwrap();
        let side = side_face_id(&cyl);
        let err = offset_ruled_face(&cyl, side, -5.0).expect_err("collapse must refuse");
        assert!(err.contains("axis") || err.contains("refus"), "unexpected: {err}");
    }

    /// A cylinder r=5 h=10 carrying a rectangular THROUGH-SLOT: a box
    /// x ∈ [−1.5, 1.5], z ∈ [3.5, 6.5] driven all the way through in y. Its
    /// four bounding faces are PLANES, so every rim neighbour is of the
    /// supported kind (unlike a round radial bore, whose wall is a NON-coaxial
    /// ruled surface and refuses earlier — see
    /// `push_cylinder_wall_with_a_radial_bore_still_refuses`).
    fn slotted_cylinder() -> BrepSolid {
        let cyl = make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 10.0).unwrap();
        let slot = crate::make_box_brep(Vec3::new(-1.5, -9.0, 3.5), 3.0, 18.0, 3.0).unwrap();
        let options = crate::BooleanOptions {
            merge_coplanar_faces: true,
            ..crate::BooleanOptions::default()
        };
        crate::boolean_operation(&cyl, &slot, crate::BooleanOperation::Subtract, &options).unwrap()
    }

    /// The multi-loop cylindrical wall of [`slotted_cylinder`].
    fn slotted_wall_id(solid: &BrepSolid) -> u64 {
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter(|face| {
                matches!(face.surface.analytic(), Some(AnalyticSurface::RuledRevolution { .. }))
            })
            .max_by_key(|face| face.loops.len())
            .expect("a ruled side face")
            .id
    }

    /// The EXACT volume of the slotted cylinder at wall radius `r` — DERIVED,
    /// not pinned. The solid is the cylinder π r² h minus the slot, and the
    /// slot is the prism of height 3 over the strip |x| ≤ a = 1.5 of the disc
    /// of radius r. That strip's area is
    /// `∫₋ₐ^ₐ 2√(r²−x²) dx = 2(a√(r²−a²) + r² asin(a/r))`.
    fn slotted_cylinder_volume(radius: f64) -> f64 {
        let a = 1.5_f64;
        let strip =
            2.0 * (a * (radius * radius - a * a).sqrt() + radius * radius * (a / radius).asin());
        std::f64::consts::PI * radius * radius * 10.0 - 3.0 * strip
    }

    /// Push the MULTI-LOOP cylindrical wall of a through-slotted cylinder in and
    /// out (backlog #7). The wall's loops are 12 + 4 coedges: the slot's +y
    /// window is crossed by the carrier's periodic seam, so it is a notch in the
    /// outer loop, while the −y window is a clean interior loop. Every rim
    /// neighbour is a plane.
    ///
    /// The rebuild has to do three things the single-loop path never needed: use
    /// the arcs' OWN endpoints instead of collapsing both onto the seam, re-solve
    /// each slot corner as the triple point `S′ ∩ slot z-plane ∩ slot x-plane`,
    /// and trim each rim conic to the arc between them. Correctness (not just
    /// validity) is checked against the closed-form volume and against the
    /// corner positions: the x = ±1.5 walls hold, so each corner slides to
    /// `y = ±√(r′² − 1.5²)`.
    #[test]
    fn push_multiloop_cylinder_wall_resizes() {
        let slotted = slotted_cylinder();
        assert!(slotted.validate().is_empty(), "fixture: {:?}", slotted.validate());
        let wall_id = slotted_wall_id(&slotted);
        let before: Vec<usize> = slotted
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .find(|face| face.id == wall_id)
            .expect("the wall")
            .loops
            .iter()
            .map(|loop_record| loop_record.coedges.len())
            .collect();
        assert!(
            before.len() >= 2,
            "fixture must give the wall multiple loops, got {before:?}"
        );
        let base = solid_signed_volume(&slotted).unwrap().abs();
        assert!(
            (base - slotted_cylinder_volume(5.0)).abs() < 1e-3,
            "fixture volume {base}, want {}",
            slotted_cylinder_volume(5.0)
        );

        for (d, r_new) in [(1.0_f64, 6.0_f64), (-1.0, 4.0)] {
            let pushed = offset_ruled_face(&slotted, wall_id, d)
                .unwrap_or_else(|e| panic!("multi-loop wall push {d}: {e}"));
            assert!(pushed.validate().is_empty(), "validate {d}: {:?}", pushed.validate());

            let wall = pushed
                .shells
                .iter()
                .flat_map(|shell| &shell.faces)
                .find(|face| face.id == wall_id)
                .expect("the pushed wall");
            let Some(AnalyticSurface::RuledRevolution { rho0, rho1, .. }) =
                wall.surface.analytic()
            else {
                panic!("the pushed wall is no longer a ruled revolution");
            };
            assert!(
                (rho0 - r_new).abs() < 1e-9 && (rho1 - r_new).abs() < 1e-9,
                "push {d}: wall radii {rho0}/{rho1}, want {r_new}"
            );
            let after: Vec<usize> = wall
                .loops
                .iter()
                .map(|loop_record| loop_record.coedges.len())
                .collect();
            assert_eq!(after, before, "push {d} must preserve the wall's loop structure");

            // Each slot corner is the triple point of the offset wall, a slot
            // z-plane and a slot x-plane: it stays on z ∈ {3.5, 6.5} and
            // x = ±1.5, and slides along them to |y| = √(r′² − 1.5²).
            let corner_y = (r_new * r_new - 2.25_f64).sqrt();
            let mut corners = 0;
            for vertex in &pushed.vertices {
                let on_slot_plane =
                    (vertex.point.z - 3.5).abs() < 1e-9 || (vertex.point.z - 6.5).abs() < 1e-9;
                if !on_slot_plane || (vertex.point.x.abs() - 1.5).abs() > 1e-9 {
                    continue;
                }
                assert!(
                    (vertex.point.y.abs() - corner_y).abs() < 1e-6,
                    "push {d}: slot corner {:?} should sit at |y| = {corner_y}",
                    vertex.point
                );
                corners += 1;
            }
            assert_eq!(corners, 8, "push {d}: the slot has eight corner vertices");

            let expected = slotted_cylinder_volume(r_new);
            let got = solid_signed_volume(&pushed).unwrap().abs();
            assert!(
                (got - expected).abs() < 1e-3,
                "push {d}: volume {got}, want {expected} (delta {}, want {})",
                got - base,
                expected - base
            );
        }
        // The fail-safe contract: the input is never mutated.
        assert!(slotted.validate().is_empty());
    }

    /// The negative half of the same fixture: pushing the wall far enough INWARD
    /// COLLAPSES the slot. At r = 1.4 the wall no longer reaches the slot's
    /// x = ±1.5 side walls, so the window's corners cease to exist and the
    /// rebuild would need a topology change this edit cannot make. It must
    /// refuse cleanly and leave the input alone.
    #[test]
    fn push_multiloop_cylinder_wall_collapsing_the_slot_refuses() {
        let slotted = slotted_cylinder();
        let wall_id = slotted_wall_id(&slotted);
        for d in [-3.6_f64, -5.0] {
            let err = offset_ruled_face(&slotted, wall_id, d)
                .expect_err("a push that collapses the slot must refuse");
            assert!(
                err.contains("refus") || err.contains("validation"),
                "push {d} must refuse with a typed error, got: {err}"
            );
        }
        assert!(slotted.validate().is_empty());
    }

    /// The CONE analogue of the same fixture, which does NOT work: a frustum
    /// minus the same through-slot. The rim rebuild is carrier-agnostic, but
    /// the slot's x = ±1.5 walls are parallel to the cone axis, so their
    /// section of the cone is a HYPERBOLA — `intersect_plane_quadric` refuses
    /// the weight-sign flip and `intersect_analytic_pair` returns nothing. So
    /// multi-loop CONE pushes stay fail-safe-but-unsupported (backlog #7b); this
    /// pins that, and would have to be revisited before the matrix may claim
    /// the cone multi-loop cell.
    #[test]
    fn push_multiloop_cone_wall_is_fail_safe() {
        let frustum =
            make_cone_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 6.0, 3.0, 10.0).unwrap();
        let slot = crate::make_box_brep(Vec3::new(-1.5, -9.0, 3.5), 3.0, 18.0, 3.0).unwrap();
        let options = crate::BooleanOptions {
            merge_coplanar_faces: true,
            ..crate::BooleanOptions::default()
        };
        let slotted =
            crate::boolean_operation(&frustum, &slot, crate::BooleanOperation::Subtract, &options)
                .unwrap();
        assert!(slotted.validate().is_empty(), "fixture: {:?}", slotted.validate());
        let wall = slotted_wall_id(&slotted);
        for d in [1.0_f64, -1.0] {
            match offset_ruled_face(&slotted, wall, d) {
                Err(error) => assert!(
                    error.contains("refus"),
                    "push {d} must refuse with a typed error, got: {error}"
                ),
                Ok(good) => assert!(
                    good.validate().is_empty(),
                    "if the cone multi-loop push is accepted it must be valid: {:?}",
                    good.validate()
                ),
            }
        }
        assert!(slotted.validate().is_empty());
    }

    /// A ROUND radial bore through the same wall is a DIFFERENT and still
    /// unimplemented problem: the bore's wall is a NON-coaxial ruled neighbour
    /// (backlog #3b), so the multi-loop rim rebuild must never be reached. The
    /// push still refuses at neighbour classification.
    #[test]
    fn push_cylinder_wall_with_a_radial_bore_still_refuses() {
        let cyl = make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 10.0).unwrap();
        let bore =
            make_cylinder_brep(Vec3::new(0.0, -9.0, 5.0), Vec3::new(0.0, 1.0, 0.0), 1.5, 18.0)
                .unwrap();
        let options = crate::BooleanOptions {
            merge_coplanar_faces: true,
            ..crate::BooleanOptions::default()
        };
        let bored =
            crate::boolean_operation(&cyl, &bore, crate::BooleanOperation::Subtract, &options)
                .unwrap();
        assert!(bored.validate().is_empty(), "fixture: {:?}", bored.validate());
        let wall = cylinder_side_id(&bored, Vec3::new(0.0, 0.0, 1.0));
        let err = offset_ruled_face(&bored, wall, 1.0)
            .expect_err("a radial bore's seam-straddling hole must still refuse");
        // The reason MOVED when the curved-neighbour lane landed, and the move
        // is the finding: the bore's wall is no longer refused for being
        // non-coaxial (the shared re-intersection marches that pair fine), it is
        // refused because the hole it cuts STRADDLES the pushed carrier's
        // periodic seam, so one of its arcs is stitched into the outer loop and
        // the loop is not a single-neighbour ring. `tee_junction` below is the
        // same pair with the hole clear of the seam, and it now SUCCEEDS.
        assert!(
            err.contains("seam") || err.contains("OPEN arc"),
            "expected the seam-straddling refusal, got: {err}"
        );
        assert!(bored.validate().is_empty());
    }

    // Push a frustum's side face OUT: both cap radii grow by δ·√(1+m²) and the
    // volume matches the frustum formula on the grown radii.
    #[test]
    fn push_frustum_side_grows_both_radii() {
        let axis = Vec3::new(0.0, 0.0, 1.0);
        let (r_b, r_t, h, d) = (4.0_f64, 2.0_f64, 6.0_f64, 1.0_f64);
        let frustum = make_cone_brep(Vec3::default(), axis, r_b, r_t, h).unwrap();
        let side = side_face_id(&frustum);
        let pushed = offset_ruled_face(&frustum, side, d)
            .unwrap_or_else(|e| panic!("push frustum side: {e}"));
        assert!(pushed.validate().is_empty(), "validate: {:?}", pushed.validate());
        let slope = (r_t - r_b) / h;
        let grow = d * (1.0 + slope * slope).sqrt();
        let (rb, rt) = (r_b + grow, r_t + grow);
        let expected = std::f64::consts::PI * h / 3.0 * (rb * rb + rb * rt + rt * rt);
        let got = solid_signed_volume(&pushed).unwrap().abs();
        assert!((got - expected).abs() < 1e-3, "frustum push vol {got}, want {expected}");
    }

    fn cap_surface_at(solid: &BrepSolid, axis: Vec3, target_axial: f64) -> NurbsSurface {
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter(|face| matches!(face.surface.analytic(), Some(AnalyticSurface::Plane { .. })))
            .find(|face| {
                let (u, v) = (0.5, 0.5);
                let p = face.surface.evaluate(u, v).unwrap();
                (p.dot(axis) - target_axial).abs() < 1e-6
            })
            .expect("a planar cap at the target height")
            .surface
            .clone()
    }

    // Probe (advisor step 1): S′ = offset carrier RE-RECOGNIZES as a ruled
    // revolution, and S′ ∩ cap is one circle at the expected radius / height —
    // for both a cylinder (radial scale) and a cone frustum (axis translation).
    #[test]
    fn offset_carrier_recognizes_and_reintersects_the_caps() {
        let axis = Vec3::new(0.0, 0.0, 1.0);
        let tol = 1e-9;

        // --- Cylinder r=5, h=10: push out +2 → coaxial cylinder r=7 ---
        let cyl = make_cylinder_brep(Vec3::default(), axis, 5.0, 10.0).unwrap();
        let s_prime = offset_ruled_carrier(&side_surface(&cyl), 2.0, tol).unwrap();
        match s_prime.analytic() {
            Some(AnalyticSurface::RuledRevolution { rho0, rho1, .. }) => {
                assert!((rho0 - 7.0).abs() < 1e-6 && (rho1 - 7.0).abs() < 1e-6, "cyl rho {rho0},{rho1}");
            }
            other => panic!("cylinder offset must re-recognize as ruled, got {other:?}"),
        }
        for (z, want_r) in [(0.0, 7.0), (10.0, 7.0)] {
            let cap = cap_surface_at(&cyl, axis, z);
            let curves = intersect_analytic_pair(&s_prime, &cap, tol)
                .unwrap_or_else(|| panic!("no analytic intersection at z={z}"));
            assert_eq!(curves.len(), 1, "one rim circle at z={z}");
            for step in 0..=8 {
                let p = curves[0].evaluate(step as f64 / 8.0).unwrap();
                assert!((radial(p, Vec3::default(), axis) - want_r).abs() < 1e-6, "cyl rim r at z={z}");
                assert!((p.z - z).abs() < 1e-6, "cyl rim z");
            }
        }

        // --- Frustum r_bottom=4 @ z=0, r_top=2 @ z=6: push out +1 ---
        // slope m = (2−4)/6 = −1/3; radial growth δ·√(1+m²) = √(10)/3 ≈ 1.0541.
        let grow = (1.0 + (1.0f64 / 3.0).powi(2)).sqrt();
        let frustum = make_cone_brep(Vec3::default(), axis, 4.0, 2.0, 6.0).unwrap();
        let s_prime = offset_ruled_carrier(&side_surface(&frustum), 1.0, tol).unwrap();
        assert!(
            matches!(s_prime.analytic(), Some(AnalyticSurface::RuledRevolution { .. })),
            "frustum offset must re-recognize as ruled"
        );
        for (z, base_r) in [(0.0, 4.0), (6.0, 2.0)] {
            let cap = cap_surface_at(&frustum, axis, z);
            let curves = intersect_analytic_pair(&s_prime, &cap, tol)
                .unwrap_or_else(|| panic!("no frustum intersection at z={z}"));
            assert_eq!(curves.len(), 1, "one frustum rim circle at z={z}");
            let want_r = base_r + grow;
            for step in 0..=8 {
                let p = curves[0].evaluate(step as f64 / 8.0).unwrap();
                assert!(
                    (radial(p, Vec3::default(), axis) - want_r).abs() < 1e-6,
                    "frustum rim r at z={z}: got {}, want {want_r}",
                    radial(p, Vec3::default(), axis)
                );
                assert!((p.z - z).abs() < 1e-6, "frustum rim z");
            }
        }
    }

    // --- Coaxial ruled × ruled neighbours (backlog #3, coaxial subset) ------

    /// A stepped boss: a cone frustum (r 5→3 over z∈[0,4]) whose top circle
    /// coincides with a coaxial cylinder (r 3, z∈[4,10]). The union shares one
    /// circular rim at z=4 between the cone side and the cylinder side.
    fn coaxial_cone_cylinder_boss() -> BrepSolid {
        let axis = Vec3::new(0.0, 0.0, 1.0);
        let cone = make_cone_brep(Vec3::default(), axis, 5.0, 3.0, 4.0).unwrap();
        let cyl = make_cylinder_brep(Vec3::default(), axis, 3.0, 10.0).unwrap();
        let options = crate::BooleanOptions {
            merge_coplanar_faces: true,
            ..crate::BooleanOptions::default()
        };
        crate::boolean_operation(&cone, &cyl, crate::BooleanOperation::Union, &options).unwrap()
    }

    /// The id of the CYLINDER side face (a ruled revolution with rho0 == rho1)
    /// whose axis is ~parallel to `axis`.
    fn cylinder_side_id(solid: &BrepSolid, axis: Vec3) -> u64 {
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .find(|face| match face.surface.analytic() {
                Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, .. }) => {
                    (rho0 - rho1).abs() < 1e-9 && frame.axis.dot(axis).abs() > 1.0 - 1e-9
                }
                _ => false,
            })
            .expect("a cylinder side face")
            .id
    }

    fn counts(solid: &BrepSolid) -> (usize, usize, usize) {
        let faces = solid.shells.iter().map(|s| s.faces.len()).sum();
        (solid.vertices.len(), solid.edges.len(), faces)
    }

    // Push the cylinder side of a coaxial cone+cylinder boss OUTWARD: the
    // shared rim must slide DOWN the FIXED cone (from z=4 to z=2, where the cone
    // has radius 4) and the cone neighbour re-intersects + re-trims instead of
    // refusing. Volume, topology counts, and volume sign are all checked.
    #[test]
    fn push_cylinder_side_against_coaxial_cone_reintersects() {
        let axis = Vec3::new(0.0, 0.0, 1.0);
        let solid = coaxial_cone_cylinder_boss();
        assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
        let before_counts = counts(&solid);
        let before_vol = solid_signed_volume(&solid).unwrap();

        let cyl = cylinder_side_id(&solid, axis);
        let pushed = offset_ruled_face(&solid, cyl, 1.0)
            .unwrap_or_else(|e| panic!("push cylinder side against coaxial cone: {e}"));
        assert!(pushed.validate().is_empty(), "validate: {:?}", pushed.validate());

        // Topology preserved (no faces/edges added or lost).
        assert_eq!(counts(&pushed), before_counts, "topology counts changed");

        // Volume: frustum z∈[0,2] (r 5→4) + cylinder r=4 z∈[2,10].
        let expected =
            std::f64::consts::PI * (2.0 / 3.0 * (25.0 + 20.0 + 16.0) + 16.0 * 8.0);
        let got = solid_signed_volume(&pushed).unwrap().abs();
        assert!((got - expected).abs() < 1e-2, "vol {got}, want {expected}");

        // Volume sign preserved (no inversion).
        assert!(
            before_vol * solid_signed_volume(&pushed).unwrap() > 0.0,
            "volume sign flipped"
        );

        // The cylinder grew to r=4, and the shared rim slid to z=2 / r=4.
        let cyl_face = pushed
            .shells
            .iter()
            .flat_map(|s| &s.faces)
            .find(|f| f.id == cyl)
            .unwrap();
        match cyl_face.surface.analytic() {
            Some(AnalyticSurface::RuledRevolution { rho0, rho1, .. }) => {
                assert!((rho0 - 4.0).abs() < 1e-6 && (rho1 - 4.0).abs() < 1e-6, "cyl r {rho0}");
            }
            other => panic!("pushed face must stay ruled, got {other:?}"),
        }
        // The shared rim (a full circle joining cone+cylinder) is now at z=2.
        let shared = pushed
            .edges
            .iter()
            .find(|e| {
                let m = e.curve.evaluate(0.5 * (e.t0 + e.t1)).unwrap();
                (radial(m, Vec3::default(), axis) - 4.0).abs() < 1e-6 && (m.z - 2.0).abs() < 1e-6
            })
            .expect("relocated shared rim at z=2, r=4");
        assert!(shared.start_vertex_id == shared.end_vertex_id, "shared rim is a closed circle");
    }

    // A NON-coaxial ruled neighbour: a vertical pipe crossed by a horizontal
    // one. The pair has no closed form, so the rim is a genuine quartic and the
    // window it cuts is two open arcs — the class the audit's §2.3 puts in the
    // "push-face refuses, offset-shell handles" column. It is the headline
    // conversion of this slice: the shared re-intersection marches the pair and
    // the window is rebuilt from ONE closed section.
    #[test]
    fn push_cylinder_side_against_a_crossing_pipe_matches_the_rebuilt_tee() {
        let vertical =
            make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 3.0, 10.0).unwrap();
        let horizontal =
            make_cylinder_brep(Vec3::new(-6.0, 0.0, 5.0), Vec3::new(1.0, 0.0, 0.0), 1.5, 12.0)
                .unwrap();
        let options = crate::BooleanOptions {
            merge_coplanar_faces: true,
            ..crate::BooleanOptions::default()
        };
        let solid = crate::boolean_operation(
            &vertical,
            &horizontal,
            crate::BooleanOperation::Union,
            &options,
        )
        .unwrap();
        assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
        // The vertical wall (axis z) borders the horizontal wall (axis x).
        let wall = cylinder_side_id(&solid, Vec3::new(0.0, 0.0, 1.0));
        // CONVERTED. This was `push_cylinder_side_against_noncoaxial_ruled_refuses`
        // — "there is no closed-form coaxial re-intersection", which was true and
        // beside the point: the shared re-intersection MARCHES the pair, and the
        // window it cuts is one closed section stored as two arcs whose corners
        // are pinned to the crossing pipe's own seam. The oracle is the same tee
        // built at the pushed radius.
        let pushed = offset_ruled_face(&solid, wall, 1.0)
            .unwrap_or_else(|error| panic!("push a wall against a crossing pipe: {error}"));
        let issues = pushed.validate();
        assert!(issues.is_empty(), "validate: {issues:?}");

        let oracle = {
            let grown =
                make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 4.0, 10.0).unwrap();
            crate::boolean_operation(
                &grown,
                &horizontal,
                crate::BooleanOperation::Union,
                &options,
            )
            .unwrap()
        };
        let got = solid_signed_volume(&pushed).unwrap().abs();
        let want = solid_signed_volume(&oracle).unwrap().abs();
        // Both sides are MARCHED-and-fitted quartic rims — the push's and the
        // boolean's — so this compares two approximations of the same curve, not
        // an approximation against a closed form. Measured 2.6e-6 relative; the
        // bound is well above that and far below any real error.
        assert!(
            (got - want).abs() <= 1e-4 * want,
            "pushed volume {got} against the independently built {want} (relative {:.3e})",
            (got - want).abs() / want
        );
        assert_eq!(
            (
                pushed.shells.iter().map(|s| s.faces.len()).sum::<usize>(),
                pushed.edges.len(),
                pushed.vertices.len()
            ),
            (
                oracle.shells.iter().map(|s| s.faces.len()).sum::<usize>(),
                oracle.edges.len(),
                oracle.vertices.len()
            ),
            "the push must reproduce the rebuilt tee's topology"
        );
        // The wall really is at the new radius, and the crossing pipe kept its
        // own radius — only its trim moved.
        let radii: Vec<f64> = pushed
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter_map(|face| match face.surface.analytic() {
                Some(AnalyticSurface::RuledRevolution { rho0, rho1, .. })
                    if (rho0 - rho1).abs() < 1e-9 =>
                {
                    Some(*rho0)
                }
                _ => None,
            })
            .collect();
        assert!(
            radii.iter().any(|r| (r - 4.0).abs() < 1e-9),
            "the pushed wall must be at radius 4, got {radii:?}"
        );
        assert_eq!(
            radii.iter().filter(|r| (**r - 1.5).abs() < 1e-9).count(),
            2,
            "both stubs of the crossing pipe keep radius 1.5, got {radii:?}"
        );
        // Every rebuilt window arc sits on BOTH carriers — the honest statement
        // of what a marched rim has to satisfy, and the thing a fit can lose.
        let mut window_samples = 0usize;
        for edge in &pushed.edges {
            for step in 0..=8 {
                let point = edge
                    .curve
                    .evaluate(edge.t0 + (edge.t1 - edge.t0) * step as f64 / 8.0)
                    .unwrap();
                let on_wall = ((point.x * point.x + point.y * point.y).sqrt() - 4.0).abs();
                let on_pipe = ((point.y * point.y + (point.z - 5.0) * (point.z - 5.0)).sqrt()
                    - 1.5)
                    .abs();
                if on_wall < 1e-3 && on_pipe < 1e-3 {
                    window_samples += 1;
                    assert!(
                        on_wall < 1e-5 && on_pipe < 1e-5,
                        "a window arc drifts off its carriers: {on_wall:.3e} / {on_pipe:.3e}"
                    );
                }
            }
        }
        assert!(
            window_samples >= 18,
            "the two window arcs must be present and sampled, got {window_samples}"
        );
    }

    /// The SAME pair, with the window straddling the pushed carrier's periodic
    /// seam: the arrangement stitches its arcs into the OUTER loop, so the loop
    /// is no longer a single-neighbour ring and the window cannot be rebuilt as
    /// one section. It must refuse — and the refusal now names the arc, not
    /// coaxiality, because coaxiality stopped being the blocker.
    #[test]
    fn a_window_straddling_the_pushed_seam_still_refuses() {
        let axis = Vec3::new(0.0, 0.0, 1.0);
        let vertical = make_cylinder_brep(Vec3::default(), axis, 3.0, 10.0).unwrap();
        // Along Y, where `make_cylinder_brep` puts the seam.
        let crossing =
            make_cylinder_brep(Vec3::new(0.0, -6.0, 5.0), Vec3::new(0.0, 1.0, 0.0), 1.5, 12.0)
                .unwrap();
        let options = crate::BooleanOptions {
            merge_coplanar_faces: true,
            ..crate::BooleanOptions::default()
        };
        let solid = crate::boolean_operation(
            &vertical,
            &crossing,
            crate::BooleanOperation::Union,
            &options,
        )
        .unwrap();
        assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
        let wall = cylinder_side_id(&solid, axis);
        let error = offset_ruled_face(&solid, wall, 1.0)
            .expect_err("a seam-straddling window must refuse");
        assert!(
            error.contains("OPEN arc") || error.contains("seam"),
            "unexpected refusal: {error}"
        );
        assert!(solid.validate().is_empty(), "the source is never mutated");
    }

    // Pushing the same boss INWARD drives the shared rim OFF the cone's domain
    // (a harder sub-case, deferred): it must refuse cleanly, not tear.
    #[test]
    fn push_cylinder_side_coaxial_inward_refuses_cleanly() {
        let axis = Vec3::new(0.0, 0.0, 1.0);
        let solid = coaxial_cone_cylinder_boss();
        let cyl = cylinder_side_id(&solid, axis);
        // r 3 → 2 puts the cone-crossing at z=6, past the cone patch [0,4].
        let result = offset_ruled_face(&solid, cyl, -1.0);
        match result {
            Err(_) => {}
            Ok(good) => assert!(
                good.validate().is_empty(),
                "if inward is accepted it must still be valid: {:?}",
                good.validate()
            ),
        }
    }

    // ---------------------------------------------------------------------
    // The CURVED-neighbour lane (offset-unification: the generic neighbour
    // re-intersection). Each of these was a blanket refusal — "a boundary
    // neighbour is not planar (sphere/torus/free-form neighbours are deferred
    // in this slice)" — for a pair the kernel's own closed forms already solve
    // exactly. The oracle is not a hand-derived volume but the SAME FEATURE
    // BUILT AT THE PUSHED SIZE: pushing a wall from r to r+d must land on the
    // solid you get by building it at r+d from scratch.
    // ---------------------------------------------------------------------

    /// A rod capped by a ball (a dome on a shaft): the wall's top rim neighbour
    /// is a SPHERE. Pushing the wall out slides the rim UP the dome, and the
    /// dome's own seam meridian re-trims to the new latitude on the curve it
    /// already carries.
    #[test]
    fn push_cylinder_wall_against_a_spherical_dome_matches_the_rebuilt_solid() {
        let ball_capped = |radius: f64| {
            let rod =
                make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), radius, 10.0)
                    .unwrap();
            let ball =
                crate::make_sphere_brep(Vec3::new(0.0, 0.0, 10.0), 4.0, Vec3::new(0.0, 0.0, 1.0))
                    .unwrap();
            crate::boolean_operation(
                &rod,
                &ball,
                crate::BooleanOperation::Union,
                &crate::BooleanOptions {
                    merge_coplanar_faces: true,
                    ..crate::BooleanOptions::default()
                },
            )
            .unwrap()
        };
        let source = ball_capped(3.0);
        let wall = cylinder_side_id(&source, Vec3::new(0.0, 0.0, 1.0));
        let pushed = offset_ruled_face(&source, wall, 0.5)
            .unwrap_or_else(|error| panic!("push a wall against a dome: {error}"));
        let issues = pushed.validate();
        assert!(issues.is_empty(), "validate: {issues:?}");

        let oracle = ball_capped(3.5);
        let got = solid_signed_volume(&pushed).unwrap().abs();
        let want = solid_signed_volume(&oracle).unwrap().abs();
        // Every step of this push is exact — the offset carrier is an exact
        // cylinder, the rim is the closed-form coaxial section, and the dome's
        // seam re-trims by a parameter on its own curve — so the tolerance is
        // rounding, not a fit budget.
        assert!(
            (got - want).abs() <= 1e-9 * want,
            "pushed volume {got} against the independently built {want}"
        );
        assert_eq!(
            (
                pushed.shells.iter().map(|s| s.faces.len()).sum::<usize>(),
                pushed.edges.len(),
                pushed.vertices.len()
            ),
            (
                oracle.shells.iter().map(|s| s.faces.len()).sum::<usize>(),
                oracle.edges.len(),
                oracle.vertices.len()
            ),
            "the push must reproduce the rebuilt solid's topology, not merely its volume"
        );
    }

    /// A shaft with a turned circumferential groove: the wall band's rim
    /// neighbour is a TORUS. The rim rides the tube to a new station and the
    /// torus's u-seam re-trims to it.
    #[test]
    fn push_cylinder_wall_against_a_toroidal_groove_moves_the_rim_onto_the_tube() {
        let axis = Vec3::new(0.0, 0.0, 1.0);
        let shaft = make_cylinder_brep(Vec3::default(), axis, 5.0, 10.0).unwrap();
        let groove = crate::make_torus_brep(Vec3::new(0.0, 0.0, 5.0), axis, 5.0, 1.5).unwrap();
        let grooved = crate::boolean_operation(
            &shaft,
            &groove,
            crate::BooleanOperation::Subtract,
            &crate::BooleanOptions {
                merge_coplanar_faces: true,
                ..crate::BooleanOptions::default()
            },
        )
        .unwrap();
        assert!(grooved.validate().is_empty(), "fixture: {:?}", grooved.validate());
        let before = solid_signed_volume(&grooved).unwrap().abs();
        let band = cylinder_side_id(&grooved, axis);
        let pushed = offset_ruled_face(&grooved, band, 0.5)
            .unwrap_or_else(|error| panic!("push a wall band against a groove: {error}"));
        let issues = pushed.validate();
        assert!(issues.is_empty(), "validate: {issues:?}");

        // The pushed band is the UPPER one (z ∈ [6.5, 10] before the push). Its
        // radius becomes 5.5, so its rim slides DOWN the tube to where the
        // r = 5.5 cylinder meets the torus: (5.5−5)² + (z−5)² = 1.5², i.e.
        // z = 5 + √2. That station is the exact statement of what the
        // re-intersection had to compute, so it is asserted directly rather
        // than through a volume the groove profile makes fiddly.
        let rim_z = 5.0 + 2.0_f64.sqrt();
        let after = solid_signed_volume(&pushed).unwrap().abs();
        assert!(after > before, "an outward push must grow the solid");
        let rim = pushed
            .edges
            .iter()
            .find(|edge| {
                let Ok(mid) = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)) else {
                    return false;
                };
                (mid.z - rim_z).abs() < 1e-9
                    && ((mid.x * mid.x + mid.y * mid.y).sqrt() - 5.5).abs() < 1e-9
            })
            .expect("a rebuilt rim circle of radius 5.5 at z = 5 + √2");
        for step in 0..=8 {
            let point = rim
                .curve
                .evaluate(rim.t0 + (rim.t1 - rim.t0) * step as f64 / 8.0)
                .unwrap();
            assert!(
                ((point.x * point.x + point.y * point.y).sqrt() - 5.5).abs() < 1e-9
                    && (point.z - rim_z).abs() < 1e-9,
                "the rim must be the exact circle, not a fitted approximation: {point:?}"
            );
        }
        // The pushed band really is at the new radius, and the torus kept its
        // own geometry (only its trim moved).
        let radii: Vec<f64> = pushed
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter_map(|face| match face.surface.analytic() {
                Some(AnalyticSurface::RuledRevolution { rho0, rho1, .. })
                    if (rho0 - rho1).abs() < 1e-9 =>
                {
                    Some(*rho0)
                }
                _ => None,
            })
            .collect();
        assert!(
            radii.iter().any(|r| (r - 5.5).abs() < 1e-9)
                && radii.iter().any(|r| (r - 5.0).abs() < 1e-9),
            "expected one band at 5.5 and one still at 5.0, got {radii:?}"
        );
        assert!(
            pushed
                .shells
                .iter()
                .flat_map(|shell| &shell.faces)
                .any(|face| matches!(
                    face.surface.analytic(),
                    Some(AnalyticSurface::Torus { major_radius, minor_radius, .. })
                        if (major_radius - 5.0).abs() < 1e-12
                            && (minor_radius - 1.5).abs() < 1e-12
                )),
            "the groove's torus must be untouched — only its trim moved"
        );
    }

    /// A curved neighbour whose rim the push SEPARATES must refuse, not emit a
    /// solid with a stranded boundary. Pushing the dome's rod INWARD far enough
    /// takes the wall out of the ball entirely.
    #[test]
    fn push_that_pulls_a_wall_out_of_its_curved_neighbour_refuses() {
        let rod =
            make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 3.0, 10.0).unwrap();
        let ball =
            crate::make_sphere_brep(Vec3::new(0.0, 0.0, 10.0), 4.0, Vec3::new(0.0, 0.0, 1.0))
                .unwrap();
        let capped = crate::boolean_operation(
            &rod,
            &ball,
            crate::BooleanOperation::Union,
            &crate::BooleanOptions {
                merge_coplanar_faces: true,
                ..crate::BooleanOptions::default()
            },
        )
        .unwrap();
        let wall = cylinder_side_id(&capped, Vec3::new(0.0, 0.0, 1.0));
        // r 3 → 3.9 keeps a rim; r 3 → 4.5 puts the wall outside the ball, so
        // the two carriers no longer meet at all.
        let error = offset_ruled_face(&capped, wall, 1.5)
            .expect_err("a wall pushed clear of its dome must refuse");
        assert!(
            error.contains("no longer meets") || error.contains("refus"),
            "unexpected refusal: {error}"
        );
        assert!(capped.validate().is_empty(), "the source is never mutated");
    }
}