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
use super::*;
use crate::{chamfer_edge, fillet_edge, make_box_brep, make_cylinder_brep};

fn unit_cube() -> BrepSolid {
    make_box_brep(Vec3::new(0.0, 0.0, 0.0), 1.0, 1.0, 1.0).unwrap()
}

/// The edge whose midpoint is nearest `target`.
fn edge_id_near(solid: &BrepSolid, target: Vec3) -> u64 {
    solid
        .edges
        .iter()
        .min_by(|a, b| {
            let ma = a
                .curve
                .evaluate((a.t0 + a.t1) * 0.5)
                .unwrap()
                .sub(target)
                .length();
            let mb = b
                .curve
                .evaluate((b.t0 + b.t1) * 0.5)
                .unwrap()
                .sub(target)
                .length();
            ma.partial_cmp(&mb).unwrap()
        })
        .unwrap()
        .id
}

#[test]
fn deletes_chamfer_and_recovers_the_sharp_cube() {
    let cube = unit_cube();
    let volume = solid_signed_volume(&cube).unwrap().abs();
    // Sharp edge between the top (z=1) and right (x=1) faces.
    let edge = edge_id_near(&cube, Vec3::new(1.0, 0.5, 1.0));
    let chamfered = chamfer_edge(&cube, edge, 0.2, Some("chamfer")).unwrap();
    assert!(chamfered.validate().is_empty());
    // The chamfer face sits over the bevel centre.
    let chamfer_face = resolve_face_by_point(&chamfered, Vec3::new(0.9, 0.5, 0.9)).unwrap();
    let face_count_before = chamfered.shells[0].faces.len();

    let healed = delete_face_and_heal(&chamfered, chamfer_face).unwrap();
    assert!(
        healed.validate().is_empty(),
        "healed solid must validate: {:?}",
        healed.validate()
    );
    // The chamfer face is gone.
    assert_eq!(healed.shells[0].faces.len(), face_count_before - 1);
    assert!(!healed.shells[0].faces.iter().any(|f| f.id == chamfer_face));
    // Volume returns to the full cube; the sharp edge is recovered.
    let healed_volume = solid_signed_volume(&healed).unwrap().abs();
    assert!(
        (healed_volume - volume).abs() < 1e-6,
        "expected full-cube volume {volume}, got {healed_volume}"
    );
    // A sharp edge sits exactly on the recovered corner line x=1,z=1.
    assert!(healed.edges.iter().any(|edge| {
        let mid = edge.curve.evaluate((edge.t0 + edge.t1) * 0.5).unwrap();
        (mid.x - 1.0).abs() < 1e-6 && (mid.z - 1.0).abs() < 1e-6
    }));
}

#[test]
fn deletes_fillet_and_recovers_the_sharp_cube() {
    let cube = unit_cube();
    let volume = solid_signed_volume(&cube).unwrap().abs();
    let edge = edge_id_near(&cube, Vec3::new(1.0, 0.5, 1.0));
    let filleted = fillet_edge(&cube, edge, 0.2, Some("fillet")).unwrap();
    assert!(filleted.validate().is_empty());
    // The cylindrical fillet face's 45° point sits on the diagonal at the
    // rolling-ball centre (1-r, ·, 1-r) plus r/√2 along (1,0,1).
    let offset = 0.2 / 2.0_f64.sqrt();
    let probe = Vec3::new(0.8 + offset, 0.5, 0.8 + offset);
    let fillet_face = resolve_face_by_point(&filleted, probe).unwrap();
    let face_count_before = filleted.shells[0].faces.len();

    let healed = delete_face_and_heal(&filleted, fillet_face).unwrap();
    assert!(
        healed.validate().is_empty(),
        "healed solid must validate: {:?}",
        healed.validate()
    );
    assert_eq!(healed.shells[0].faces.len(), face_count_before - 1);
    let healed_volume = solid_signed_volume(&healed).unwrap().abs();
    assert!(
        (healed_volume - volume).abs() < 1e-6,
        "expected full-cube volume {volume}, got {healed_volume}"
    );
    assert!(healed.edges.iter().any(|edge| {
        let mid = edge.curve.evaluate((edge.t0 + edge.t1) * 0.5).unwrap();
        (mid.x - 1.0).abs() < 1e-6 && (mid.z - 1.0).abs() < 1e-6
    }));
}

#[test]
fn refuses_to_delete_a_face_whose_neighbours_cannot_reintersect() {
    // Deleting a plain cube face: its four neighbours are two pairs of
    // parallel planes, so nothing re-intersects cleanly.
    let cube = unit_cube();
    let top = resolve_face_by_point(&cube, Vec3::new(0.5, 0.5, 1.0)).unwrap();
    let result = delete_face_and_heal(&cube, top);
    assert!(result.is_err(), "expected a refusal, got a solid");
    let message = result.unwrap_err();
    assert!(
        message.contains("re-intersect") || message.contains("parallel"),
        "unexpected error: {message}"
    );
    // And the original solid is untouched / still valid.
    assert!(cube.validate().is_empty());
}

// --- move_faces --------------------------------------------------------

/// (a) Extrude-equivalent sanity: pushing the +x face of a 1×2×3 box
/// outward by 0.5 along x must grow the volume by exactly
/// 0.5 · (dy · dz) = 0.5 · 6 = 3.
#[test]
fn moving_a_box_face_outward_grows_volume_like_an_extrude() {
    let block = make_box_brep(Vec3::new(0.0, 0.0, 0.0), 1.0, 2.0, 3.0).unwrap();
    let volume = solid_signed_volume(&block).unwrap();
    let plus_x = resolve_face_by_point(&block, Vec3::new(1.0, 1.0, 1.5)).unwrap();

    let moved = move_faces(&block, &[plus_x], Vec3::new(0.5, 0.0, 0.0)).unwrap();
    assert!(
        moved.validate().is_empty(),
        "moved solid must validate: {:?}",
        moved.validate()
    );
    let moved_volume = solid_signed_volume(&moved).unwrap();
    assert!(
        (moved_volume - (volume + 0.5 * 2.0 * 3.0)).abs() < 1e-9,
        "expected {} + 3, got {moved_volume}",
        volume
    );
    // Pure geometry edit: no topology was created or destroyed.
    assert_eq!(moved.vertices.len(), block.vertices.len());
    assert_eq!(moved.edges.len(), block.edges.len());
    assert_eq!(moved.shells[0].faces.len(), block.shells[0].faces.len());
    // The input is untouched.
    assert!(block.validate().is_empty());
    assert!((solid_signed_volume(&block).unwrap() - volume).abs() < 1e-12);
}

/// (b) The same face moved INWARD shrinks the volume by exactly the same
/// prism: 0.25 · (dy · dz) = 1.5.
#[test]
fn moving_a_box_face_inward_shrinks_volume_exactly() {
    let block = make_box_brep(Vec3::new(0.0, 0.0, 0.0), 1.0, 2.0, 3.0).unwrap();
    let volume = solid_signed_volume(&block).unwrap();
    let plus_x = resolve_face_by_point(&block, Vec3::new(1.0, 1.0, 1.5)).unwrap();

    let moved = move_faces(&block, &[plus_x], Vec3::new(-0.25, 0.0, 0.0)).unwrap();
    assert!(moved.validate().is_empty());
    let moved_volume = solid_signed_volume(&moved).unwrap();
    assert!(
        (moved_volume - (volume - 0.25 * 2.0 * 3.0)).abs() < 1e-9,
        "expected {} - 1.5, got {moved_volume}",
        volume
    );
}

/// (c) A two-face group: the +x and +y faces of the unit cube moved
/// together by (0.3, 0.4, 0).
///
/// Hand computation of the expected volume: translating a PLANE only
/// displaces it by the normal component of the translation, so the +x
/// carrier (normal +x) lands on x = 1.3 and the +y carrier (normal +y)
/// lands on y = 1.4. Re-intersecting with the four fixed planes x = 0,
/// y = 0, z = 0, z = 1 leaves the axis-aligned prism
/// [0, 1.3] × [0, 1.4] × [0, 1], i.e.
///     V = 1.3 · 1.4 · 1.0 = 1.82.
/// The cube edge shared by the two moved faces is interior to the group
/// and rides rigidly onto the line x = 1.3, y = 1.4 — exactly where the
/// two translated carriers re-intersect, so the group stays attached.
#[test]
fn moving_a_two_face_group_diagonally_yields_the_analytic_prism() {
    let cube = unit_cube();
    let plus_x = resolve_face_by_point(&cube, Vec3::new(1.0, 0.5, 0.5)).unwrap();
    let plus_y = resolve_face_by_point(&cube, Vec3::new(0.5, 1.0, 0.5)).unwrap();

    let moved = move_faces(&cube, &[plus_x, plus_y], Vec3::new(0.3, 0.4, 0.0)).unwrap();
    assert!(
        moved.validate().is_empty(),
        "moved solid must validate: {:?}",
        moved.validate()
    );
    let moved_volume = solid_signed_volume(&moved).unwrap();
    assert!(
        (moved_volume - 1.82).abs() < 1e-9,
        "expected the analytic prism volume 1.82, got {moved_volume}"
    );
    // The group's interior edge was carried rigidly: its top corner is
    // the full translation of (1, 1, 1).
    assert!(moved
        .vertices
        .iter()
        .any(|vertex| { vertex.point.sub(Vec3::new(1.3, 1.4, 1.0)).length() < 1e-9 }));
    assert_eq!(moved.vertices.len(), 8);
    assert_eq!(moved.edges.len(), 12);
    assert_eq!(moved.shells[0].faces.len(), 6);
}

/// (d) SM1: moving a cylinder's cap along its axis. The moved face is planar
/// but its neighbour is the cylindrical wall — a translation-invariant carrier
/// (the push is ∥ the axis), so the wall re-trims as a ruled carrier and the
/// cap push EXTENDS the cylinder. Volume grows by π·r²·distance; the input is
/// untouched.
#[test]
fn moving_a_cylinder_cap_extends_the_wall() {
    let cylinder =
        make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 1.0, 2.0).unwrap();
    let v0 = solid_signed_volume(&cylinder).unwrap();
    let cap = resolve_face_by_point(&cylinder, Vec3::new(0.0, 0.0, 2.0)).unwrap();

    let moved = move_faces(&cylinder, &[cap], Vec3::new(0.0, 0.0, 0.5))
        .expect("cap push along the axis extends the wall");
    assert!(
        moved.validate().is_empty(),
        "moved solid must validate: {:?}",
        moved.validate()
    );
    let delta = solid_signed_volume(&moved).unwrap() - v0;
    let expected = std::f64::consts::PI * 0.5; // π·r²·d, r=1, d=0.5
    assert!(
        (delta - expected).abs() < 1e-3,
        "cap push volume delta {delta}, expected {expected}"
    );
    // Pure geometry edit: topology is untouched.
    assert_eq!(moved.shells[0].faces.len(), cylinder.shells[0].faces.len());
    assert!(cylinder.validate().is_empty());
}

/// (e) Unknown ids, an empty group, and translations that collapse or
/// invert the box past its opposite face are refused without panicking
/// and without corrupting the input.
#[test]
fn unknown_ids_and_collapsing_translations_are_refused_without_panic() {
    let cube = unit_cube();
    let step = Vec3::new(0.1, 0.0, 0.0);

    let unknown = move_faces(&cube, &[424_242], step).unwrap_err();
    assert!(unknown.contains("no face with id"), "got: {unknown}");

    let empty = move_faces(&cube, &[], step).unwrap_err();
    assert!(empty.contains("no faces selected"), "got: {empty}");

    let plus_x = resolve_face_by_point(&cube, Vec3::new(1.0, 0.5, 0.5)).unwrap();
    // Landing exactly on the opposite face collapses the side edges.
    let collapse = move_faces(&cube, &[plus_x], Vec3::new(-1.0, 0.0, 0.0)).unwrap_err();
    assert!(collapse.contains("collapses"), "got: {collapse}");
    // Passing beyond the opposite face reverses the side edges.
    let invert = move_faces(&cube, &[plus_x], Vec3::new(-1.5, 0.0, 0.0)).unwrap_err();
    assert!(invert.contains("inverts"), "got: {invert}");

    // The refusal path never mutates the input.
    assert!(cube.validate().is_empty());
    assert!((solid_signed_volume(&cube).unwrap() - 1.0).abs() < 1e-12);
}

// ---------------------------------------------------------------------------
// synchronous-modeling.md §5: the arbitrary-face / internal-loop boundary,
// pinned with evidence. These four cases document the CURRENT `move_faces`
// reach; the SM1/SM3 markers below flip to Ok as those slices land.
// ---------------------------------------------------------------------------
fn subtract_solid(body: BrepSolid, cutter: BrepSolid) -> Result<BrepSolid, String> {
    let options = crate::BooleanOptions {
        merge_coplanar_faces: true,
        ..crate::BooleanOptions::default()
    };
    crate::boolean_operation(&body, &cutter, crate::BooleanOperation::Subtract, &options)
}

fn plate_20x20x4() -> BrepSolid {
    make_box_brep(Vec3::new(0.0, 0.0, 0.0), 20.0, 20.0, 4.0).unwrap()
}

fn max_loops(solid: &BrepSolid) -> usize {
    solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .map(|face| face.loops.len())
        .max()
        .unwrap_or(0)
}

// SM0: a PLANAR face with an internal loop (rectangular through-pocket) pushes
// exactly like a single-loop one — the plane translates, every wall extends,
// the hole survives, volume grows by the pushed area · distance.
#[test]
fn move_faces_pushes_planar_multiloop_top() {
    let rect_cutter = make_box_brep(Vec3::new(7.0, 7.0, -1.0), 6.0, 6.0, 6.0).unwrap();
    let holed = subtract_solid(plate_20x20x4(), rect_cutter).expect("rect through-hole");
    assert_eq!(max_loops(&holed), 2, "top/bottom carry the pocket as a 2nd loop");
    let top = resolve_face_by_point(&holed, Vec3::new(2.0, 2.0, 4.0)).expect("top face");

    let pushed = move_faces(&holed, &[top], Vec3::new(0.0, 0.0, 3.0)).expect("planar multi-loop");
    // Plate 1600 − pocket 144 = 1456; push the 400−36 = 364 top area up 3 → +1092.
    assert!(
        (solid_signed_volume(&pushed).unwrap() - 2548.0).abs() < 1e-6,
        "volume {}",
        solid_signed_volume(&pushed).unwrap()
    );
    assert_eq!(max_loops(&pushed), 2, "the pocket loop survives the push");
    assert!(pushed.validate().is_empty());
}

// SM1: push the flat top of a plate with a DRILLED (cylindrical) hole. The
// fixed cap wall is a cylinder ∥ the push axis, so it re-trims as a ruled
// carrier. Volume grows/shrinks by (plate area − hole area)·distance. The
// curved-face integrator is only ~1e-5 absolute, so compare the volume DELTA
// against the analytic slab at 1e-3, not ideal volumes at 1e-6.
#[test]
fn move_faces_pushes_drilled_hole_cap_up_and_down() {
    let hole_area = std::f64::consts::PI * 9.0;
    let base_area = 400.0 - hole_area;
    for distance in [3.0_f64, -1.5] {
        let cyl_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 drilled = subtract_solid(plate_20x20x4(), cyl_cutter).expect("drilled hole");
        let v_before = solid_signed_volume(&drilled).unwrap();
        let top = resolve_face_by_point(&drilled, Vec3::new(2.0, 2.0, 4.0)).expect("top face");

        let pushed = move_faces(&drilled, &[top], Vec3::new(0.0, 0.0, distance))
            .unwrap_or_else(|e| panic!("push cap by {distance}: {e}"));
        assert!(pushed.validate().is_empty(), "validate after push {distance}");
        let delta = solid_signed_volume(&pushed).unwrap() - v_before;
        assert!(
            (delta - base_area * distance).abs() < 1e-3,
            "push {distance}: volume delta {delta}, expected {}",
            base_area * distance
        );
        // The hole (inner loop on top + bottom) survives the push.
        assert!(max_loops(&pushed) >= 2, "the hole loop survives");
    }
}

// SM1b: a SOLID frustum (cone-shaped object). Push the top flat cap along the
// axis: the lateral cone keeps the SAME analytic surface, only its trim (and the
// cap's radius) change. Volume matches the frustum formula V = πh/3(R²+Rr+r²),
// up (toward the apex, radius shrinks) and down (away, radius grows).
#[test]
fn move_faces_pushes_frustum_top_cap() {
    let big_r = 3.0_f64; // bottom radius at z=0
    let top_r0 = 1.5_f64; // top radius at z=4
    let h0 = 4.0_f64;
    let frustum_vol = |r_top: f64, h: f64| {
        std::f64::consts::PI * h / 3.0 * (big_r * big_r + big_r * r_top + r_top * r_top)
    };
    for d in [1.0_f64, -1.5] {
        let frustum =
            crate::make_cone_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), big_r, top_r0, h0)
                .unwrap();
        let cap = resolve_face_by_point(&frustum, Vec3::new(0.0, 0.0, h0)).expect("top cap");
        let pushed = move_faces(&frustum, &[cap], Vec3::new(0.0, 0.0, d))
            .unwrap_or_else(|e| panic!("push frustum cap by {d}: {e}"));
        assert!(
            pushed.validate().is_empty(),
            "validate after push {d}: {:?}",
            pushed.validate()
        );
        // New top radius at z = h0+d (linear along the same cone).
        let r_top_new = big_r + (top_r0 - big_r) * (h0 + d) / h0;
        let expected = frustum_vol(r_top_new, h0 + d);
        let got = solid_signed_volume(&pushed).unwrap().abs();
        assert!(
            (got - expected).abs() < 1e-3,
            "push {d}: volume {got}, expected {expected}"
        );
    }
}

// SM1b: pushing the BOTTOM cap of a frustum outward (−z) extends the cone
// downward — the negative-axial extension direction. Bottom radius grows.
#[test]
fn move_faces_pushes_frustum_bottom_cap() {
    let big_r = 3.0_f64; // bottom radius at z=0
    let top_r = 1.5_f64; // top radius at z=4
    let h0 = 4.0_f64;
    let frustum =
        crate::make_cone_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), big_r, top_r, h0).unwrap();
    let bottom = resolve_face_by_point(&frustum, Vec3::new(0.0, 0.0, 0.0)).expect("bottom cap");
    let d = 1.0_f64; // push down by 1 (the bottom cap's outward normal is −z)
    let pushed = move_faces(&frustum, &[bottom], Vec3::new(0.0, 0.0, -d))
        .unwrap_or_else(|e| panic!("push frustum bottom cap: {e}"));
    assert!(pushed.validate().is_empty(), "validate: {:?}", pushed.validate());
    let r_bottom_new = big_r + (top_r - big_r) * (-d) / h0;
    let new_h = h0 + d;
    let expected = std::f64::consts::PI * new_h / 3.0
        * (r_bottom_new * r_bottom_new + r_bottom_new * top_r + top_r * top_r);
    let got = solid_signed_volume(&pushed).unwrap().abs();
    assert!(
        (got - expected).abs() < 1e-3,
        "bottom-cap push volume {got}, expected {expected}"
    );
}

// SM1b fail-safe pin: pushing a frustum's top cap TOWARD the apex until the
// re-intersected radius reaches/passes zero must refuse, not emit a degenerate
// solid. Apex at z=8 (R=3 at 0, r=1.5 at 4 → 0 at 8); push up 4.5 → past it.
#[test]
fn move_faces_frustum_apex_push_refuses() {
    let frustum =
        crate::make_cone_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 3.0, 1.5, 4.0).unwrap();
    let cap = resolve_face_by_point(&frustum, Vec3::new(0.0, 0.0, 4.0)).expect("top cap");
    let err = move_faces(&frustum, &[cap], Vec3::new(0.0, 0.0, 4.5))
        .expect_err("a cap push past the apex must refuse");
    assert!(err.contains("apex"), "unexpected refusal: {err}");
}

// SM1b (was an SM1 refusal marker): a countersink — plate top pushed over a
// CONICAL hole — now heals by the same rule (the cone hole wall re-trims).
#[test]
fn move_faces_pushes_conical_hole_cap() {
    let cone = crate::make_cone_brep(
        Vec3::new(10.0, 10.0, -1.0),
        Vec3::new(0.0, 0.0, 1.0),
        2.0,
        4.0,
        6.0,
    )
    .expect("frustum cutter");
    let drilled = subtract_solid(plate_20x20x4(), cone).expect("conical hole");
    let v0 = solid_signed_volume(&drilled).unwrap();
    let top = resolve_face_by_point(&drilled, Vec3::new(2.0, 2.0, 4.0)).expect("top face");

    let pushed = move_faces(&drilled, &[top], Vec3::new(0.0, 0.0, 3.0))
        .expect("countersink cap push now heals");
    assert!(pushed.validate().is_empty(), "validate: {:?}", pushed.validate());
    assert!(
        solid_signed_volume(&pushed).unwrap() > v0,
        "pushing the top out grows the plate volume"
    );
    assert!(max_loops(&pushed) >= 2, "the conical hole loop survives");
}

// Finding (c): the SM1b rim map relies on `transform_curve` mapping a rational
// circle by a radial scale EXACTLY onto the analytic circle. Pin it directly.
#[test]
fn transform_curve_scales_a_rational_circle_exactly() {
    let cyl = make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 5.0, 2.0).unwrap();
    let rim = cyl
        .edges
        .iter()
        .find(|e| e.curve.degree == 2)
        .expect("a rational-quadratic circle rim")
        .clone();
    // Radial scale ×2 about the z-axis: x,y ×2, z unchanged.
    let scale2 = AffineTransform::new([
        2.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0,
    ])
    .unwrap();
    let scaled = transform_curve(&rim.curve, scale2).unwrap();
    for step in 0..=16 {
        let t = rim.t0 + (rim.t1 - rim.t0) * (step as f64 / 16.0);
        let p = scaled.evaluate(t).unwrap();
        let r = (p.x * p.x + p.y * p.y).sqrt();
        assert!((r - 10.0).abs() < 1e-9, "scaled radius {r}, expected 10");
    }
}

// MF evidence: `move_faces` already TRANSLATES a curved moved carrier (a whole
// cylinder side) and a holed carrier (relocate a drilled hole) rigidly — the
// surface keeps its shape, volume is unchanged. This is the Move Face op the
// SM2 feature wraps; note it is TRANSLATE, not PUSH (push would change radius).
#[test]
fn move_faces_translates_curved_and_holed_carriers() {
    // A rigid translation preserves volume exactly. Compare against the PRE-move
    // volume, not an ideal formula — the B-rep volume integral over a curved face
    // carries a small discretization error that cancels between before/after.
    let cyl = make_cylinder_brep(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 5.0, 10.0)
        .unwrap();
    let v_cyl = solid_signed_volume(&cyl).unwrap();
    let side = resolve_face_by_point(&cyl, Vec3::new(5.0, 0.0, 5.0)).expect("side");
    let moved = move_faces(&cyl, &[side], Vec3::new(1.0, 0.0, 0.0)).expect("translate cylinder");
    assert!(
        (solid_signed_volume(&moved).unwrap() - v_cyl).abs() < 1e-6,
        "translating a cylinder side preserves volume"
    );

    let cyl_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 drilled = subtract_solid(plate_20x20x4(), cyl_cutter).expect("drilled hole");
    let v_drilled = solid_signed_volume(&drilled).unwrap();
    let wall = resolve_face_by_point(&drilled, Vec3::new(13.0, 10.0, 2.0)).expect("hole wall");
    let relocated = move_faces(&drilled, &[wall], Vec3::new(2.0, 0.0, 0.0)).expect("move hole");
    assert!(
        (solid_signed_volume(&relocated).unwrap() - v_drilled).abs() < 1e-6,
        "relocating a drilled hole preserves volume"
    );
    assert!(relocated.validate().is_empty());
}

// --- SM1c oblique multi-rim caps (backlog #2) --------------------------------
// Small affine helpers to build a tilted oblique-cut cutter box.
fn rot_y(angle: f64) -> AffineTransform {
    let (s, c) = angle.sin_cos();
    AffineTransform::new([
        c, 0.0, s, 0.0, //
        0.0, 1.0, 0.0, 0.0, //
        -s, 0.0, c, 0.0, //
        0.0, 0.0, 0.0, 1.0,
    ])
    .unwrap()
}

fn translate_af(t: Vec3) -> AffineTransform {
    AffineTransform::new([
        1.0, 0.0, 0.0, t.x, //
        0.0, 1.0, 0.0, t.y, //
        0.0, 0.0, 1.0, t.z, //
        0.0, 0.0, 0.0, 1.0,
    ])
    .unwrap()
}

fn compose(a: AffineTransform, b: AffineTransform) -> AffineTransform {
    // a ∘ b
    let m = a.elements;
    let n = b.elements;
    let mut r = [0.0f64; 16];
    for i in 0..4 {
        for j in 0..4 {
            for k in 0..4 {
                r[i * 4 + j] += m[i * 4 + k] * n[k * 4 + j];
            }
        }
    }
    AffineTransform::new(r).unwrap()
}

/// A cylinder (`r`, axis `+z`, `height`) with two axis-parallel flats at
/// `x = ±flat`, capped OBLIQUELY by a plane tilted `alpha` about `+y` and
/// pivoted at `pivot_z`. The oblique cap is bounded by several conic rims (arc
/// bands of the flatted wall) + two straight flat edges meeting at seam corners
/// whose FIXED edges are cylinder generatrices.
fn flatted_oblique_capped(
    make_wall: impl Fn() -> BrepSolid,
    flat: f64,
    alpha: f64,
    pivot_z: f64,
) -> (BrepSolid, u64) {
    let slab_px = make_box_brep(Vec3::new(flat, -10.0, -1.0), 10.0, 20.0, 40.0).unwrap();
    let slab_nx = make_box_brep(Vec3::new(-flat - 10.0, -10.0, -1.0), 10.0, 20.0, 40.0).unwrap();
    let flatted = subtract_solid(subtract_solid(make_wall(), slab_px).unwrap(), slab_nx).unwrap();
    let raw = make_box_brep(Vec3::new(-15.0, -15.0, 0.0), 30.0, 30.0, 25.0).unwrap();
    let xf = compose(translate_af(Vec3::new(0.0, 0.0, pivot_z)), rot_y(alpha));
    let cutter = crate::transform_brep(&raw, xf, false).unwrap();
    let solid = subtract_solid(flatted, cutter).unwrap();
    let cap = resolve_face_by_point(&solid, Vec3::new(0.0, 0.0, pivot_z)).expect("oblique cap");
    (solid, cap)
}

/// The same oblique cutter as `flatted_oblique_capped`, but with NO flats: a
/// SINGLE closed conic rim against ONE ruled wall (the oblique single-rim cap).
fn oblique_capped(make_wall: impl Fn() -> BrepSolid, alpha: f64, pivot_z: f64) -> (BrepSolid, u64) {
    let raw = make_box_brep(Vec3::new(-15.0, -15.0, 0.0), 30.0, 30.0, 25.0).unwrap();
    let xf = compose(translate_af(Vec3::new(0.0, 0.0, pivot_z)), rot_y(alpha));
    let cutter = crate::transform_brep(&raw, xf, false).unwrap();
    let solid = subtract_solid(make_wall(), cutter).unwrap();
    let cap = resolve_face_by_point(&solid, Vec3::new(0.0, 0.0, pivot_z)).expect("oblique cap");
    (solid, cap)
}

/// Exact volume of `frustum(rho(z) = r0 + (r1-r0)*z/h)` clipped by the two flats
/// `|x| <= flat` and by the oblique cap plane pushed a distance `d` along its own
/// normal `(sin a, 0, cos a)` through `(0, 0, pivot)`.
///
/// The y-extent at `(x, z)` is `2*sqrt(rho(z)^2 - x^2)`, and the z-integral is
/// closed form under `u = rho(z)` (`F(u) = u/2*sqrt(u^2-x^2) - x^2/2*ln(u+sqrt(u^2-x^2))`,
/// `F' = sqrt(u^2-x^2)`), leaving ONE smooth 1-D Simpson integral in `x`. This is
/// an independent oracle: it never touches the kernel's own geometry.
fn flatted_frustum_volume(
    r0: f64,
    r1: f64,
    height: f64,
    flat: f64,
    alpha: f64,
    pivot: f64,
    d: f64,
) -> f64 {
    let slope = (r1 - r0) / height; // drho/dz, negative for a shrinking frustum
    assert!(slope < 0.0, "oracle assumes a shrinking frustum");
    let antiderivative = |u: f64, a: f64| -> f64 {
        let root = (u * u - a * a).max(0.0).sqrt();
        0.5 * u * root - 0.5 * a * a * (u + root).ln()
    };
    const N: usize = 4000;
    let mut total = 0.0;
    for step in 0..=N {
        let x = -flat + 2.0 * flat * (step as f64 / N as f64);
        let z_cap =
            (pivot + d / alpha.cos() - x * alpha.tan()).clamp(0.0, height);
        let a = x.abs();
        let u_low = (r0 + slope * z_cap).max(a); // rho at the cap
        let u_high = r0.max(a); // rho at z = 0
        let inner =
            (2.0 / slope.abs()) * (antiderivative(u_high, a) - antiderivative(u_low, a));
        let weight = if step == 0 || step == N {
            1.0
        } else if step % 2 == 1 {
            4.0
        } else {
            2.0
        };
        total += weight * inner;
    }
    total * (2.0 * flat / N as f64) / 3.0
}

fn ruled_neighbour_count(solid: &BrepSolid, face_id: u64) -> usize {
    let mut foe: std::collections::HashMap<u64, Vec<u64>> = Default::default();
    for f in &solid.shells[0].faces {
        for lp in &f.loops {
            for ce in &lp.coedges {
                foe.entry(ce.edge_id).or_default().push(f.id);
            }
        }
    }
    let face = solid.shells[0].faces.iter().find(|f| f.id == face_id).unwrap();
    let mut ruled: std::collections::HashSet<u64> = Default::default();
    for lp in &face.loops {
        for ce in &lp.coedges {
            for &o in foe.get(&ce.edge_id).into_iter().flatten() {
                if o == face_id {
                    continue;
                }
                let nf = solid.shells[0].faces.iter().find(|f| f.id == o).unwrap();
                if matches!(
                    nf.surface.analytic(),
                    Some(AnalyticSurface::RuledRevolution { .. })
                        | Some(AnalyticSurface::Revolution { .. })
                ) {
                    ruled.insert(o);
                }
            }
        }
    }
    ruled.len()
}

/// SM1c multi-rim (backlog #2): an OBLIQUE planar cap bounded by MULTIPLE conic
/// rims + seam corners, pushed along its own (non-axis-parallel) normal. Each
/// corner is re-solved as `translated cap plane ∩ fixed generatrix`, the split
/// cylinder bands extend + re-trim, and the whole thing stays a valid solid.
/// The solid is a uniform prism along `+z`, so pushing the cap by `d` slides
/// every boundary point axially by `h = d/cos α`, growing the volume by exactly
/// `A_xsec · h` with `A_xsec` the double-flatted cross-section area.
#[test]
fn pushing_an_oblique_multi_rim_cap_on_a_flatted_cylinder() {
    let alpha = 30.0_f64.to_radians();
    let (r, flat) = (3.0_f64, 2.0_f64);
    let (solid, cap) = flatted_oblique_capped(
        || make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), r, 10.0).unwrap(),
        flat,
        alpha,
        8.0,
    );
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    // Fixture guard: the cap really is a MULTI-rim oblique cap — it borders
    // several ruled (cylinder) bands and has several conic (deg-2) rim edges.
    assert!(
        ruled_neighbour_count(&solid, cap) >= 2,
        "cap must border multiple ruled bands"
    );
    let conic_rims = solid.shells[0]
        .faces
        .iter()
        .find(|f| f.id == cap)
        .unwrap()
        .loops
        .iter()
        .flat_map(|lp| &lp.coedges)
        .filter(|ce| {
            solid
                .edges
                .iter()
                .find(|e| e.id == ce.edge_id)
                .map(|e| e.curve.degree == 2)
                .unwrap_or(false)
        })
        .count();
    assert!(conic_rims >= 2, "cap must have multiple conic rims, got {conic_rims}");

    // Double-flatted cross-section area: full disk − two circular segments.
    let seg = r * r * (flat / r).acos() - flat * (r * r - flat * flat).sqrt();
    let a_xsec = std::f64::consts::PI * r * r - 2.0 * seg;
    let n = Vec3::new(alpha.sin(), 0.0, alpha.cos());
    let v0 = solid_signed_volume(&solid).unwrap();

    // OUT (bands grow along the axis) and IN (bands shrink).
    for d in [0.6_f64, -0.6] {
        let pushed = move_faces(&solid, &[cap], n.scale(d))
            .unwrap_or_else(|e| panic!("oblique multi-rim push d={d}: {e}"));
        assert!(
            pushed.validate().is_empty(),
            "pushed solid must validate (d={d}): {:?}",
            pushed.validate()
        );
        let h = d / alpha.cos();
        let expected = v0 + a_xsec * h;
        let got = solid_signed_volume(&pushed).unwrap();
        assert!(
            (got - expected).abs() < 1e-2,
            "d={d}: volume {got}, expected {expected} (prism slab A·h)"
        );
        // Pure geometry edit: topology untouched, signed volume keeps its sign.
        assert_eq!(pushed.vertices.len(), solid.vertices.len());
        assert_eq!(pushed.edges.len(), solid.edges.len());
        assert_eq!(pushed.shells[0].faces.len(), solid.shells[0].faces.len());
        assert!(v0 * got > 0.0, "signed volume must keep its sign (d={d})");
    }
    // The input is untouched by either push.
    assert!(solid.validate().is_empty());
    assert!((solid_signed_volume(&solid).unwrap() - v0).abs() < 1e-12);
}

/// SM1c multi-rim on a CONE (backlog #2's remainder after `f2dd6d0f0`): the SAME
/// double-flatted oblique-cap construction on a FRUSTUM. Two things differ from
/// the cylinder and are what used to force a refusal:
///
/// * the FIXED edges at the corners are HYPERBOLAS (cone ∩ axis-parallel flat),
///   which the straight-chord rebuild could not re-lay without leaving the cone,
///   and
/// * the conic rim is carried by a HOMOTHETY about the apex, which maps the whole
///   conic exactly (carrier → itself, cap plane → translated cap plane) but slides
///   the arc's ENDPOINT off the fixed flat.
///
/// The heal now takes the corner from `translated cap plane ∩ fixed edge` as
/// truth, keeps the exact mapped rim CURVE and RE-TRIMS it to that corner, and
/// re-trims the untouched hyperbola in place. Volume is checked against an
/// independent quadrature oracle (`flatted_frustum_volume`), both directions,
/// plus a push/counter-push round trip.
#[test]
fn pushing_an_oblique_multi_rim_cap_on_a_cone_frustum() {
    let alpha = 22.0_f64.to_radians();
    let (flat, r0, r1, height, pivot) = (2.0_f64, 4.0_f64, 2.0_f64, 10.0_f64, 8.0_f64);
    let (solid, cap) = flatted_oblique_capped(
        || crate::make_cone_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), r0, r1, height).unwrap(),
        flat,
        alpha,
        pivot,
    );
    assert!(solid.validate().is_empty(), "cone fixture: {:?}", solid.validate());
    // Fixture guards: a genuine MULTI-rim oblique cap (several ruled bands, several
    // conic rims) whose fixed corner edges are CURVED (the hyperbolas).
    assert!(
        ruled_neighbour_count(&solid, cap) >= 2,
        "cone cap must border multiple ruled bands"
    );
    let cap_face = solid.shells[0].faces.iter().find(|f| f.id == cap).unwrap();
    let conic_rims = cap_face
        .loops
        .iter()
        .flat_map(|lp| &lp.coedges)
        .filter(|ce| {
            solid
                .edges
                .iter()
                .find(|e| e.id == ce.edge_id)
                .map(|e| e.curve.degree == 2)
                .unwrap_or(false)
        })
        .count();
    assert!(conic_rims >= 2, "cone cap must have multiple conic rims, got {conic_rims}");
    let curved_fixed = solid
        .edges
        .iter()
        .filter(|e| e.curve.degree >= 2 && e.curve.evaluate(e.t0).unwrap().z.abs() < 1e-9)
        .count();
    assert!(curved_fixed >= 2, "the flats must meet the cone on CURVED (hyperbolic) fixed edges");

    let v0 = solid_signed_volume(&solid).unwrap();
    let oracle0 = flatted_frustum_volume(r0, r1, height, flat, alpha, pivot, 0.0);
    assert!(
        (v0.abs() - oracle0).abs() < 1e-3,
        "fixture volume {} vs oracle {oracle0}",
        v0.abs()
    );

    let n = Vec3::new(alpha.sin(), 0.0, alpha.cos());
    let mut volumes = Vec::new();
    // OUT (the bands and the hyperbolas grow) and IN (they shrink).
    for d in [0.5_f64, -0.5] {
        let pushed = move_faces(&solid, &[cap], n.scale(d))
            .unwrap_or_else(|e| panic!("oblique multi-rim cone push d={d}: {e}"));
        assert!(
            pushed.validate().is_empty(),
            "pushed cone solid must validate (d={d}): {:?}",
            pushed.validate()
        );
        let got = solid_signed_volume(&pushed).unwrap();
        let expected = flatted_frustum_volume(r0, r1, height, flat, alpha, pivot, d);
        assert!(
            (got.abs() - expected).abs() < 2e-3,
            "d={d}: volume {}, expected {expected} (quadrature oracle)",
            got.abs()
        );
        // Pure geometry edit: topology untouched, signed volume keeps its sign.
        assert_eq!(pushed.vertices.len(), solid.vertices.len());
        assert_eq!(pushed.edges.len(), solid.edges.len());
        assert_eq!(pushed.shells[0].faces.len(), solid.shells[0].faces.len());
        assert!(v0 * got > 0.0, "signed volume must keep its sign (d={d})");
        // Direct geometry check, independent of any volume quadrature: EVERY
        // curved edge of this solid lives on the cone (bottom-circle arcs, the
        // flat×cone hyperbolas, and the cap's conic rims alike), and every edge
        // bounding the cap lies on the TRANSLATED cap plane. Both hold to machine
        // precision only if the rebuilt sections really are the exact conics.
        let cap_c = n.dot(Vec3::new(0.0, 0.0, pivot)) + d;
        for edge in &pushed.edges {
            if edge.curve.degree < 2 {
                continue;
            }
            for step in 0..=8 {
                let t = edge.t0 + (edge.t1 - edge.t0) * (step as f64 / 8.0);
                let p = edge.curve.evaluate(t).unwrap();
                let radial = (p.x * p.x + p.y * p.y).sqrt();
                let off = (radial - (r0 + (r1 - r0) * p.z / height)).abs();
                assert!(off < 1e-9, "d={d}: curved edge {} is {off:.3e} off the cone", edge.id);
            }
        }
        let pushed_cap = pushed.shells[0].faces.iter().find(|f| f.id == cap).unwrap();
        for coedge in pushed_cap.loops.iter().flat_map(|lp| &lp.coedges) {
            let edge = pushed.edges.iter().find(|e| e.id == coedge.edge_id).unwrap();
            for step in 0..=8 {
                let t = edge.t0 + (edge.t1 - edge.t0) * (step as f64 / 8.0);
                let off = (n.dot(edge.curve.evaluate(t).unwrap()) - cap_c).abs();
                assert!(off < 1e-9, "d={d}: cap edge {} is {off:.3e} off the pushed plane", edge.id);
            }
        }
        volumes.push(got.abs());
    }
    assert!(
        volumes[0] > v0.abs() && v0.abs() > volumes[1],
        "pushing out must grow and pushing in must shrink: {volumes:?} around {}",
        v0.abs()
    );

    // Round trip: push out, then push the SAME cap back by the same amount. The
    // second push starts from re-trimmed hyperbolas, so it exercises the new
    // trims as INPUT as well as output.
    let out = move_faces(&solid, &[cap], n.scale(0.5)).unwrap();
    let back = move_faces(&out, &[cap], n.scale(-0.5)).expect("counter-push heals");
    assert!(back.validate().is_empty(), "round trip validates: {:?}", back.validate());
    assert!(
        (solid_signed_volume(&back).unwrap().abs() - v0.abs()).abs() < 1e-2,
        "round trip returns to the original volume"
    );

    // The input is untouched by any of the pushes.
    assert!(solid.validate().is_empty());
    assert!((solid_signed_volume(&solid).unwrap() - v0).abs() < 1e-12);
}

/// Fail-safe negative, the CONE analogue of `oblique_multi_rim_cap_tearing_push_refuses`:
/// an oblique multi-rim cap on a frustum pushed so far INWARD that the cap plane no
/// longer crosses the fixed hyperbolas at all must refuse, not emit a degenerate
/// solid. The multi-rim cone case being supported must not weaken this.
#[test]
fn oblique_multi_rim_cone_cap_tearing_push_refuses() {
    let alpha = 22.0_f64.to_radians();
    let (solid, cap) = flatted_oblique_capped(
        || crate::make_cone_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 4.0, 2.0, 10.0).unwrap(),
        2.0,
        alpha,
        8.0,
    );
    assert!(solid.validate().is_empty(), "cone fixture: {:?}", solid.validate());
    let n = Vec3::new(alpha.sin(), 0.0, alpha.cos());
    // The cap sits around z in [7.2, 8.8]; a push of -9 (axial slide -9/cos22 ~
    // -9.7) drives every corner below the frustum's base plane z=0.
    let err = move_faces(&solid, &[cap], n.scale(-9.0))
        .expect_err("a cone cap pushed through the base must refuse");
    assert!(
        err.contains("collapse")
            || err.contains("invert")
            || err.contains("tear")
            || err.contains("refusing")
            || err.contains("validation"),
        "unexpected refusal: {err}"
    );
    assert!(solid.validate().is_empty());
}

/// SM1c single-rim on a CYLINDER — the case the support matrix flagged as
/// "code-reachable but untested". An oblique cap on a plain cylinder has ONE
/// CLOSED elliptical rim (start vertex == end vertex, no corners), so the seam
/// vertex rides `rim_ruled_map`'s cylinder branch (a pure axis translation
/// `t = (n·T)/(n·axis)`) and the rim maps by that same affine. A plane crossing
/// the axis at `z_c` caps exactly `pi*r^2*z_c` of the cylinder, so a push of `d`
/// along the cap normal changes the volume by exactly `pi*r^2*d/cos(alpha)`.
#[test]
fn pushing_an_oblique_single_rim_cap_on_a_cylinder() {
    let alpha = 25.0_f64.to_radians();
    let (r, pivot) = (3.0_f64, 7.0_f64);
    let (solid, cap) = oblique_capped(
        || make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), r, 10.0).unwrap(),
        alpha,
        pivot,
    );
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    // Fixture guard: exactly ONE ruled neighbour and ONE closed conic rim.
    assert_eq!(
        ruled_neighbour_count(&solid, cap),
        1,
        "the single-rim cap must border exactly one ruled wall"
    );
    let closed_conic_rims = solid.shells[0]
        .faces
        .iter()
        .find(|f| f.id == cap)
        .unwrap()
        .loops
        .iter()
        .flat_map(|lp| &lp.coedges)
        .filter(|ce| {
            solid
                .edges
                .iter()
                .find(|e| e.id == ce.edge_id)
                .map(|e| e.curve.degree == 2 && e.start_vertex_id == e.end_vertex_id)
                .unwrap_or(false)
        })
        .count();
    assert_eq!(closed_conic_rims, 1, "the cap's rim must be a single CLOSED conic");

    let n = Vec3::new(alpha.sin(), 0.0, alpha.cos());
    let v0 = solid_signed_volume(&solid).unwrap();
    let expected0 = std::f64::consts::PI * r * r * pivot;
    assert!(
        (v0.abs() - expected0).abs() < 1e-3,
        "fixture volume {} vs pi*r^2*z_c {expected0}",
        v0.abs()
    );
    for d in [0.6_f64, -0.6] {
        let pushed = move_faces(&solid, &[cap], n.scale(d))
            .unwrap_or_else(|e| panic!("oblique single-rim push d={d}: {e}"));
        assert!(
            pushed.validate().is_empty(),
            "pushed solid must validate (d={d}): {:?}",
            pushed.validate()
        );
        let expected = std::f64::consts::PI * r * r * (pivot + d / alpha.cos());
        let got = solid_signed_volume(&pushed).unwrap();
        assert!(
            (got.abs() - expected).abs() < 1e-3,
            "d={d}: volume {}, expected {expected}",
            got.abs()
        );
        assert_eq!(pushed.vertices.len(), solid.vertices.len());
        assert_eq!(pushed.edges.len(), solid.edges.len());
        assert_eq!(pushed.shells[0].faces.len(), solid.shells[0].faces.len());
        assert!(v0 * got > 0.0, "signed volume must keep its sign (d={d})");
    }
    // The input is untouched.
    assert!(solid.validate().is_empty());
    assert!((solid_signed_volume(&solid).unwrap() - v0).abs() < 1e-12);
}

/// Fail-safe negative: an oblique multi-rim cap pushed so far INWARD that a seam
/// corner passes the flat's bottom (the wall collapses/inverts) must refuse, not
/// emit a degenerate solid.
#[test]
fn oblique_multi_rim_cap_tearing_push_refuses() {
    let alpha = 30.0_f64.to_radians();
    let (solid, cap) = flatted_oblique_capped(
        || make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 3.0, 10.0).unwrap(),
        2.0,
        alpha,
        8.0,
    );
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    let n = Vec3::new(alpha.sin(), 0.0, alpha.cos());
    // The cap sits around z∈[6.85, 9.15]; a push of −9 (axial slide −9/cos30 ≈
    // −10.4) drives every corner below the base plane z=0.
    let err = move_faces(&solid, &[cap], n.scale(-9.0))
        .expect_err("a cap pushed through the base must refuse");
    assert!(
        err.contains("collapse")
            || err.contains("invert")
            || err.contains("tear")
            || err.contains("refusing")
            || err.contains("validation"),
        "unexpected refusal: {err}"
    );
    assert!(solid.validate().is_empty());
}

// --- partial-sweep ruled neighbours (fillet-band adjacency) ------------------

/// The `z`-closed rim edge of a `+z` cylinder at axial height `h` (a full
/// circle, so `start_vertex == end_vertex`).
fn z_rim_edge(solid: &BrepSolid, h: f64) -> u64 {
    solid
        .edges
        .iter()
        .find(|edge| {
            edge.start_vertex_id == edge.end_vertex_id
                && edge
                    .curve
                    .evaluate(edge.t0)
                    .map(|point| (point.z - h).abs() < 1e-9)
                    .unwrap_or(false)
        })
        .expect("cylinder has a closed rim edge at that height")
        .id
}

/// Backlog #1: a planar cap that ends a FILLET BAND can be pushed along the
/// band's own axis — the band extends and re-intersects. The band is a
/// partial-sweep straight-generatrix `Revolution` (NOT a full-2π
/// `RuledRevolution`), so this exercises the generalised ruled-neighbour heal.
/// The solid stays valid and the volume scales exactly with the prism length.
#[test]
fn pushing_a_cap_extends_a_fillet_band_neighbour() {
    // Box 4×3×4; fillet the top-right edge running along +y at (x=4, z=4). The
    // band is a quarter cylinder whose axis is +y, spanning the box's y-extent.
    let block = make_box_brep(Vec3::new(0.0, 0.0, 0.0), 4.0, 3.0, 4.0).unwrap();
    let edge = edge_id_near(&block, Vec3::new(4.0, 1.5, 4.0));
    let filleted = fillet_edge(&block, edge, 1.0, Some("F")).unwrap();
    assert!(
        filleted.validate().is_empty(),
        "fillet fixture: {:?}",
        filleted.validate()
    );
    // Fixture guard: the band must recognise as the general Revolution kind, so
    // the heal MUST take the new partial-sweep ruled path (not RuledRevolution).
    assert!(
        filleted.shells[0].faces.iter().any(|face| matches!(
            face.surface.analytic(),
            Some(AnalyticSurface::Revolution { .. })
        )),
        "fillet band must be a partial-sweep Revolution"
    );

    let length = 3.0_f64;
    let far_cap = resolve_face_by_point(&filleted, Vec3::new(2.0, length, 2.0)).unwrap();
    let v0 = solid_signed_volume(&filleted).unwrap();

    // OUT (band grows along its axis) and IN (band shrinks, growth early-returns).
    for d in [0.75_f64, -0.75] {
        let pushed = move_faces(&filleted, &[far_cap], Vec3::new(0.0, d, 0.0))
            .unwrap_or_else(|e| panic!("push fillet cap by {d}: {e}"));
        assert!(
            pushed.validate().is_empty(),
            "pushed solid must validate (d={d}): {:?}",
            pushed.validate()
        );
        // Uniform prism along +y ⇒ the volume scales with (L + d)/L exactly
        // (tolerance covers tessellated-volume noise on the curved fillet band).
        let v = solid_signed_volume(&pushed).unwrap();
        assert!(
            (v - v0 * (length + d) / length).abs() < 1e-3,
            "volume {v}, expected {} (d={d})",
            v0 * (length + d) / length
        );
        // Pure geometry edit: no topology created or destroyed, sign preserved.
        assert_eq!(pushed.vertices.len(), filleted.vertices.len());
        assert_eq!(pushed.edges.len(), filleted.edges.len());
        assert_eq!(pushed.shells[0].faces.len(), filleted.shells[0].faces.len());
        assert!(v0 * v > 0.0, "signed volume must keep its sign (d={d})");
    }
    // The input is untouched.
    assert!(filleted.validate().is_empty());
}

/// Fail-safe negative: a CURVED-generatrix revolution neighbour (a toroidal
/// fillet on a cylinder's rim) is NOT a ruled carrier, so pushing the adjacent
/// cap into it must refuse cleanly — never emit a bad solid.
#[test]
fn pushing_a_cap_against_a_toroidal_fillet_refuses() {
    let cyl = make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 3.0, 6.0).unwrap();
    let rim = z_rim_edge(&cyl, 6.0);
    let filleted = fillet_edge(&cyl, rim, 0.5, Some("T")).unwrap();
    assert!(
        filleted.validate().is_empty(),
        "toroidal fillet fixture: {:?}",
        filleted.validate()
    );
    let top_cap = resolve_face_by_point(&filleted, Vec3::new(0.0, 0.0, 6.0)).unwrap();
    let result = move_faces(&filleted, &[top_cap], Vec3::new(0.0, 0.0, 0.5));
    assert!(
        result.is_err(),
        "a toroidal (curved-generatrix) neighbour must refuse, got a solid"
    );
    // The input is untouched.
    assert!(filleted.validate().is_empty());
}

// ---------------------------------------------------------------------------
// Backlog #5 — Plane × Sphere: a planar push re-intersects a FIXED sphere
// neighbour. The moved plane's new position ∩ the fixed sphere is an exact
// circle (`intersect_plane_quadric`); the sphere re-trims to that new rim.
// ---------------------------------------------------------------------------

/// An upper half-ball (sphere ∩ z≥0): a flat disk (z=0) whose sole boundary is
/// the great-circle rim shared with the spherical dome. The disk is a planar
/// neighbour of the sphere — exactly the Plane × Sphere adjacency this slice
/// heals.
fn upper_half_ball(r: f64) -> BrepSolid {
    let sphere =
        crate::make_sphere_brep(Vec3::new(0.0, 0.0, 0.0), r, Vec3::new(0.0, 0.0, 1.0)).unwrap();
    let box_up = make_box_brep(Vec3::new(-2.0 * r, -2.0 * r, 0.0), 4.0 * r, 4.0 * r, 2.0 * r).unwrap();
    let options = crate::BooleanOptions {
        merge_coplanar_faces: true,
        ..crate::BooleanOptions::default()
    };
    crate::boolean_operation(&sphere, &box_up, crate::BooleanOperation::Intersect, &options).unwrap()
}

/// Radius, off the given axis, of the edge shared by a spherical face and a
/// planar face (the plane × sphere rim circle).
fn sphere_plane_rim_radius(solid: &BrepSolid, axis_point: Vec3, axis: Vec3) -> f64 {
    use crate::AnalyticSurface;
    let mut faces_of_edge: std::collections::HashMap<u64, Vec<u64>> = Default::default();
    let mut kind: std::collections::HashMap<u64, &'static str> = Default::default();
    for shell in &solid.shells {
        for face in &shell.faces {
            let k = match face.surface.analytic() {
                Some(AnalyticSurface::Sphere { .. }) => "sphere",
                Some(AnalyticSurface::Plane { .. }) => "plane",
                _ => "other",
            };
            kind.insert(face.id, k);
            for lp in &face.loops {
                for ce in &lp.coedges {
                    faces_of_edge.entry(ce.edge_id).or_default().push(face.id);
                }
            }
        }
    }
    for edge in &solid.edges {
        if edge.degenerate {
            continue;
        }
        let incident = faces_of_edge.get(&edge.id).cloned().unwrap_or_default();
        let has_sphere = incident.iter().any(|f| kind.get(f) == Some(&"sphere"));
        let has_plane = incident.iter().any(|f| kind.get(f) == Some(&"plane"));
        if has_sphere && has_plane {
            let point = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).unwrap();
            let delta = point.sub(axis_point);
            return delta.sub(axis.scale(delta.dot(axis))).length();
        }
    }
    panic!("no sphere×plane rim edge found");
}

/// Push the flat disk of a half-ball along the sphere axis, both INTO the dome
/// (+z, cap shrinks) and OUT past the equator (−z, cap grows — the seam meridian
/// trim EXTENDS below its original span into the curve's untrimmed domain). The
/// fixed sphere re-intersects to the new small circle and re-trims; the solid
/// stays a valid spherical cap of the analytic volume π(R−d)²(2R+d)/3.
#[test]
fn push_planar_face_reintersects_sphere_neighbour() {
    let r = 5.0f64;
    for d in [1.0_f64, -1.0] {
        let half = upper_half_ball(r);
        assert!(half.validate().is_empty(), "fixture: {:?}", half.validate());
        let (nv, ne, nf) = (
            half.vertices.len(),
            half.edges.len(),
            half.shells[0].faces.len(),
        );
        let v0 = solid_signed_volume(&half).unwrap();
        let disk = resolve_face_by_point(&half, Vec3::new(0.0, 0.0, 0.0)).expect("flat disk face");

        let pushed = move_faces(&half, &[disk], Vec3::new(0.0, 0.0, d))
            .unwrap_or_else(|e| panic!("push disk by {d}: {e}"));
        assert!(
            pushed.validate().is_empty(),
            "validate after push {d}: {:?}",
            pushed.validate()
        );
        // Spherical cap of height h = R − d.
        let expected = std::f64::consts::PI * (r - d) * (r - d) * (2.0 * r + d) / 3.0;
        let got = solid_signed_volume(&pushed).unwrap().abs();
        assert!(
            (got - expected).abs() < 1e-2,
            "push {d}: cap volume {got}, expected {expected}"
        );
        // The rim is the small circle where z=d meets the fixed sphere.
        let want_rim = (r * r - d * d).sqrt();
        let got_rim =
            sphere_plane_rim_radius(&pushed, Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0));
        assert!(
            (got_rim - want_rim).abs() < 1e-6,
            "push {d}: rim radius {got_rim}, expected {want_rim}"
        );
        // Pure geometry edit: topology count and volume sign are preserved.
        assert_eq!(pushed.vertices.len(), nv, "vertex count (d={d})");
        assert_eq!(pushed.edges.len(), ne, "edge count (d={d})");
        assert_eq!(pushed.shells[0].faces.len(), nf, "face count (d={d})");
        assert!(v0 * solid_signed_volume(&pushed).unwrap() > 0.0, "sign (d={d})");
        // The input is never mutated.
        assert!(half.validate().is_empty());
    }
}

/// Fail-safe: pushing the disk far enough that the grown/translated plane no
/// longer meets the fixed sphere (d ≥ R) makes the cap vanish — refuse cleanly.
#[test]
fn push_planar_sphere_vanishing_cap_refuses() {
    let r = 5.0f64;
    let half = upper_half_ball(r);
    let disk = resolve_face_by_point(&half, Vec3::new(0.0, 0.0, 0.0)).expect("flat disk face");
    let err = move_faces(&half, &[disk], Vec3::new(0.0, 0.0, r)).expect_err("vanished cap");
    assert!(
        err.contains("vanish") || err.contains("tangent") || err.contains("refus"),
        "unexpected refusal: {err}"
    );
    assert!(half.validate().is_empty());
}

/// Scope discipline: a non-axis-perpendicular plane × sphere adjacency (the
/// sphere's polar axis lies +x, IN the z=0 cut plane, so the section is a
/// through-poles great circle — not the supported fixed-latitude rim) must
/// refuse cleanly this slice — never emit a bad solid.
#[test]
fn push_planar_sphere_oblique_neighbour_refuses() {
    let r = 5.0f64;
    // Sphere with a +x polar axis, cut by z=0 (a great circle through both poles,
    // NOT a latitude circle perpendicular to the sphere axis).
    let sphere =
        crate::make_sphere_brep(Vec3::new(0.0, 0.0, 0.0), r, Vec3::new(1.0, 0.0, 0.0)).unwrap();
    let box_up = make_box_brep(Vec3::new(-2.0 * r, -2.0 * r, 0.0), 4.0 * r, 4.0 * r, 2.0 * r).unwrap();
    let options = crate::BooleanOptions {
        merge_coplanar_faces: true,
        ..crate::BooleanOptions::default()
    };
    let half =
        crate::boolean_operation(&sphere, &box_up, crate::BooleanOperation::Intersect, &options)
            .unwrap();
    assert!(half.validate().is_empty(), "fixture: {:?}", half.validate());
    let disk = resolve_face_by_point(&half, Vec3::new(0.0, 0.0, 0.0)).expect("flat disk face");
    let result = move_faces(&half, &[disk], Vec3::new(0.0, 0.0, 0.5));
    assert!(
        result.is_err(),
        "an oblique plane × sphere rim must refuse, got a solid"
    );
    assert!(half.validate().is_empty());
}

/// Scope discipline (torus / general-revolution neighbour still refuses): a
/// planar cap that borders a TRUE torus surface re-intersects nothing this
/// slice — the push must refuse cleanly (routing only handles spheres).
#[test]
fn push_planar_against_torus_neighbour_refuses() {
    // Half a torus (torus ∩ z≥0): the flat cut faces border the toroidal wall.
    let torus =
        crate::make_torus_brep(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.0, 0.0, 1.0), 6.0, 2.0).unwrap();
    let box_up = make_box_brep(Vec3::new(-20.0, -20.0, 0.0), 40.0, 40.0, 20.0).unwrap();
    let options = crate::BooleanOptions {
        merge_coplanar_faces: true,
        ..crate::BooleanOptions::default()
    };
    // Every step below asserts. This is the ONLY pin for the Plane × Torus
    // refusal cell of the push-face neighbour matrix, and it used to be a
    // triple conditional (bail on a failed boolean, then `if validate()
    // .is_empty()`, then `if let Some(flat)`) that would pass green if the
    // fixture stopped building, if it stopped validating, or if the planar
    // face vanished — i.e. it could pass three different ways without ever
    // reaching the refusal it exists to guard.
    let half_torus =
        crate::boolean_operation(&torus, &box_up, crate::BooleanOperation::Intersect, &options)
            .expect("torus ∩ box fixture must build — this test's only subject");
    let issues = half_torus.validate();
    assert!(issues.is_empty(), "half-torus fixture is invalid: {issues:?}");
    // Find a planar face that borders the toroidal wall and push it.
    use crate::AnalyticSurface;
    let flat = half_torus
        .shells
        .iter()
        .flat_map(|s| &s.faces)
        .find(|f| matches!(f.surface.analytic(), Some(AnalyticSurface::Plane { .. })))
        .map(|f| f.id)
        .expect("the half torus must expose a planar cut face to push");
    let result = move_faces(&half_torus, &[flat], Vec3::new(0.0, 0.0, 0.5));
    assert!(
        result.is_err(),
        "a torus neighbour of a planar push must refuse, got a solid"
    );
    assert!(half_torus.validate().is_empty());
}

// --- Plane-push refusal pins ------------------------------------------------
//
// `face_move.rs` carries 47 of the offset family's 209 capability refusals and
// the refusal census
// (`docs/developer/kernel-plans/offset-refusal-census.md` §2.2) measured **30 of
// them reached by nothing** — no test, no fixture, no probe. A refusal nothing
// reaches is not evidence of anything: it may be dead code, it may be firing on
// inputs that should work, or it may be the only thing between a user and a
// wrong solid, and there is no way to tell from reading it.
//
// The block below pins every site `examples/plane_push_refusal_probe.rs`
// reaches that the corpus did not. Each test asserts a needle that identifies
// ONE site — census §2.3 measured that the corpus's existing refusal assertions
// are overwhelmingly generic (one needle, `"refusing"`, matches 92 distinct
// sites), so a refusal that moves from one gate to another inside the same
// function passes them silently. These do not.
//
// Every test also asserts that the INPUT is untouched, because a refusal that
// mutated its argument on the way out would be worse than the refusal.

/// A box whose `+x` side carries a surface that evaluates *identically* to the
/// original bilinear patch — it is that patch degree-elevated in `u` from 1 to
/// 2 — but which `NurbsSurface::is_affine` rejects (it wants exactly 2 × 2
/// control points), so `analytic()` returns `None`.
///
/// Degree-elevating a degree-1 Bezier to degree 2 with control points
/// `P0, (P0+P1)/2, P1` reproduces `(1−t)·P0 + t·P1` at every parameter, so every
/// pcurve on the face stays exactly valid and the solid still validates. This is
/// a legitimate B-rep and it is what a STEP import of a planar `B_SPLINE_SURFACE`
/// hands the kernel — and it is the ONLY shape that reaches the "borders a
/// non-planar, non-axis-parallel carrier" gate, which tests the analytic TAG
/// while the arm 500 lines earlier has already accepted the same face
/// geometrically.
fn box_with_unrecognised_planar_side() -> (BrepSolid, u64, u64) {
    let mut solid = make_box_brep(Vec3::new(-5.0, -5.0, 0.0), 10.0, 10.0, 6.0).unwrap();
    let top = plane_face_with_normal(&solid, Vec3::new(0.0, 0.0, 1.0), 6.0);
    let side = plane_face_with_normal(&solid, Vec3::new(1.0, 0.0, 0.0), 5.0);
    for shell in &mut solid.shells {
        for face in &mut shell.faces {
            if face.id != side {
                continue;
            }
            let surface = &face.surface;
            assert_eq!(surface.degree_u, 1, "box faces are bilinear");
            assert_eq!(surface.control_points.len(), 2);
            let (u0, u1) = (surface.knots_u[0], *surface.knots_u.last().unwrap());
            let row0 = surface.control_points[0].clone();
            let row1 = surface.control_points[1].clone();
            let middle: Vec<crate::Vec4> = row0
                .iter()
                .zip(row1.iter())
                .map(|(a, b)| crate::Vec4 {
                    x: 0.5 * (a.x + b.x),
                    y: 0.5 * (a.y + b.y),
                    z: 0.5 * (a.z + b.z),
                    w: 0.5 * (a.w + b.w),
                })
                .collect();
            let elevated = NurbsSurface::new(
                2,
                surface.degree_v,
                vec![u0, u0, u0, u1, u1, u1],
                surface.knots_v.clone(),
                vec![row0, middle, row1],
            )
            .expect("degree-elevated planar patch");
            // The elevation is exact: same point at every parameter.
            for (u, v) in [(0.0, 0.0), (0.3, 0.7), (1.0, 1.0), (0.5, 0.5)] {
                let [a0, a1] = surface.domain_u().unwrap();
                let [b0, b1] = surface.domain_v().unwrap();
                let (pu, pv) = (a0 + (a1 - a0) * u, b0 + (b1 - b0) * v);
                let before = surface.evaluate(pu, pv).unwrap();
                let after = elevated.evaluate(pu, pv).unwrap();
                assert!(
                    after.sub(before).length() < 1e-12,
                    "degree elevation must preserve the parameterisation"
                );
            }
            assert!(
                elevated.analytic().is_none(),
                "the elevated patch must NOT recognise as a plane — that is the point"
            );
            face.surface = elevated;
        }
    }
    assert!(
        solid.validate().is_empty(),
        "the elevated box is still a valid solid: {:?}",
        solid.validate()
    );
    (solid, top, side)
}

fn plane_face_with_normal(solid: &BrepSolid, normal: Vec3, offset: f64) -> u64 {
    use crate::AnalyticSurface;
    solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .find(|face| match face.surface.analytic() {
            Some(AnalyticSurface::Plane {
                origin,
                u_dir,
                v_dir,
                ..
            }) => {
                let n = match u_dir.cross(*v_dir).normalized() {
                    Ok(n) => n,
                    Err(_) => return false,
                };
                n.cross(normal).length() < 1e-9 && (origin.dot(normal) - offset).abs() < 1e-7
            }
            _ => false,
        })
        .map(|face| face.id)
        .unwrap_or_else(|| panic!("no planar face with normal {normal:?} at {offset}"))
}

fn merge_options() -> crate::BooleanOptions {
    crate::BooleanOptions {
        merge_coplanar_faces: true,
        ..crate::BooleanOptions::default()
    }
}

fn boolean_of(a: &BrepSolid, b: &BrepSolid, op: crate::BooleanOperation) -> BrepSolid {
    crate::boolean_operation(a, b, op, &merge_options()).expect("fixture boolean")
}

fn rot_x_af(angle: f64) -> AffineTransform {
    let (s, c) = angle.sin_cos();
    AffineTransform::new([
        1.0, 0.0, 0.0, 0.0, //
        0.0, c, -s, 0.0, //
        0.0, s, c, 0.0, //
        0.0, 0.0, 0.0, 1.0,
    ])
    .unwrap()
}

/// A square PYRAMID: base `2·half` at `z = 0`, apex at `(0, 0, half)`. The apex
/// is a valence-FOUR vertex — four carrier planes concurrent in one point —
/// which `solve_corner` can only place by taking a best-conditioned TRIPLE. A
/// push that breaks the concurrency is the only construction that reaches the
/// over-constrained-corner refusal.
fn square_pyramid(half: f64) -> BrepSolid {
    let big = 10.0 * half;
    let quarter = std::f64::consts::FRAC_PI_4;
    let mut solid = make_box_brep(
        Vec3::new(-half, -half, 0.0),
        2.0 * half,
        2.0 * half,
        2.0 * half,
    )
    .unwrap();
    let px = make_box_brep(Vec3::new(0.0, -big, -big), 2.0 * big, 2.0 * big, 2.0 * big).unwrap();
    let nx = make_box_brep(
        Vec3::new(-2.0 * big, -big, -big),
        2.0 * big,
        2.0 * big,
        2.0 * big,
    )
    .unwrap();
    let py = make_box_brep(Vec3::new(-big, 0.0, -big), 2.0 * big, 2.0 * big, 2.0 * big).unwrap();
    let ny = make_box_brep(
        Vec3::new(-big, -2.0 * big, -big),
        2.0 * big,
        2.0 * big,
        2.0 * big,
    )
    .unwrap();
    for (raw, rot, shift) in [
        (px, rot_y(-quarter), Vec3::new(half, 0.0, 0.0)),
        (nx, rot_y(quarter), Vec3::new(-half, 0.0, 0.0)),
        (py, rot_x_af(quarter), Vec3::new(0.0, half, 0.0)),
        (ny, rot_x_af(-quarter), Vec3::new(0.0, -half, 0.0)),
    ] {
        let cutter =
            crate::transform_brep(&raw, compose(translate_af(shift), rot), false).unwrap();
        solid = boolean_of(&solid, &cutter, crate::BooleanOperation::Subtract);
    }
    solid
}

/// A rectangular POCKET milled into a cylinder's wall: the pocket floor is a
/// plane that CONTAINS the cylinder axis direction, which is what makes the
/// rim's affine map degenerate.
fn pocketed_cylinder(r: f64, h: f64) -> (BrepSolid, u64) {
    let solid = boolean_of(
        &make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), r, h).unwrap(),
        &make_box_brep(
            Vec3::new(0.6 * r, -2.0 * r, 0.3 * h),
            r,
            4.0 * r,
            0.4 * h,
        )
        .unwrap(),
        crate::BooleanOperation::Subtract,
    );
    let floor = plane_face_with_normal(&solid, Vec3::new(1.0, 0.0, 0.0), 0.6 * r);
    (solid, floor)
}

/// A sphere ZONE: the ball cut by TWO axis-perpendicular planes, so its one
/// spherical face carries two rims and a seam meridian trimmed between them.
fn sphere_zone(r: f64, low: f64, high: f64) -> (BrepSolid, u64) {
    let solid = boolean_of(
        &crate::make_sphere_brep(Vec3::default(), r, Vec3::new(0.0, 0.0, 1.0)).unwrap(),
        &make_box_brep(
            Vec3::new(-2.0 * r, -2.0 * r, low),
            4.0 * r,
            4.0 * r,
            high - low,
        )
        .unwrap(),
        crate::BooleanOperation::Intersect,
    );
    let top = plane_face_with_normal(&solid, Vec3::new(0.0, 0.0, 1.0), high);
    (solid, top)
}

/// CENSUS CORRECTION, pinned. `offset-refusal-census.md` §7.2 attributes the
/// Plane × Torus refusal to `face_move.rs`'s "SM3 territory" arm in the FACE
/// loop; the arm that actually fires is the edge-CLASSIFICATION loop's carrier
/// gate, hundreds of lines earlier, and it used to produce its error by calling
/// `cached_plane` purely to fail — so the user got `plane_of_surface`'s generic
/// "face is not planar (curved neighbours are deferred in this slice)", naming
/// neither the face nor the neighbour, out of a helper three features share.
///
/// This test is the durable form of that measurement: the message must name the
/// boundary edge, the face and the carrier kind.
#[test]
fn push_plane_across_a_torus_neighbour_names_the_face_and_the_carrier() {
    let plate = make_box_brep(Vec3::new(-10.0, -10.0, 0.0), 20.0, 20.0, 6.0).unwrap();
    let groove = crate::make_torus_brep(
        Vec3::new(0.0, 0.0, 6.0),
        Vec3::new(0.0, 0.0, 1.0),
        5.0,
        1.5,
    )
    .unwrap();
    let solid = boolean_of(&plate, &groove, crate::BooleanOperation::Subtract);
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    let top = plane_face_with_normal(&solid, Vec3::new(0.0, 0.0, 1.0), 6.0);
    for translation in [Vec3::new(0.0, 0.0, 0.5), Vec3::new(0.4, 0.0, 0.0)] {
        let error = move_faces(&solid, &[top], translation)
            .expect_err("a torus fixed neighbour must refuse");
        assert!(
            error.contains("the fixed neighbour across boundary edge"),
            "the refusal must come from the edge-CLASSIFICATION carrier gate, \
             not the face loop's SM3 arm: {error}"
        );
        assert!(
            error.contains("is a torus"),
            "the refusal must name the carrier kind: {error}"
        );
        assert!(
            !error.contains("in this slice"),
            "slice-scoped wording must not leak out of a shared helper: {error}"
        );
    }
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// The "SM3 territory" arm the census cites DOES exist and IS reachable — but
/// only for a fixed neighbour that is geometrically planar and analytically
/// unrecognised, because a genuinely curved neighbour is refused by the
/// classification gate above first. Pinning it here is what makes the
/// attribution above falsifiable rather than an assertion.
#[test]
fn push_plane_across_an_unrecognised_planar_neighbour_refuses_at_the_sm3_arm() {
    let (solid, top, _side) = box_with_unrecognised_planar_side();
    let error = move_faces(&solid, &[top], Vec3::new(0.0, 0.0, 0.5))
        .expect_err("an analytically-unrecognised boundary neighbour must refuse");
    assert!(
        error.contains("borders a non-planar, non-axis-parallel"),
        "expected the SM3-territory boundary-edge gate: {error}"
    );
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// The complement, and the reason the gate above is a TAG test rather than a
/// geometry test: the very same unrecognised patch is pushed successfully when
/// it is the MOVED face. `move_faces` only needs a plane where it re-intersects,
/// and it gets one from `plane_of_surface` — the geometric test — there.
#[test]
fn an_unrecognised_planar_face_can_itself_be_pushed() {
    let (solid, _top, side) = box_with_unrecognised_planar_side();
    let before = solid_signed_volume(&solid).unwrap().abs();
    let pushed = move_faces(&solid, &[side], Vec3::new(0.5, 0.0, 0.0))
        .expect("an unrecognised PLANAR moved face pushes");
    assert!(
        pushed.validate().is_empty(),
        "pushed solid is invalid: {:?}",
        pushed.validate()
    );
    let after = solid_signed_volume(&pushed).unwrap().abs();
    // 10 x 10 x 6 grown to 10.5 x 10 x 6.
    assert!((before - 600.0).abs() < 1e-9, "fixture volume {before}");
    assert!((after - 630.0).abs() < 1e-9, "pushed volume {after}");
}

/// A moved carrier that is not planar and must be re-intersected at a corner:
/// pushing a cylinder's SIDE face along its own axis (the sideways push, which
/// the corpus pins, rides rigidly instead). The refusal must name the moved face
/// and its carrier, not merely say "not planar".
#[test]
fn pushing_a_cylinder_wall_along_its_axis_names_the_moved_carrier() {
    use crate::AnalyticSurface;
    let solid = make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 3.0, 10.0).unwrap();
    let wall = solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .find(|face| {
            matches!(
                face.surface.analytic(),
                Some(AnalyticSurface::RuledRevolution { .. })
            )
        })
        .map(|face| face.id)
        .expect("a cylinder wall");
    let error = move_faces(&solid, &[wall], Vec3::new(0.0, 0.0, 0.5))
        .expect_err("a curved moved carrier at a re-solved corner must refuse");
    assert!(
        error.contains("a MOVED carrier meeting a fixed neighbour at vertex"),
        "expected the generic corner solve's moved-carrier gate: {error}"
    );
    assert!(error.contains("is a cylinder"), "name the carrier: {error}");
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// A cap plane that CONTAINS the cylinder axis: the rim's affine map is a pure
/// axis translation scaled by `n · axis`, which is zero here, so there is no
/// map to build. Reached by a rectangular pocket milled into a cylinder wall.
#[test]
fn pushing_a_pocket_floor_parallel_to_the_cylinder_axis_refuses() {
    let (solid, floor) = pocketed_cylinder(4.0, 12.0);
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    for d in [0.3_f64, -0.3] {
        let error = move_faces(&solid, &[floor], Vec3::new(d, 0.0, 0.0))
            .expect_err("an axis-parallel cap plane has no rim map");
        assert!(
            error.contains("the cap plane is parallel to the cylinder axis"),
            "expected the rim-map cylinder branch's degenerate gate: {error}"
        );
    }
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// The same pocket floor pushed far enough OUT that the corner's carrier line
/// no longer meets the cylinder at all — the carrier-level corner solve's own
/// refusal, which is a different gate from the rim map above.
#[test]
fn pushing_a_pocket_floor_off_its_ruled_neighbour_refuses() {
    let (solid, floor) = pocketed_cylinder(4.0, 12.0);
    let error = move_faces(&solid, &[floor], Vec3::new(3.0, 0.0, 0.0))
        .expect_err("a corner driven off the cylinder must refuse");
    assert!(
        error.contains("no longer meets the fixed ruled neighbour"),
        "expected the carrier-level corner solve's refusal: {error}"
    );
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// A curved fixed edge on a CYLINDER carrier: the section is an ellipse, which
/// `conic_arc_on_ruled` builds only for a cone (the cone's section is the
/// projective image of its base circle from the apex; a cylinder has no apex).
/// Reached by a lengthwise flat, whose cap-ring arcs are the curved fixed edges.
#[test]
fn rebuilding_a_curved_section_on_a_cylinder_carrier_refuses() {
    let solid = boolean_of(
        &make_cylinder_brep(Vec3::default(), Vec3::new(0.0, 0.0, 1.0), 3.0, 10.0).unwrap(),
        &make_box_brep(Vec3::new(1.5, -6.0, -1.0), 8.0, 12.0, 12.0).unwrap(),
        crate::BooleanOperation::Subtract,
    );
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    let flat = plane_face_with_normal(&solid, Vec3::new(1.0, 0.0, 0.0), 1.5);
    let error = move_faces(&solid, &[flat], Vec3::new(0.4, 0.0, 0.0))
        .expect_err("an elliptical section on a cylinder is deferred");
    assert!(
        error.contains("curved section on a CYLINDER carrier"),
        "expected the cylinder branch of the conic rebuild: {error}"
    );
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// A valence-FOUR corner: four planes concurrent at a pyramid apex. Translating
/// ONE of them breaks the concurrency, so the best-conditioned triple's solution
/// does not lie on the fourth — the group has torn away from its neighbours and
/// no manifold heal exists. This is the gate that stands between that and an
/// invalid solid.
#[test]
fn pushing_one_face_of_a_pyramid_apex_tears_and_refuses() {
    let solid = square_pyramid(6.0);
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    assert_eq!(
        solid.shells.iter().map(|s| s.faces.len()).sum::<usize>(),
        5,
        "a square pyramid: four slopes and a base"
    );
    use crate::AnalyticSurface;
    let slope = solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .find(|face| match face.surface.analytic() {
            Some(AnalyticSurface::Plane { u_dir, v_dir, .. }) => {
                let n = u_dir.cross(*v_dir).normalized().unwrap_or_default();
                (n.x.abs() - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6
                    && (n.z.abs() - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6
            }
            _ => false,
        })
        .map(|face| face.id)
        .expect("a sloping pyramid face");
    let error = move_faces(&solid, &[slope], Vec3::new(0.3, 0.0, 0.3))
        .expect_err("breaking a four-plane corner must refuse");
    assert!(
        error.contains("tears away from its neighbours"),
        "expected the over-constrained corner residual gate: {error}"
    );
    // The BASE, whose push keeps every corner on its own three planes, still works.
    let base = plane_face_with_normal(&solid, Vec3::new(0.0, 0.0, 1.0), 0.0);
    let pushed = move_faces(&solid, &[base], Vec3::new(0.0, 0.0, 2.0))
        .expect("pushing the base of a pyramid is a plain frustum trim");
    assert!(pushed.validate().is_empty(), "{:?}", pushed.validate());
    // The frustum between z = 2 and the apex at z = 6: ∫ 4(6−z)² dz = 4·4³/3.
    let expected = 4.0 * 4.0f64.powi(3) / 3.0;
    let got = solid_signed_volume(&pushed).unwrap().abs();
    assert!(
        (got - expected).abs() < 1e-9,
        "pyramid frustum volume {got} vs {expected}"
    );
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

// --- the Plane × Sphere lane ------------------------------------------------

/// A moved GROUP against a sphere neighbour. The sphere lane takes a single
/// planar face only; the generic path cannot heal a sphere rim at all, so this
/// has to be a refusal and it has to say which restriction it is.
#[test]
fn pushing_a_group_against_a_sphere_neighbour_refuses() {
    let (solid, top) = sphere_zone(5.0, -2.0, 2.0);
    let bottom = plane_face_with_normal(&solid, Vec3::new(0.0, 0.0, 1.0), -2.0);
    let error = move_faces(&solid, &[top, bottom], Vec3::new(0.0, 0.0, 0.4))
        .expect_err("a moved group against a sphere is deferred");
    assert!(
        error.contains("a moved GROUP against a sphere neighbour"),
        "expected the sphere lane's single-face restriction: {error}"
    );
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// A planar face that borders a sphere across ONE edge and four planes across
/// the others (a spherical dimple in a plate's top face). The sphere lane is
/// entered because of the one sphere rim and then refuses on the first planar
/// neighbour — naming the edge, so a user can see which adjacency is the problem.
#[test]
fn pushing_a_plate_with_a_spherical_dimple_refuses_on_the_mixed_neighbour() {
    let plate = make_box_brep(Vec3::new(-10.0, -10.0, 0.0), 20.0, 20.0, 6.0).unwrap();
    let ball = crate::make_sphere_brep(
        Vec3::new(0.0, 0.0, 6.0),
        4.0,
        Vec3::new(0.0, 0.0, 1.0),
    )
    .unwrap();
    let solid = boolean_of(&plate, &ball, crate::BooleanOperation::Subtract);
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    let top = plane_face_with_normal(&solid, Vec3::new(0.0, 0.0, 1.0), 6.0);
    let error = move_faces(&solid, &[top], Vec3::new(0.0, 0.0, 0.3))
        .expect_err("mixed sphere + planar neighbours are deferred");
    assert!(
        error.contains("borders a non-sphere fixed"),
        "expected the sphere lane's neighbour-class gate: {error}"
    );
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// A ball capped by a TILTED plane whose rim is still a single closed circle:
/// the OBLIQUE-rim gate, which is a different site from the multi-edge-rim gate
/// the corpus's through-poles fixture reaches. Both must stay loud, and a test
/// that only asserted "refuses" could not tell them apart (census §2.3).
#[test]
fn pushing_an_obliquely_capped_ball_refuses_as_an_oblique_rim() {
    let sphere =
        crate::make_sphere_brep(Vec3::default(), 5.0, Vec3::new(0.0, 0.0, 1.0)).unwrap();
    let raw = make_box_brep(Vec3::new(-15.0, -15.0, -30.0), 30.0, 30.0, 30.0).unwrap();
    let tilt = compose(
        translate_af(Vec3::new(0.0, 0.0, 2.0)),
        rot_y(45.0_f64.to_radians()),
    );
    let cutter = crate::transform_brep(&raw, tilt, false).unwrap();
    let solid = boolean_of(&sphere, &cutter, crate::BooleanOperation::Intersect);
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    use crate::AnalyticSurface;
    let disk = solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .find(|face| matches!(face.surface.analytic(), Some(AnalyticSurface::Plane { .. })))
        .map(|face| face.id)
        .expect("the tilted cap");
    let error = move_faces(&solid, &[disk], Vec3::new(0.0, 0.0, 0.4))
        .expect_err("an oblique plane × sphere rim is deferred");
    assert!(
        error.contains("an OBLIQUE plane × sphere rim"),
        "expected the axis-perpendicular-only gate, not the multi-edge one: {error}"
    );
    assert!(solid.validate().is_empty(), "the input is never mutated");
}

/// A sphere ZONE's top disk pushed past the zone's other rim: the seam meridian
/// between the two rims would have to run backwards. The supported pushes on
/// either side of that bound still work, which is what makes this a bound and
/// not a blanket refusal.
#[test]
fn pushing_a_sphere_zone_disk_past_its_other_rim_refuses() {
    let (solid, top) = sphere_zone(5.0, -4.0, 2.0);
    assert!(solid.validate().is_empty(), "fixture: {:?}", solid.validate());
    // Inside the bound: the disk slides down and the cap re-intersects cleanly.
    for d in [-0.5_f64, -3.99] {
        let pushed = move_faces(&solid, &[top], Vec3::new(0.0, 0.0, d))
            .unwrap_or_else(|e| panic!("zone disk push {d}: {e}"));
        assert!(pushed.validate().is_empty(), "{:?}", pushed.validate());
    }
    // Past it: the meridian trim would collapse or invert.
    let error = move_faces(&solid, &[top], Vec3::new(0.0, 0.0, -6.0))
        .expect_err("a disk pushed past the other rim must refuse");
    assert!(
        error.contains("trim collapses or inverts under"),
        "expected the seam-meridian trim guard: {error}"
    );
    assert!(solid.validate().is_empty(), "the input is never mutated");
}