BREP_kernel 0.14.0

A boundary representation (BREP) geometry kernel for building CAD applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
use crate::{KernelRefusal, KernelStage, OrRefuse};
use super::*;

/// Record one split parameter on `edge`, honouring the near-endpoint guard
/// and the dedupe band.  Two split points closer than the assembler's weld
/// tolerance can never survive as distinct vertices — they weld at assembly
/// and leave zero-length edges behind — so they are folded here instead.
///
/// Free-standing because the SOLID-level self-touch scan
/// ([`super::self_touch::self_touch_edge_splits`]) has no builder to record
/// into and must not diverge from the guard the builder applies.
/// `BREP_IMPRINT_HULL_CULL`: skips the overlap test and curve crossing for
/// boundary edges whose control hull is clear of the section's. On by
/// default; `0`/`off` disables it.
/// `BREP_IMPRINT_PIERCE_CULL` (lane P3b row 1, 2026-10-26): skips the exact
/// edge/carrier pierce solve for a boundary edge whose control hull is clear
/// of the section's by more than every band a pierce is read through (see
/// the PIERCE CULL note in `process_curve`). On by default (promoted 2026-10-26
/// after the 98 + 144 case body-digest census); `0`/`off` disables it.
pub(super) fn pierce_cull_enabled() -> bool {
    switch!("BREP_IMPRINT_PIERCE_CULL", true)
}


thread_local! {
    pub(super) static PIERCE_CULLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Edges whose pierce solve the pierce cull skipped on this thread since the last call.
pub(super) fn take_pierce_culls() -> u64 {
    PIERCE_CULLS.with(|count| count.replace(0))
}

/// `BREP_IMPRINT_EXCHANGE_HULL` (lane P3b row 7, 2026-10-27): in
/// [`ImprintBuilder::exchange_piece_endpoint_junctions`], a piece whose
/// control hull is clear of a ridden edge's control hull by more than the
/// overlap limit cannot ride it (no station is within the limit), and a
/// station outside that expanded hull is off the edge without a projection.
/// On by default (promoted 2026-10-27); `0`/`off` disables it.
pub(super) fn exchange_hull_enabled() -> bool {
    switch!("BREP_IMPRINT_EXCHANGE_HULL", true)
}


thread_local! {
    static EXCHANGE_HULL_SKIPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Pieces and stations the exchange hull pre-gate answered without a projection on this thread since the last call.
pub(super) fn take_exchange_hull_skips() -> u64 {
    EXCHANGE_HULL_SKIPS.with(|count| count.replace(0))
}

/// MINTED-ONLY EDGE SPLITS (hosted reports 2026-11-02 "boolean fails": the
/// mug tree's branch union and the shelf pin's bracket union). `process_curve`
/// splits the operand edges a section crosses as it finds the crossings, on the
/// WHOLE section, before the sub-segments between the crossings are classified
/// against the trims. A sub-segment the trims reject (the full plane×cylinder
/// ellipse that enters the cylinder's trim for 5° and leaves it everywhere
/// else; the full generatrix line a bracket's floor cuts for 0.4 of a 7.4
/// cylinder) left its crossings behind as splits with no piece ending at them:
/// seven on the mug tree's cylinder seam, two on the shelf pin's far rim. A
/// split nothing ends at is a stray vertex, and it made an otherwise untouched
/// face (the pin's 0.01-wide cap annulus, no piece on it, far from the bracket)
/// a touched one that the fragmenter then lost. With this on, a crossing's
/// split is recorded only once a minted sub-segment ends at it (by section
/// parameter, or by point within the junction's own radius). Escape hatch
/// `BREP_IMPRINT_MINTED_SPLITS=0|off` restores the eager splits.
pub(super) fn minted_splits_enabled() -> bool {
    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    let enabled = *ON.get_or_init(|| !matches!(std::env::var("BREP_IMPRINT_MINTED_SPLITS").as_deref(), Ok("0") | Ok("off")));
    enabled
}


/// An operand-edge split `process_curve` found on the whole section, held
/// until a minted sub-segment claims it (see [`minted_splits_enabled`]).
struct PendingSplit<'a> {
    operand: u8,
    edge: &'a EdgeRecord,
    edge_parameter: f64,
    /// Where on the section the crossing sits.
    curve_parameter: f64,
    /// The crossing's point (the junction it snapped to, when it did).
    point: Vec3,
}

/// Whether the pierce recovery projects each pierce onto the section once
/// and reuses the reading (2026-11-05): ON unless
/// `BREP_PIERCE_PROJECTION_CACHE=0`.
pub(super) fn pierce_projection_cache_enabled() -> bool {
    switch!("BREP_PIERCE_PROJECTION_CACHE", true)
}

pub(super) fn hull_cull_enabled() -> bool {
    switch!("BREP_IMPRINT_HULL_CULL", true)
}


thread_local! {
    /// Edges the hull cull skipped since the last [`take_hull_culls`].
    pub(super) static HULL_CULLS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}

pub(super) fn take_hull_culls() -> u64 {
    HULL_CULLS.with(|count| count.replace(0))
}

pub(super) fn push_edge_split(
    parameters: &mut Vec<f64>,
    edge: &EdgeRecord,
    parameter: f64,
    model_tolerance: f64,
    weld_cap: f64,
) -> Result<(), KernelRefusal> {
    let span = edge.t1 - edge.t0;
    // `weld_cap` (B1″ of the feature-scale design; infinite unless
    // `BREP_FEATURE_SCALE_IMPRINT`) keeps a split a sliver's width from the
    // edge's end apart from that end.
    let weld_distance = assembler_weld(model_tolerance).min(weld_cap);
    let tolerance = (KNOT_IDENTITY_TOL * span).max(parameter_tolerance(
        &edge.curve,
        parameter,
        weld_distance,
    )?);
    if parameter <= edge.t0 + tolerance || parameter >= edge.t1 - tolerance {
        return Ok(());
    }
    if !parameters
        .iter()
        .any(|existing| (*existing - parameter).abs() <= tolerance)
    {
        parameters.push(parameter);
    }
    Ok(())
}

pub(super) struct ImprintBuilder<'a> {
    pub(super) open_carriers: bool,
    pub(super) edges: HashMap<(u8, u64), &'a EdgeRecord>,
    pub(super) tolerance: f64,
    /// Combined bbox extent of the two operands ([`solid_scale`]); the merge
    /// bands scale with part SIZE via [`merge_scale`], not distance from origin.
    pub(super) scale: f64,
    pub(super) vertices: Vec<ImprintVertex>,
    pub(super) vertex_radii: HashMap<u64, f64>,
    /// What minted each vertex: an operand edge's crossing or pierce, or
    /// a section end polished onto its two carriers. The lowest
    /// dimension any mint reported wins.
    pub(super) vertex_sources: HashMap<u64, JunctionSource>,
    pub(super) pieces: Vec<ImprintPieceRecord>,
    pub(super) by_face: HashMap<FaceKey, Vec<u64>>,
    pub(super) edge_splits: HashMap<(u8, u64), Vec<f64>>,
    pub(super) barrier_edges: HashSet<(u8, u64)>,
    /// Operand edges some section curve geometrically RODE (the overlap
    /// branch of `process_curve`): candidates for the PIECE-ENDPOINT
    /// post-pass (`exchange_piece_endpoint_junctions`). Deliberately a
    /// separate set from `barrier_edges` (same writer today) so the two
    /// mechanisms cannot silently couple if either gains another writer.
    pub(super) overlap_ridden_edges: HashSet<(u8, u64)>,
    /// Ids of the pieces minted from a MARCHED run (fitted from the marcher's
    /// polyline), as opposed to an analytic, planar-iso or boundary-copy
    /// curve. Only these are candidates for `dissolve_section_origin_vertices`:
    /// an exact analytic ring's origin split is the coalescer's exact-band
    /// closure, and dissolving it moved an offset shell's corners (see there).
    pub(super) marched_pieces: HashSet<u64>,
    /// Set by the driver around an EXACT section's `process_curve` (an
    /// analytic lane's line, circle or ellipse): with
    /// `BREP_EXACT_TANGENT_TOUCH`, its tangential hits on an edge it touches in
    /// passing are junctions, not grazes. See TANGENT TOUCH in `process_curve`.
    pub(super) exact_section: bool,
    /// The operands' local feature sizes (`BREP_FEATURE_SCALE_IMPRINT`; empty
    /// without it): see `crate::feature_scale`.
    pub(super) feature_scale: crate::feature_scale::FeatureScale,
    /// `(piece id, face)` of every pcurve the Hermite lane EMITTED rather
    /// than fitted: the junction passes move its ends instead of re-marching
    /// it, and the coincident merge re-keys it to the keeper.
    pub(super) emitted_pcurves: HashSet<(u64, FaceKey)>,
    /// Slice 1's `check` mode (`BREP_EXACT_ISO_PCURVES=check`): a pcurve
    /// handed in exactly is built beside the fitted one, the two are compared
    /// in 3-D on the face's chart and one census line is appended
    /// (`BREP_EXACT_ISO_CENSUS=<file>`), and the FITTED one is kept, so the
    /// record is the default lane's to the byte.
    pub(super) exact_pcurve_check: bool,
    pub(super) next_id: u64,
}

/// `BREP_EXACT_ISO_CENSUS=<file>`: one line per checked pcurve, appended;
/// `BREP_CENSUS_LABEL` names the run on every line.
fn exact_iso_census(line: impl FnOnce() -> String) {
    if let Ok(path) = std::env::var("BREP_EXACT_ISO_CENSUS") {
        use std::io::Write;
        let label = std::env::var("BREP_CENSUS_LABEL").unwrap_or_default();
        if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
            let _ = writeln!(file, "exact-iso census: label={label} {}", line());
        }
    }
}

/// Largest 3-D distance over `samples` fractions of the piece's domain
/// between the chart images of two pcurves, and of each from the curve.
/// Each pcurve is read at the same FRACTION of its own domain (a fitted
/// pcurve lives on `[0, 1]`, an exact one on the curve's knots); a
/// parameter past a closed direction's domain is read a period in (the
/// loops are drawn in a band), an open one clamped as the chart would.
/// Returns the three distances and the curve parameter of the largest of
/// the first.
fn pcurve_images_apart(
    chart: &NurbsSurface,
    curve: &NurbsCurve,
    fitted: &NurbsCurve,
    exact: &NurbsCurve,
    samples: usize,
) -> Result<([f64; 3], f64), String> {
    let [t0, t1] = curve.domain()?;
    let (closed_u, closed_v) = chart.closed_directions()?;
    let (du, dv) = (chart.domain_u()?, chart.domain_v()?);
    let wrap = |value: f64, closed: bool, domain: [f64; 2]| -> f64 {
        let period = domain[1] - domain[0];
        if closed && period > 0.0 {
            domain[0] + (value - domain[0]).rem_euclid(period)
        } else {
            value.clamp(domain[0], domain[1])
        }
    };
    let [f0, f1] = fitted.domain()?;
    let [e0, e1] = exact.domain()?;
    let mut apart = [0.0_f64; 3];
    let mut worst_t = t0;
    for k in 0..=samples {
        let fraction = k as f64 / samples as f64;
        let t = t0 + (t1 - t0) * fraction;
        let on_curve = curve.evaluate(t)?;
        let a = fitted.evaluate(f0 + (f1 - f0) * fraction)?;
        let b = exact.evaluate(e0 + (e1 - e0) * fraction)?;
        let image_a = chart.evaluate(wrap(a.x, closed_u, du), wrap(a.y, closed_v, dv))?;
        let image_b = chart.evaluate(wrap(b.x, closed_u, du), wrap(b.y, closed_v, dv))?;
        let between = image_a.sub(image_b).length();
        if between > apart[0] {
            apart[0] = between;
            worst_t = t;
        }
        apart[1] = apart[1].max(image_a.sub(on_curve).length());
        apart[2] = apart[2].max(image_b.sub(on_curve).length());
    }
    Ok((apart, worst_t))
}

fn pole_split_enabled() -> bool {
    crate::switch!("BREP_SECTION_POLE_SPLIT", true)
}

impl<'a> ImprintBuilder<'a> {
    fn vertex(&mut self, point: Vec3, merge_radius: f64) -> (u64, Vec3) {
        self.vertex_apart_from(point, merge_radius, None)
    }

    /// Both ends of one section through the registry. SECTION ENDS DISTINCT
    /// (`BREP_IMPRINT_SECTION_ENDS_DISTINCT`, default off; lane O's 705
    /// hand-off, 2026-11-03): a registry radius GROWS with every merge, so a
    /// junction whose fuzzy pierce left a radius of a few 1e-3 can later take
    /// BOTH ends of a genuinely distinct short section (the offset band across
    /// the 705 cap skin: its start merges 6.308e-3 into the vertex a wall
    /// skin's section left at its end with radius 7.570e-3, its end lands on
    /// that vertex), which then reads as a loopback and yields no piece. With
    /// the switch, when both ends take one vertex while lying farther apart
    /// than the base radius and their own fuzzy radii, the end farther from
    /// that vertex is resolved again without it: a grown radius may absorb a
    /// near-duplicate of its junction, not the other end of a section this
    /// pair separates from it. Every other merge is as before.
    fn section_vertices(&mut self, start: Vec3, start_radius: f64, end: Vec3, end_radius: f64) -> ((u64, Vec3), (u64, Vec3)) {
        let first = self.vertex(start, start_radius);
        let second = self.vertex(end, end_radius);
        if first.0 != second.0 || !switch!(live "BREP_IMPRINT_SECTION_ENDS_DISTINCT", false) {
            return (first, second);
        }
        let base = self.tolerance * 10.0 * merge_scale(self.scale);
        if start.sub(end).length() <= base.max(start_radius).max(end_radius) {
            return (first, second);
        }
        let Some(shared) = self.vertices.iter().find(|vertex| vertex.id == first.0).map(|vertex| vertex.point) else {
            return (first, second);
        };
        if start.sub(shared).length() >= end.sub(shared).length() {
            (self.vertex_apart_from(start, start_radius, Some(first.0)), second)
        } else {
            (first, self.vertex_apart_from(end, end_radius, Some(first.0)))
        }
    }

    fn vertex_apart_from(&mut self, point: Vec3, merge_radius: f64, apart_from: Option<u64>) -> (u64, Vec3) {
        let base = self.tolerance * 10.0 * merge_scale(self.scale);
        // FEATURE SCALE B1 (`BREP_FEATURE_SCALE_IMPRINT`, default on, `=0` off): the
        // registry's bands (1.8e-5 base, 2e-5 fuzzy radii on a 10 mm part)
        // reach past a feature far thinner than the part: the hairline saw's
        // two walls 1e-6 apart minted one vertex per corner. Beside such a
        // feature every band is capped at a quarter of it.
        let cap = if self.feature_scale.is_empty() {
            f64::INFINITY
        } else {
            self.feature_scale.cap(point, base.max(merge_radius))
        };
        let (base, merge_radius) = (base.min(cap), merge_radius.min(cap));
        for vertex in &self.vertices {
            let existing_radius = self.vertex_radii.get(&vertex.id).copied().unwrap_or(0.0).min(cap);
            let distance = vertex.point.sub(point).length();
            if apart_from == Some(vertex.id) && distance > base.max(merge_radius) {
                continue;
            }
            if distance <= base.max(existing_radius).max(merge_radius) {
                if distance > self.tolerance && env_read!("BREP_DEBUG_PROCESS_CURVE").is_some() {
                    eprintln!(
                        "vertex: MERGE v{} dist={distance:.3e} base={base:.3e} existing_radius={existing_radius:.3e} merge_radius={merge_radius:.3e} at=({:.7},{:.7},{:.7}) -> ({:.7},{:.7},{:.7})",
                        vertex.id, point.x, point.y, point.z, vertex.point.x, vertex.point.y, vertex.point.z
                    );
                }
                self.vertex_radii
                    .insert(vertex.id, existing_radius.max(merge_radius));
                // The registry point is canonical.  Returning the caller's
                // near-duplicate here would give one topological vertex ID
                // several geometric positions on its incident curves.
                return (
                    vertex.id,
                    if distance <= base {
                        vertex.point
                    } else {
                        point
                    },
                );
            }
            // A broad fuzzy radius nominates a possible joint, but must not
            // collapse visibly distinct curve endpoints into one vertex.  The
            // caller's fuzzy-junction pass writes the same refined point into
            // both candidates when the joint is genuine.
        }
        let id = self.next_id;
        self.next_id += 1;
        self.vertices.push(ImprintVertex { id, point });
        self.vertex_radii.insert(id, merge_radius);
        (id, point)
    }

    pub(super) fn add_edge_split(
        &mut self,
        operand: u8,
        edge: &EdgeRecord,
        parameter: f64,
    ) -> Result<(), KernelRefusal> {
        let tolerance = self.tolerance;
        // FEATURE SCALE B1″ (`BREP_FEATURE_SCALE_IMPRINT`, default on, `=0` off): the
        // endpoint guard reaches the assembler weld (1e-5) from the edge's
        // ends; beside a sliver that is wider than the sliver itself (the
        // wedge's corner edges split 5e-6 below the cube's top), so it is
        // capped at the sliver's scale there.
        let weld_cap = if self.feature_scale.is_empty() {
            f64::INFINITY
        } else {
            let point = edge.curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
            self.feature_scale.cap(point, assembler_weld(tolerance))
        };
        push_edge_split(
            self.edge_splits.entry((operand, edge.id)).or_default(),
            edge,
            parameter,
            tolerance,
            weld_cap,
        )
    }

    /// OVERLAP-JUNCTION EXCHANGE, PIECE-ENDPOINT POST-PASS (rotated
    /// equator-tangency, cardinal-sphere sub-configuration): the per-call
    /// exchange in `process_curve` can only imprint junctions IT sees onto
    /// edges IT sees — but the seam-crossing junction of a section riding
    /// an operand ring can be minted by a boundary-copy call whose
    /// `split_faces` exclude the ring, while the analytic call that DOES
    /// ride the ring carries that same junction at its closed curve's
    /// parameterization origin (param 0/1), where the endpoint guards
    /// suppress it (`perpendicular(cap_normal)` derives the analytic
    /// circle's origin, which lands exactly on the sphere seam for cardinal
    /// sphere axes). No single call ever holds both halves, so the ring
    /// stays one CLOSED record against two OPEN arc pieces — the one-use
    /// S=2 genus=1 signature. This post-pass runs once ALL calls have
    /// minted their pieces: every endpoint of an OPEN piece that RIDES an
    /// overlap-ridden edge, and that is a real junction (referenced by ≥ 2
    /// piece-endpoint slots — a marched curve's deliberate slack end is
    /// degree 1 and must NOT imprint; see the `!refine` guard in the
    /// overlap branch), is imprinted onto that edge via `add_edge_split`
    /// (which keeps the near-endpoint and dedup guards — a junction already
    /// at the ring's own vertex is correctly rejected there). Escape
    /// hatches: `BREP_OVERLAP_PIECE_ENDPOINT_SPLIT=0` (this pass) or the
    /// family hatch `BREP_OVERLAP_JUNCTION_SPLIT=0` (whole exchange).
    pub(super) fn exchange_piece_endpoint_junctions(&mut self) -> Result<(), KernelRefusal> {
        if env_read!("BREP_OVERLAP_JUNCTION_SPLIT").as_deref() == Some("0")
            || std::env::var("BREP_OVERLAP_PIECE_ENDPOINT_SPLIT").as_deref() == Ok("0")
        {
            return Ok(());
        }
        if self.overlap_ridden_edges.is_empty() || self.pieces.is_empty() {
            return Ok(());
        }
        let overlap_limit = self.tolerance.max(1e-5);
        let mut endpoint_degree: HashMap<u64, usize> = HashMap::default();
        for piece in &self.pieces {
            *endpoint_degree.entry(piece.start_vertex_id).or_insert(0) += 1;
            *endpoint_degree.entry(piece.end_vertex_id).or_insert(0) += 1;
        }
        let mut ridden: Vec<(u8, u64)> = self.overlap_ridden_edges.iter().copied().collect();
        ridden.sort_unstable();
        let debug = std::env::var("BREP_DEBUG_BOOL").is_ok();
        let stats = std::env::var("BREP_ROT2_STATS").is_ok();
        // web_time::Instant (imported above), NOT std::time::Instant — std's clock
        // is unimplemented on wasm32-unknown-unknown and Instant::now() ABORTS there
        // ("RuntimeError: unreachable"). This pass runs on knife-edge tangency booleans
        // (overlap_ridden_edges non-empty), so a raw std::time call here traps the whole
        // cyl×sphere union in the browser while passing natively. See lib.rs boolean path.
        let t_start = Instant::now();
        let mut ride_tests = 0usize;
        let mut planned: Vec<(u8, &EdgeRecord, f64)> = Vec::new();
        for &(operand, edge_id) in &ridden {
            let Some(&edge) = self.edges.get(&(operand, edge_id)) else {
                continue;
            };
            if edge.degenerate {
                continue;
            }
            let low = edge.t0.min(edge.t1);
            let high = edge.t0.max(edge.t1);
            // HULL PRE-GATE (`BREP_IMPRINT_EXCHANGE_HULL`): the edge's control
            // hull expanded by the overlap limit holds every point within the
            // limit of the edge; a piece whose control hull misses it has no
            // station on the edge (`on` would read 0), and a station outside
            // it is off without being projected. The counts are unchanged.
            let edge_hull = if exchange_hull_enabled() {
                edge.curve.control_points.iter().map(|control| control.point()).collect::<Result<Vec<_>, _>>().ok()
                    .map(|points| crate::spatial::Aabb::from_points(points).expanded(overlap_limit))
            } else {
                None
            };
            for piece in &self.pieces {
                // Open pieces only: a CLOSED piece riding a closed ring is
                // the shared-section RING reuse's territory; splitting the
                // ring at its origin would recreate the closed-vs-open
                // mismatch this pass exists to remove.
                if piece.start_vertex_id == piece.end_vertex_id || !(piece.t1 > piece.t0) {
                    continue;
                }
                // Ride test over the piece's LIVE window (records may carry
                // a window narrower than the curve's domain).
                if let Some(hull) = &edge_hull {
                    let apart = piece.curve.control_points.iter().map(|control| control.point()).collect::<Result<Vec<_>, _>>().ok()
                        .is_some_and(|points| !hull.intersects(crate::spatial::Aabb::from_points(points), 0.0));
                    if apart {
                        EXCHANGE_HULL_SKIPS.with(|count| count.set(count.get() + 1));
                        continue;
                    }
                }
                ride_tests += 1;
                let mut on = 0usize;
                for fraction in [0.1, 0.3, 0.5, 0.7, 0.9] {
                    let t = piece.t0 + (piece.t1 - piece.t0) * fraction;
                    let point = piece.curve.evaluate(t).or_refuse(KernelStage::Intersect, "evaluate")?;
                    if let Some(hull) = &edge_hull {
                        if !hull.contains(point) {
                            EXCHANGE_HULL_SKIPS.with(|count| count.set(count.get() + 1));
                            continue;
                        }
                    }
                    let projection = project_point_to_curve(&edge.curve, point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
                    let nearest = edge.curve.evaluate(projection.u.clamp(low, high)).or_refuse(KernelStage::Intersect, "evaluate")?;
                    if nearest.sub(point).length() <= overlap_limit {
                        on += 1;
                    }
                }
                if on < 3 {
                    continue;
                }
                for (t, vertex_id) in [
                    (piece.t0, piece.start_vertex_id),
                    (piece.t1, piece.end_vertex_id),
                ] {
                    if endpoint_degree.get(&vertex_id).copied().unwrap_or(0) < 2 {
                        continue;
                    }
                    let point = piece.curve.evaluate(t).or_refuse(KernelStage::Intersect, "evaluate")?;
                    let projection = project_point_to_curve(&edge.curve, point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
                    let nearest = edge.curve.evaluate(projection.u.clamp(low, high)).or_refuse(KernelStage::Intersect, "evaluate")?;
                    if nearest.sub(point).length() <= overlap_limit {
                        if debug {
                            eprintln!(
                                "piece-endpoint exchange: piece {} vertex {} \
                                 -> op={operand} edge={edge_id} u={:.6}",
                                piece.id, vertex_id, projection.u
                            );
                        }
                        planned.push((operand, edge, projection.u));
                    }
                }
            }
        }
        if stats {
            eprintln!(
                "ROT2_STATS: ridden_edges={} pieces={} ride_tests={} planned={} post_pass_ms={:.1}",
                ridden.len(),
                self.pieces.len(),
                ride_tests,
                planned.len(),
                t_start.elapsed().as_secs_f64() * 1000.0
            );
        }
        for (operand, edge, parameter) in planned {
            self.add_edge_split(operand, edge, parameter)?;
        }
        Ok(())
    }

    /// Whether a section point classified `Boundary` on an open offset sheet
    /// truly rides that sheet, rather than projecting onto its rim from off
    /// the patch. A rational conic carrier (a quarter-arc fillet's offset)
    /// continues around its whole circle past its domain, so the march can
    /// trace the full closed section; the far half then projects, clamped,
    /// onto the patch's rim and reads `Boundary`. Measured on the 2026-11-06
    /// offset-shell report (a box with four r5 fillets on one
    /// face, shelled 0.1 through the opposite face): the tilted bottom
    /// plane's section with the NX|NY fillet's offset kept its far half,
    /// 4.9 off the fillet, as a one-sided cut on the bottom sheet, which
    /// left three one-use edges and an open loop. A riding section lies on
    /// the sheet to its fit contract (`intersection_fit`, 20 × tolerance =
    /// 2e-6 there); the band is the wider of the march's own default seed
    /// gate (`intersect_surfaces`: 100 × tolerance) and 1e-4 of the part
    /// (3.5e-3 there), so a fitted curve's fallback noise stays inside it
    /// while a section wrapped around a conic (5 to 7 off there) does not.
    /// `BREP_IMPRINT_RECOVER_ON_SHEET=0` restores the unchecked recovery.
    fn rides_sheet_surface(&self, face: TaggedFace<'_>, point: Vec3) -> Result<bool, KernelRefusal> {
        if !switch!("BREP_IMPRINT_RECOVER_ON_SHEET", true) {
            return Ok(true);
        }
        let projection = project_point_to_surface(&face.face.surface, point)
            .or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
        Ok(projection.distance <= (self.tolerance * 100.0).max(self.scale * 1e-4))
    }

    fn face_has_seam_at(&self, face: TaggedFace<'_>, point: Vec3) -> Result<bool, KernelRefusal> {
        let mut counts = HashMap::default();
        for coedge in face
            .face
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
        {
            *counts.entry(coedge.edge_id).or_insert(0usize) += 1;
        }
        let tolerance = WELD_FLOOR * merge_scale(self.scale);
        for (edge_id, count) in counts {
            let edge = self.edges[&(face.operand, edge_id)];
            if count >= 2
                && !edge.degenerate
                && project_point_to_curve(&edge.curve, point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?.distance <= tolerance
            {
                return Ok(true);
            }
        }
        Ok(false)
    }

    fn polish_endpoint(
        &self,
        point: Vec3,
        first: &NurbsSurface,
        second: &NurbsSurface,
    ) -> Result<Vec3, KernelRefusal> {
        let threshold = (self.tolerance * 100.0).max(1e-6);
        let original = project_point_to_surface(first, point).or_refuse(KernelStage::Intersect, "project_point_to_surface")?
            .distance
            .max(project_point_to_surface(second, point).or_refuse(KernelStage::Intersect, "project_point_to_surface")?.distance);
        if original <= threshold {
            return Ok(point);
        }
        let mut current = point;
        let mut best = point;
        let mut best_residual = original;
        for _ in 0..30 {
            let on_first = project_point_to_surface(first, current).or_refuse(KernelStage::Intersect, "project_point_to_surface")?.point;
            let on_second = project_point_to_surface(second, on_first).or_refuse(KernelStage::Intersect, "project_point_to_surface")?.point;
            let back = project_point_to_surface(first, on_second).or_refuse(KernelStage::Intersect, "project_point_to_surface")?.point;
            let candidate = back.add(on_second).scale(0.5);
            let residual = project_point_to_surface(first, candidate).or_refuse(KernelStage::Intersect, "project_point_to_surface")?
                .distance
                .max(project_point_to_surface(second, candidate).or_refuse(KernelStage::Intersect, "project_point_to_surface")?.distance);
            if residual < best_residual {
                best = candidate;
                best_residual = residual;
            }
            current = candidate;
            if residual <= (self.tolerance * 10.0).max(1e-7) {
                break;
            }
        }
        Ok(if best_residual <= threshold {
            best
        } else {
            point
        })
    }

    pub(super) fn process_curve(
        &mut self,
        curve: NurbsCurve,
        first: TaggedFace<'_>,
        second: TaggedFace<'_>,
        test_faces: &[TaggedFace<'_>],
        target_faces: &[TaggedFace<'_>],
        refine: bool,
        exact_pcurves: Option<[NurbsCurve; 2]>,
    ) -> Result<(), KernelRefusal> {
        super::work_profile::add(|c| c.sections += 1);
        let profile = profile_enabled();
        let began = profile.then(Instant::now);
        let mut split_parameters = Vec::new();
        let mut fuzzy_junctions: Vec<(Vec3, f64)> = Vec::new();
        // Operand edges the section curve geometrically RIDES (the overlap
        // branch below): junctions minted on the section must be exchanged
        // onto them once the full junction set is known — see the
        // OVERLAP-JUNCTION EXCHANGE after the split_parameters dedup.
        let mut overlapped_edges: Vec<(u8, &EdgeRecord)> = Vec::new();
        let minted_only = minted_splits_enabled();
        let mut pending_splits: Vec<PendingSplit<'a>> = Vec::new();
        let [whole_start, whole_end] = curve.domain().or_refuse(KernelStage::Intersect, "domain")?;
        // Anything finer than the assembler's weld tolerance cannot survive
        // as distinct topology, so that is the meaningful noise floor for
        // overlap detection (marched curves wiggle a few 1e-6 around the
        // exact curve and every wiggle would otherwise count as a crossing).
        let overlap_limit = self.tolerance.max(1e-5);
        let distinct_pierces_on_section =
            env_read!("BREP_PIERCE_DISTINCT_ON_SECTION").as_deref() != Some("0");
        // Crossings this close to the curve's own endpoints are the
        // endpoint junction itself seen through the finders' spatial
        // tolerance: splitting there leaves a sliver piece whose surviving
        // half evaluates measurably off the true corner (§4.13 — the
        // parametric guard below is far tighter than the finders' 1e-5).
        let whole_start_point = curve.evaluate(whole_start).or_refuse(KernelStage::Intersect, "evaluate")?;
        let whole_end_point = curve.evaluate(whole_end).or_refuse(KernelStage::Intersect, "evaluate")?;
        let near_curve_end = |point: Vec3| {
            point.sub(whole_start_point).length() <= overlap_limit
                || point.sub(whole_end_point).length() <= overlap_limit
        };
        let split_faces = if refine {
            vec![first, second]
        } else {
            target_faces.to_vec()
        };
        // HULL CULL (`BREP_IMPRINT_HULL_CULL`, lane X): a boundary edge whose
        // control hull stays farther than the overlap and crossing bands from
        // the section's can neither be ridden by it nor crossed by it (a NURBS
        // curve lies in its control hull), so the overlap test and the curve
        // crossing are skipped for it; its exact pierces still run.
        let hull_cull = hull_cull_enabled();
        let hull_band = overlap_limit.max(1e-5) * 4.0;
        let control_hull = |nurbs: &NurbsCurve| -> Option<crate::spatial::Aabb> {
            let points = nurbs.control_points.iter().map(|control| control.point()).collect::<Result<Vec<_>, _>>().ok()?;
            Some(crate::spatial::Aabb::from_points(points))
        };
        let curve_hull = if hull_cull { control_hull(&curve) } else { None };
        // PIERCE CULL (`BREP_IMPRINT_PIERCE_CULL`, lane P3b row 1). Every use of
        // an edge's pierce set below is local to that edge and bounded in
        // distance from the section: a pierce is a fuzzy-junction candidate
        // only within `4e-3 * (1 + |hit|)` of a curve hit ON the section, is
        // recovered as a cut only when it projects onto the section within
        // `2e-3 * (1 + |pierce|)` (the station rescue re-reads the same bar),
        // and the ambiguity read compares pierces of the SAME edge. So an edge
        // whose control hull is separated from the section's control hull by
        // more than `4e-3 * (1 + the farthest corner of either hull)` — every
        // point of the edge is in its hull, every point of the section in its —
        // can contribute nothing, and its curve/carrier solve is skipped
        // outright. The overlap test and the curve crossing are untouched.
        let pierce_cull = refine && pierce_cull_enabled();
        let pierce_hull = if pierce_cull && curve_hull.is_none() { control_hull(&curve) } else { None };
        let section_hull = curve_hull.or(pierce_hull);
        let farthest_corner = |hull: &crate::spatial::Aabb| -> f64 {
            hull.minimum.length().max(hull.maximum.length())
                .max(Vec3::new(hull.minimum.x, hull.minimum.y, hull.maximum.z).length())
                .max(Vec3::new(hull.minimum.x, hull.maximum.y, hull.minimum.z).length())
                .max(Vec3::new(hull.minimum.x, hull.maximum.y, hull.maximum.z).length())
                .max(Vec3::new(hull.maximum.x, hull.minimum.y, hull.minimum.z).length())
                .max(Vec3::new(hull.maximum.x, hull.minimum.y, hull.maximum.z).length())
                .max(Vec3::new(hull.maximum.x, hull.maximum.y, hull.minimum.z).length())
        };
        for face in split_faces {
            let other = if face.key() == first.key() {
                second
            } else {
                first
            };
            for edge in face_edges(face, &self.edges)? {
                if edge.degenerate {
                    // POLE SPLIT (2026-11-06;
                    // `BREP_SECTION_POLE_SPLIT`, default on, `=0` off). A section through
                    // a face's pole meets no edge there that has length: the
                    // pole is a degenerate edge, which no crossing or pierce
                    // reads. Two balls meeting through a pole of each
                    // (brep-bench `singular/balls-meeting-through-a-pole`): the
                    // exact circle starts at the first ball's pole and passes
                    // the second's at t = 0.5, so the whole circle stayed one
                    // piece, its midpoint read Boundary on the second ball and
                    // the piece was never attached there; the second ball was
                    // kept whole. Splitting the section at the pole gives each
                    // half an end on the pole row and a regular midpoint.
                    if pole_split_enabled() {
                        let pole = edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Intersect, "evaluate")?;
                        let projection = project_point_to_curve(&curve, pole)
                            .or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
                        if projection.distance <= overlap_limit
                            && projection.u > whole_start + 1e-7
                            && projection.u < whole_end - 1e-7
                            && !near_curve_end(pole)
                            && !split_parameters
                                .iter()
                                .any(|value: &f64| (*value - projection.u).abs() <= 1e-6)
                        {
                            split_parameters.push(projection.u);
                        }
                    }
                    continue;
                }
                // Propagate failures: a swallowed error here silently drops
                // junction splits and corrupts topology far downstream.
                let solve_pierces = |builder: &Self| -> Result<Vec<crate::CurveSurfaceIntersection>, KernelRefusal> {
                    let started = profile.then(Instant::now);
                    let pierces = intersect_curve_surface(
                        &edge.curve,
                        &other.face.surface,
                        builder.tolerance.max(1e-9),
                    )
                    .map_err(|error| {
                        format!("imprint pierce recovery on edge {}: {error}", edge.id)
                    }).or_refuse(KernelStage::Intersect, "csg.imprint.builder")?;
                    if let Some(started) = started {
                        let elapsed = started.elapsed();
                        imprint_split_add(|split| { split.pierce += elapsed; split.pierce_edges += 1; });
                    }
                    Ok(pierces)
                };
                let pierce_apart = match (&section_hull, pierce_cull) {
                    (Some(hull), true) => control_hull(&edge.curve).is_some_and(|edge_hull| {
                        let band = 4e-3 * (1.0 + farthest_corner(hull).max(farthest_corner(&edge_hull)));
                        !hull.intersects(edge_hull, band)
                    }),
                    _ => false,
                };
                if pierce_apart {
                    PIERCE_CULLS.with(|count| count.set(count.get() + 1));
                }
                // Switch off: the production order, the solve before the overlap test.
                let mut pierces = if refine && !pierce_cull { solve_pierces(self)? } else { Vec::new() };
                // A (near-)coincident overlap must exchange ENDPOINTS only:
                // intersect_curves between overlapping curves reports
                // spurious subdivision hits along the whole shared span,
                // spraying micro edge-splits (glue unions copy each face's
                // edges onto the other and then hit-test them against their
                // own coincident twins).
                let apart = match (&curve_hull, hull_cull) {
                    (Some(hull), true) => control_hull(&edge.curve).is_some_and(|edge_hull| !hull.intersects(edge_hull, hull_band)),
                    _ => false,
                };
                if apart {
                    HULL_CULLS.with(|count| count.set(count.get() + 1));
                }
                let split_clock = profile.then(Instant::now);
                let overlaps = !apart && curve_overlaps_edge(&curve, edge, overlap_limit)?;
                if let Some(started) = split_clock {
                    let elapsed = started.elapsed();
                    imprint_split_add(|split| { split.overlap += elapsed; split.overlap_edges += (!apart) as u64; });
                }
                if overlaps {
                    self.barrier_edges.insert((face.operand, edge.id));
                    self.overlap_ridden_edges.insert((face.operand, edge.id));
                    overlapped_edges.push((face.operand, edge));
                    // Marched (refine) curves stop with deliberate slack past
                    // the trim boundary, so their endpoints are NOT junctions;
                    // exchanging them here plants off-by-a-band vertices on
                    // the overlapped edge. Exact-endpoint sources (cosurface
                    // boundary copies) still exchange.
                    if !refine {
                        for parameter in [whole_start, whole_end] {
                            let point = curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
                            let projection = project_point_to_curve(&edge.curve, point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
                            let nearest = edge.curve.evaluate(
                                projection
                                    .u
                                    .clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1)),
                            ).or_refuse(KernelStage::Intersect, "csg.imprint.builder")?;
                            if nearest.sub(point).length() <= overlap_limit {
                                pending_splits.push(PendingSplit {
                                    operand: face.operand,
                                    edge,
                                    edge_parameter: projection.u,
                                    curve_parameter: parameter,
                                    point,
                                });
                            }
                        }
                    }
                    for parameter in [edge.t0, edge.t1] {
                        let point = edge.curve.evaluate(parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
                        let projection = project_point_to_curve(&curve, point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
                        if projection.distance <= overlap_limit
                            && projection.u > whole_start + 1e-7
                            && projection.u < whole_end - 1e-7
                            && !split_parameters
                                .iter()
                                .any(|value: &f64| (*value - projection.u).abs() <= 1e-6)
                        {
                            split_parameters.push(projection.u);
                        }
                    }
                    continue;
                }
                // Switch on: the solve runs only here, past the overlap branch
                // that never reads it, and only for an edge the cull admits.
                if refine && pierce_cull && !pierce_apart {
                    pierces = solve_pierces(self)?;
                }
                let split_clock = profile.then(Instant::now);
                let curve_hits = if apart { Vec::new() } else { intersect_curves(&curve, &edge.curve, 1e-5).map_err(|error| {
                    format!("imprint curve-edge crossing on edge {}: {error}", edge.id)
                }).or_refuse(KernelStage::Intersect, "csg.imprint.builder")? };
                if let Some(started) = split_clock {
                    let elapsed = started.elapsed();
                    imprint_split_add(|split| { split.crossing += elapsed; split.crossing_edges += (!apart) as u64; });
                }
                for hit in curve_hits {
                    if hit.t < edge.t0 - 1e-9 || hit.t > edge.t1 + 1e-9 {
                        continue;
                    }
                    let mut curve_parameter = hit.s;
                    let mut edge_parameter = hit.t;
                    let mut fuzzy_junction = None;
                    if refine {
                        let hit_point = curve.evaluate(curve_parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
                        let search_radius = 4e-3 * (1.0 + hit_point.length());
                        let mut candidates = pierces
                            .iter()
                            .filter(|pierce| {
                                pierce.t >= edge.t0 - 1e-9 && pierce.t <= edge.t1 + 1e-9
                            })
                            .map(|pierce| (pierce, pierce.point.sub(hit_point).length()))
                            .collect::<Vec<_>>();
                        candidates.sort_by(|a, b| a.1.total_cmp(&b.1));
                        if let Some((best, best_distance)) = candidates.first() {
                            let second_distance = candidates
                                .get(1)
                                .map(|candidate| candidate.1)
                                .unwrap_or(f64::INFINITY);
                            if *best_distance <= search_radius
                                && *best_distance < 0.5 * second_distance
                            {
                                let projection = project_point_to_curve(&curve, best.point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
                                if projection.distance <= 2e-3 * (1.0 + best.point.length()) {
                                    curve_parameter = projection.u;
                                    edge_parameter = best.t;
                                    fuzzy_junction = Some((
                                        best.point,
                                        (2.0 * projection.distance).max(2e-5).min(1.5e-3),
                                    ));
                                }
                            }
                        }
                    }
                    // TANGENT HIT AT AN EDGE VERTEX (slab + end cylinder,
                    // hosted report 2026-10-03): a section tangent to an edge
                    // is located only to about sqrt(gap/κ) along it — the gap
                    // grows as s²/2R, so the finder's 1e-12 floor is 1.3e-5 of
                    // travel at R = 90 — and may stop just past the endpoint
                    // guard's weld band when the true contact IS the edge's own
                    // vertex (the cap circle touching the slab's height edges at
                    // their corners). Splitting there mints a sliver edge and a
                    // second vertex the arc's two copies then end on
                    // differently (open loops on both caps, eight one-use
                    // edges). An endpoint that lies on the section, with the
                    // edge hugging the section the whole way from the hit, is
                    // the junction the hit was reaching for: re-point the hit
                    // at it, and `push_edge_split`'s endpoint guard declines the
                    // split while the curve split lands on the vertex. The
                    // band is the imprint's own overlap floor, below which no
                    // distinct topology can survive; no weld band moved.
                    if hit.tangential {
                        // Edge side first: the edge's own vertex is the
                        // junction (the slab corner the cap circle touches).
                        // Then the section side: the section ends ON the edge
                        // (the slab's height edge copied onto the cylinder,
                        // touching the cap ring at the copy's own end) — the
                        // end-guard below then withholds the sliver curve split
                        // and the edge split lands where the real end projects.
                        if let Some((snapped_t, snapped_u)) = tangent_hit_endpoint(
                            &edge.curve,
                            edge.t0,
                            edge.t1,
                            edge_parameter,
                            &curve,
                            whole_start,
                            whole_end,
                            overlap_limit,
                        )? {
                            edge_parameter = snapped_t;
                            curve_parameter = snapped_u;
                            fuzzy_junction = None;
                        } else if let Some((snapped_s, snapped_t)) = tangent_hit_endpoint(
                            &curve,
                            whole_start,
                            whole_end,
                            curve_parameter,
                            &edge.curve,
                            edge.t0,
                            edge.t1,
                            overlap_limit,
                        )? {
                            curve_parameter = snapped_s;
                            edge_parameter = snapped_t;
                            fuzzy_junction = None;
                        }
                        if std::env::var("BREP_DEBUG_TANGENT_HIT").is_ok() {
                            eprintln!(
                                "tangent hit edge=({},{}) hit.t={:.9} hit.s={:.9} -> t={:.9} s={:.9}",
                                face.operand, edge.id, hit.t, hit.s, edge_parameter, curve_parameter
                            );
                        }
                    }
                    let [start, end] = curve.domain().or_refuse(KernelStage::Intersect, "domain")?;
                    let interior = curve_parameter > start + 1e-7
                        && curve_parameter < end - 1e-7
                        && !near_curve_end(curve.evaluate(curve_parameter).or_refuse(KernelStage::Intersect, "evaluate")?);
                    // A marched section that GRAZES an edge where it passes
                    // through is not a junction: the tangential hit is skipped. A
                    // section that ENDS on an edge ends at a junction whatever
                    // the angle, so an end hit splits the edge. The hit is an end
                    // hit when its junction (the pierce it snapped to, or the hit
                    // itself) lies at the section's endpoint, not merely when its
                    // parameter clamps there. A faithful fit reproduces a real
                    // tangency at such an end: the self-crossing repair's section
                    // on `FilletFailureWith2RasiusValues` runs along the bore's
                    // mouth ring at both ends (the carriers read sin 5.7e-10 and
                    // 2.0e-11), and skipping those hits left the ring whole.
                    let junction_point = match fuzzy_junction {
                        Some((point, _)) => point,
                        None => curve.evaluate(curve_parameter).or_refuse(KernelStage::Intersect, "evaluate")?,
                    };
                    let ends_on = !interior && near_curve_end(junction_point);
                    // TANGENT TOUCH (`BREP_EXACT_TANGENT_TOUCH`, default on): an
                    // EXACT section (an analytic lane's circle) that touches an
                    // edge in passing touches it at a true point: the plane's
                    // circle of a ball inscribed in a cube's edges touches each
                    // side of its square at the side's midpoint, where the
                    // neighbouring face's circle touches it too. Skipping the hit
                    // leaves the circle one piece whose midpoint reads On the
                    // boundary, so it is dropped (midsphere-common refused and was
                    // answered by perturbation). The touch is kept as a junction
                    // only where the curve and the edge meet to round-off.
                    let exact_touch = hit.tangential
                        && self.exact_section
                        && interior
                        && exact_tangent_touch_enabled()
                        && edge.curve.evaluate(edge_parameter).ok().is_some_and(|on_edge| {
                            on_edge.sub(junction_point).length() <= 1e-9 * (1.0 + junction_point.length())
                        })
                        // A TOUCH parts from the edge on either side (a circle
                        // leaves its tangent line as κδ²/2); a coincident span
                        // does not, and the curve/curve solve reports spurious
                        // "tangential" hits all along one (a split bore's rim
                        // arc read on its own circle at t = s = 0.1875, 0.3125,
                        // 0.4375), which must not become junctions.
                        && {
                            let step = 1e-3 * (end - start);
                            let band = 1e-7 * (1.0 + junction_point.length());
                            [curve_parameter - step, curve_parameter + step].iter().any(|&beside| {
                                let beside = beside.clamp(start, end);
                                curve.evaluate(beside).ok().and_then(|point| {
                                    project_point_to_curve(&edge.curve, point).ok().map(|foot| foot.distance > band)
                                }).unwrap_or(false)
                            })
                        };
                    // GRAZING CROSSING (`BREP_FEATURE_SCALE_GRAZING_CROSSING`,
                    // default on, `=0` off): "tangential" is decided by angle,
                    // but a section can cross an edge at an angle far below that
                    // and still leave the face there. brep-bench
                    // tangent/wedge-a-millionth-steep: the half-space's face
                    // crosses the cube's x = ±5 sides along z = 1e-6·y, which
                    // passes through the top edges at (±5, 0, 0); skipping that
                    // hit left the side section one 10-long piece, half of it
                    // above the top, and the piece read "invalid-boundary". A
                    // graze stays on one side of the edge; a crossing changes
                    // side. So a tangential interior hit on the edge to round-off
                    // is kept when the section's offsets from the edge 1e-3 of
                    // the domain either side point to opposite sides, each above
                    // round-off, however small. Straight section, straight edge
                    // only: two lines meet at one point and change side there
                    // exactly, while a curved section can change side of an edge
                    // it is tangent to through its curvature (a G1 elbow over its
                    // arm grew a face and an edge under this rule).
                    let straight = |nurbs: &NurbsCurve| nurbs.degree == 1 && nurbs.control_points.len() == 2;
                    let grazing_crossing = hit.tangential
                        && interior
                        && !exact_touch
                        && grazing_crossing_enabled()
                        && straight(&curve)
                        && straight(&edge.curve)
                        && edge.curve.evaluate(edge_parameter).ok().is_some_and(|on_edge| {
                            on_edge.sub(junction_point).length() <= 1e-9 * (1.0 + junction_point.length())
                        })
                        && {
                            let step = 1e-3 * (end - start);
                            let round_off = 1e-12 * (1.0 + junction_point.length());
                            let offset = |beside: f64| -> Option<Vec3> {
                                let point = curve.evaluate(beside.clamp(start, end)).ok()?;
                                let foot = project_point_to_curve(&edge.curve, point).ok()?;
                                let on_edge = edge.curve.evaluate(foot.u).ok()?;
                                let offset = point.sub(on_edge);
                                (offset.length() > round_off).then_some(offset)
                            };
                            match (offset(curve_parameter - step), offset(curve_parameter + step)) {
                                (Some(before), Some(after)) => before.dot(after) < 0.0,
                                _ => false,
                            }
                        };
                    if hit.tangential && refine && !ends_on && !exact_touch && !grazing_crossing {
                        continue;
                    }
                    if let Some(junction) = fuzzy_junction {
                        if env_read!("BREP_DEBUG_PROCESS_CURVE").is_some() {
                            eprintln!(
                                "process_curve[{:?}/{:?}]: FUZZY hit op={} edge={} at=({:.7},{:.7},{:.7}) radius={:.3e}",
                                first.key(), second.key(), face.operand, edge.id, junction.0.x, junction.0.y, junction.0.z, junction.1
                            );
                        }
                        fuzzy_junctions.push(junction);
                    }
                    pending_splits.push(PendingSplit {
                        operand: face.operand,
                        edge,
                        edge_parameter,
                        curve_parameter,
                        point: junction_point,
                    });
                    if interior
                        && !split_parameters
                            .iter()
                            .any(|value: &f64| (*value - curve_parameter).abs() <= 1e-6)
                    {
                        split_parameters.push(curve_parameter);
                    }
                }

                // A fitted SSI curve can miss a boundary curve by chord sag.
                // Exact edge/surface pierces recover those topological cuts.
                let split_clock = profile.then(Instant::now);
                if let Some(started) = split_clock {
                    let _ = started;
                    imprint_split_add(|split| split.recover_pierces += pierces.len() as u64);
                }
                if refine {
                    // PIERCE PROJECTION CACHE (2026-11-05): the projector is
                    // a pure function of the section and the point, and the
                    // ambiguity read below projects every pierce within
                    // `4e-3 * scale` of each pierce again. An edge that runs
                    // along the other carrier yields a dense cluster of
                    // pierces and the read went quadratic in projections (12
                    // s a boolean). Each pierce's projection is computed
                    // where it was first computed and reused after, so every
                    // reading is the one the projector returned. Escape
                    // hatch BREP_PIERCE_PROJECTION_CACHE=0.
                    let cache_projections = pierce_projection_cache_enabled();
                    let mut raw_projections: Vec<Option<crate::CurveProjection>> = vec![None; pierces.len()];
                    let mut project_pierce = |index: usize| -> Result<crate::CurveProjection, KernelRefusal> {
                        if let Some(projection) = raw_projections[index] {
                            return Ok(projection);
                        }
                        let projection = project_point_to_curve(&curve, pierces[index].point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
                        if cache_projections {
                            raw_projections[index] = Some(projection);
                        }
                        Ok(projection)
                    };
                    for (pierce_index, pierce) in pierces.iter().enumerate() {
                        if pierce.t < edge.t0 - 1e-9 || pierce.t > edge.t1 + 1e-9 {
                            continue;
                        }
                        let scale = 1.0 + pierce.point.length();
                        let mut projection = project_pierce(pierce_index)?;
                        if projection.distance > 2e-3 * scale {
                            // `project_point_to_curve`'s per-knot-span seed grid
                            // (4..deg+2 samples/span) + Newton can settle in the
                            // WRONG basin on a near-closed section curve, mapping
                            // an on-curve pierce onto the far endpoint: 00000170's
                            // box-plane × revolution-band corner grazes the band's
                            // v=1 rim in a shallow <0.2mm arc and re-enters at the
                            // exact edge×plane pierce P0 (on the section at
                            // t≈0.978), yet the projector returns t=0 (the section
                            // start, 0.86mm away) so this gate drops the split, the
                            // tiny on-band corner arc is never minted, the mating
                            // box face's loop cannot close and the band's own corner
                            // fragment strands the shared rim/seam edges one-use
                            // (pool t288). Locating the parameter of a point KNOWN
                            // to lie on the curve (both pierce finders put it there)
                            // is deterministic INVERSION, not a containment verdict,
                            // so a projector-free dense-sample-then-bracket rescue is
                            // sound here — and it runs ONLY on pierces the projector
                            // already rejected, re-verified against the SAME gate, so
                            // no currently-accepted split changes. Escape hatch
                            // BREP_PIERCE_PARAM_RESCUE=0.
                            if std::env::var("BREP_PIERCE_PARAM_RESCUE").as_deref() == Ok("0") {
                                continue;
                            }
                            let [c_start, c_end] = curve.domain().or_refuse(KernelStage::Intersect, "domain")?;
                            const RESCUE_STATIONS: usize = 512;
                            let mut best_u = c_start;
                            let mut best_d2 = f64::INFINITY;
                            for index in 0..=RESCUE_STATIONS {
                                let u = c_start
                                    + (c_end - c_start) * (index as f64) / (RESCUE_STATIONS as f64);
                                let d2 =
                                    curve.evaluate(u).or_refuse(KernelStage::Intersect, "evaluate")?.sub(pierce.point).length_squared();
                                if d2 < best_d2 {
                                    best_d2 = d2;
                                    best_u = u;
                                }
                            }
                            let step = (c_end - c_start) / (RESCUE_STATIONS as f64);
                            let mut lo = (best_u - step).max(c_start);
                            let mut hi = (best_u + step).min(c_end);
                            for _ in 0..64 {
                                let m1 = lo + (hi - lo) / 3.0;
                                let m2 = hi - (hi - lo) / 3.0;
                                let d1 =
                                    curve.evaluate(m1).or_refuse(KernelStage::Intersect, "evaluate")?.sub(pierce.point).length_squared();
                                let d2 =
                                    curve.evaluate(m2).or_refuse(KernelStage::Intersect, "evaluate")?.sub(pierce.point).length_squared();
                                if d1 < d2 {
                                    hi = m2;
                                } else {
                                    lo = m1;
                                }
                            }
                            let rescued_u = 0.5 * (lo + hi);
                            let rescued_point = curve.evaluate(rescued_u).or_refuse(KernelStage::Intersect, "evaluate")?;
                            let rescued_distance = rescued_point.sub(pierce.point).length();
                            if rescued_distance > 2e-3 * scale {
                                continue;
                            }
                            projection = crate::CurveProjection {
                                u: rescued_u,
                                point: rescued_point,
                                distance: rescued_distance,
                            };
                        }
                        // Two pierces near each other are AMBIGUOUS when the
                        // section cannot tell them apart — one of them lies off
                        // it and projects to the other's place. Two pierces that
                        // BOTH lie on the section, at places along it as far
                        // apart as the pierces themselves, are two junctions: a
                        // graze crossing an edge twice 0.107 apart, each pierce
                        // on the section to 2e-9 (`22_sag_boundary_identity_t164`,
                        // 2026-09-26), lost both to this rule and left the
                        // sphere face bounded by a rim arc 4.6e-4 off it.
                        // Read coincidence at the assembler's identity floor,
                        // not the section fit's requested residual: a fitted
                        // section can miss a real crossing by a few microns
                        // while the crossings remain well-separated vertices.
                        // Escape hatch BREP_PIERCE_DISTINCT_ON_SECTION=0.
                        let on_section = assembler_weld(self.tolerance);
                        let mut ambiguous = false;
                        for (other_index, other_pierce) in pierces.iter().enumerate() {
                            let apart = other_pierce.point.sub(pierce.point).length();
                            if other_index == pierce_index || apart > 4e-3 * scale {
                                continue;
                            }
                            let other_projection = project_pierce(other_index)?;
                            if distinct_pierces_on_section
                                && projection.distance <= on_section
                                && other_projection.distance <= on_section
                                && apart > overlap_limit
                                && projection.point.sub(other_projection.point).length() >= 0.5 * apart
                            {
                                continue;
                            }
                            if projection.distance >= 0.5 * other_projection.distance {
                                ambiguous = true;
                                break;
                            }
                        }
                        if ambiguous {
                            continue;
                        }
                        let curve_tangent = curve.derivatives(projection.u, 1).or_refuse(KernelStage::Intersect, "derivatives")?[1];
                        let edge_tangent = edge.curve.derivatives(pierce.t, 1).or_refuse(KernelStage::Intersect, "derivatives")?[1];
                        let parallel_scale = curve_tangent.length() * edge_tangent.length();
                        let [start, end] = curve.domain().or_refuse(KernelStage::Intersect, "domain")?;
                        let interior = projection.u > start + 1e-7
                            && projection.u < end - 1e-7
                            && !near_curve_end(curve.evaluate(projection.u).or_refuse(KernelStage::Intersect, "evaluate")?);
                        // The parallel skip is for a pierce the section passes
                        // THROUGH while running along the edge. A pierce the
                        // section ENDS on is a junction whatever the angle, the
                        // same rule as the tangential hit above: the edge is
                        // split and the piece boundary is a vertex. The pierce
                        // itself must lie at the endpoint: one past the end
                        // projects onto it too, and the section does not end
                        // there.
                        let ends_on = !interior && near_curve_end(pierce.point);
                        if !ends_on
                            && parallel_scale > 1e-12
                            && curve_tangent.cross(edge_tangent).length() <= 1e-3 * parallel_scale
                        {
                            continue;
                        }
                        pending_splits.push(PendingSplit {
                            operand: face.operand,
                            edge,
                            edge_parameter: pierce.t,
                            curve_parameter: projection.u,
                            point: pierce.point,
                        });
                        if interior
                            && !split_parameters
                                .iter()
                                .any(|value: &f64| (*value - projection.u).abs() <= 1e-6)
                        {
                            split_parameters.push(projection.u);
                        }
                        let pierce_radius = if interior {
                            (2.0 * projection.distance).max(2e-5).min(1.5e-3)
                        } else {
                            (1.2 * projection.distance).max(2e-5)
                        };
                        if env_read!("BREP_DEBUG_PROCESS_CURVE").is_some() {
                            eprintln!(
                                "process_curve[{:?}/{:?}]: FUZZY pierce op={} edge={} t={:.6} at=({:.7},{:.7},{:.7}) proj_dist={:.3e} proj_u={:.6} interior={interior} ends_on={ends_on} radius={pierce_radius:.3e}",
                                first.key(), second.key(), face.operand, edge.id, pierce.t, pierce.point.x, pierce.point.y, pierce.point.z, projection.distance, projection.u
                            );
                        }
                        fuzzy_junctions.push((pierce.point, pierce_radius));
                    }
                }
                if let Some(started) = split_clock {
                    let elapsed = started.elapsed();
                    imprint_split_add(|split| split.recover += elapsed);
                }
            }
        }
        // SECTION DOMAIN-EXIT SPLITS. A refine section on an ANALYTIC carrier
        // (plane×cylinder ellipse; the deg-(2,1) revolution "band" faces of
        // 00000170) can leave the carrier's PARAMETRIC domain in a non-closed
        // direction: the ellipse rises past the band's v=1 top, so a piece
        // straddling the boundary has an on-carrier midpoint but an endpoint
        // 12.5 mm off the surface — `build_pcurve_on_surface` then hard-errors
        // (pool trial 645). The section is on the carrier only within [0,1];
        // add a split exactly where it crosses the domain edge so the
        // on-carrier arc mints cleanly and the off-carrier tail is skipped by
        // the existing midpoint Outside gate. Detection is closed-form via
        // `AnalyticSurface::project` (whose clamped-projection distance is the
        // 3D gap once a coordinate leaves [0,1]) — NEVER the poisoned NURBS
        // projector — and every candidate is verified evaluate-vs-evaluate
        // before it is accepted. Planes self-clip through their real coplanar
        // trim edges, so they are excluded. A shallow graze that never leaves
        // the on-carrier band (max excursion below `out_tol`) is left
        // untouched: only a genuine deep exit, the class that errors today,
        // gets a split. Escape hatch `BREP_SECTION_DOMAIN_SPLIT=0`.
        if refine && std::env::var("BREP_SECTION_DOMAIN_SPLIT").as_deref() != Ok("0") {
            for face in [first, second] {
                let Some(analytic) = face.face.surface.analytic() else {
                    continue;
                };
                if matches!(analytic, crate::AnalyticSurface::Plane { .. }) {
                    continue;
                }
                // Local per-point tolerances: `in_tol` is the on-carrier band
                // (kept << build_pcurve's 1e-3·scale endpoint floor so a
                // clipped endpoint always passes); `out_tol` confirms a real
                // deep exit before any split is registered.
                let off_gap = |f: f64| -> Result<f64, KernelRefusal> {
                    let point = curve.evaluate(f).or_refuse(KernelStage::Intersect, "evaluate")?;
                    Ok(analytic
                        .project(&face.face.surface, point)
                        .map(|projection| projection.point.sub(point).length())
                        .unwrap_or(0.0))
                };
                let local_scale = |f: f64| -> Result<f64, KernelRefusal> {
                    Ok(1.0 + curve.evaluate(f).or_refuse(KernelStage::Intersect, "evaluate")?.length())
                };
                let is_inside = |f: f64| -> Result<bool, KernelRefusal> {
                    Ok(off_gap(f)? <= 1e-4 * local_scale(f)?)
                };
                const STATIONS: usize = 96;
                let mut previous_f = whole_start;
                let mut previous_inside = is_inside(previous_f)?;
                let mut previous_far = off_gap(previous_f)?;
                for index in 1..=STATIONS {
                    let f = whole_start + (whole_end - whole_start) * (index as f64) / (STATIONS as f64);
                    let inside = is_inside(f)?;
                    let far = off_gap(f)?;
                    // A genuine crossing: the two flanking stations disagree on
                    // membership AND at least one is DEEP off the carrier
                    // (>out_tol), so marched-section noise around 0 can never
                    // register a spurious split.
                    let deep = previous_far.max(far) > 1e-2 * local_scale(f)?;
                    if inside != previous_inside && deep {
                        // Bisect to the boundary, keeping the accepted parameter
                        // on the INSIDE flank so the retained arc ends on-carrier.
                        let (mut lo, mut hi) = (previous_f, f);
                        let lo_inside = previous_inside;
                        for _ in 0..48 {
                            let mid = 0.5 * (lo + hi);
                            if is_inside(mid)? == lo_inside {
                                lo = mid;
                            } else {
                                hi = mid;
                            }
                        }
                        let crossing = if lo_inside { lo } else { hi };
                        if crossing > whole_start + 1e-7
                            && crossing < whole_end - 1e-7
                            && !near_curve_end(curve.evaluate(crossing).or_refuse(KernelStage::Intersect, "evaluate")?)
                            && off_gap(crossing)? <= 1e-4 * local_scale(crossing)?
                            && !split_parameters
                                .iter()
                                .any(|value: &f64| (*value - crossing).abs() <= 1e-6)
                        {
                            split_parameters.push(crossing);
                        }
                    }
                    previous_f = f;
                    previous_inside = inside;
                    previous_far = far;
                }
            }
        }
        // SECTION CARRIER-SEAM SPLITS. A section crossing the parameter seam of
        // a closed revolution carrier must end there: its pcurve is built on
        // the carrier's own period, and across the branch cut the fit clamps
        // half of it onto the seam line (the 2026-09-14 gear's fillet torus
        // against a box keeper: the x = 8.5 section ran azimuth -45 deg ->
        // +45 deg over the torus's u = 0, its trim read u = 0 for the first
        // half and its ends v = 1 and v = 0 for the rim's 0.25, and the face's
        // arrangement tore on it). A native face carries its seam EDGE on that
        // meridian, so the edge pierce above already splits there and this
        // adds nothing; an imported face can carry its seam edge elsewhere and
        // only a vertex on each rim at the carrier's seam, and then nothing
        // did. The crossing is where the section passes through the seam's
        // plane on the seam's half of it (`CarrierSeam`), bisected on the sign
        // of the signed distance between two stations that stand clear of the
        // plane by more than `overlap_limit` — a section riding IN the seam's
        // plane (a plane through a torus's equator, whose outer circle is the
        // v seam) reads round-off there, and a sign flip of round-off is no
        // crossing. A crossing an existing split already stands on (within
        // `overlap_limit`) or that is the section's own end is not added again.
        // The stations are the domain-exit pass's. Escape hatch
        // `BREP_SECTION_CARRIER_SEAM_SPLIT=0`.
        if refine && std::env::var("BREP_SECTION_CARRIER_SEAM_SPLIT").as_deref() != Ok("0") {
            const STATIONS: usize = 96;
            for face in [first, second] {
                for seam in CarrierSeam::of(&face.face.surface)? {
                    let offset_at = |f: f64| -> Result<f64, KernelRefusal> {
                        Ok(seam.offset(curve.evaluate(f).or_refuse(KernelStage::Intersect, "evaluate")?))
                    };
                    // The last station clear of the plane, and its offset.
                    let mut clear: Option<(f64, f64)> = None;
                    for index in 0..=STATIONS {
                        let f = whole_start + (whole_end - whole_start) * (index as f64) / (STATIONS as f64);
                        let current = offset_at(f)?;
                        if current.abs() <= overlap_limit {
                            continue;
                        }
                        let Some((previous_f, previous)) = clear.replace((f, current)) else {
                            continue;
                        };
                        if (previous < 0.0) != (current < 0.0) {
                            let (mut lo, mut hi) = (previous_f, f);
                            let lo_negative = previous < 0.0;
                            for _ in 0..48 {
                                let mid = 0.5 * (lo + hi);
                                if (offset_at(mid)? < 0.0) == lo_negative {
                                    lo = mid;
                                } else {
                                    hi = mid;
                                }
                            }
                            let crossing = 0.5 * (lo + hi);
                            let point = curve.evaluate(crossing).or_refuse(KernelStage::Intersect, "evaluate")?;
                            let mut standing = near_curve_end(point) || !seam.on_seam_half(point);
                            for value in &split_parameters {
                                if standing {
                                    break;
                                }
                                let existing = curve.evaluate(*value).or_refuse(KernelStage::Intersect, "evaluate")?;
                                standing = existing.sub(point).length() <= overlap_limit;
                            }
                            if !standing && crossing > whole_start && crossing < whole_end {
                                split_parameters.push(crossing);
                            }
                        }
                    }
                }
            }
        }
        let [curve_start, curve_end] = curve.domain().or_refuse(KernelStage::Intersect, "domain")?;
        let split_tolerance = 2e-9f64.max((curve_end - curve_start) * KNOT_IDENTITY_TOL);
        split_parameters.sort_by(f64::total_cmp);
        split_parameters.dedup_by(|a, b| (*a - *b).abs() <= split_tolerance);
        // OVERLAP-JUNCTION EXCHANGE (rotated equator-tangency): when the
        // section curve RIDES an operand edge (the overlap branch above —
        // the tangency circle IS the cylinder's cap ring), every junction
        // minted ON the section (its split_parameters; e.g. the sphere-seam
        // crossing) is a junction OF that edge too. Without the matching
        // edge split the ring stays one CLOSED record while the section
        // arrives as open ARCS, and closed-ring vs open-arc records can
        // never endpoint-weld — both sides strand one-use (S=2 genus=1).
        // The overlap branch already exchanges the curve's ENDPOINTS; this
        // adds its interior junctions. Escape hatch:
        // BREP_OVERLAP_JUNCTION_SPLIT=0.
        if !overlapped_edges.is_empty()
            && env_read!("BREP_OVERLAP_JUNCTION_SPLIT").as_deref() != Some("0")
        {
            for parameter in &split_parameters {
                let point = curve.evaluate(*parameter).or_refuse(KernelStage::Intersect, "evaluate")?;
                for (operand, edge) in &overlapped_edges {
                    let projection = project_point_to_curve(&edge.curve, point).or_refuse(KernelStage::Intersect, "project_point_to_curve")?;
                    let nearest = edge.curve.evaluate(
                        projection
                            .u
                            .clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1)),
                    ).or_refuse(KernelStage::Intersect, "csg.imprint.builder")?;
                    if nearest.sub(point).length() <= overlap_limit {
                        pending_splits.push(PendingSplit {
                            operand: *operand,
                            edge,
                            edge_parameter: projection.u,
                            curve_parameter: *parameter,
                            point,
                        });
                    }
                }
            }
        }
        if env_read!("BREP_DEBUG_PROCESS_CURVE").is_some() {
            eprintln!(
                "process_curve[{:?}/{:?}]: domain=[{curve_start:.6},{curve_end:.6}] splits={} at {:?}",
                first.key(),
                second.key(),
                split_parameters.len(),
                split_parameters
                    .iter()
                    .map(|value| (value * 1e4).round() / 1e4)
                    .collect::<Vec<_>>()
            );
        }
        let crossing_ms = began.map_or(0.0, |start| start.elapsed().as_secs_f64() * 1000.0);
        let emission_started = profile.then(Instant::now);
        let mut pieces: Vec<(NurbsCurve, Option<[NurbsCurve; 2]>)> = Vec::new();
        let mut rest = curve;
        let mut rest_pcurves = exact_pcurves;
        for parameter in split_parameters {
            if parameter <= curve_start + split_tolerance
                || parameter >= curve_end - split_tolerance
            {
                continue;
            }
            let (left, right) = rest.split(parameter).or_refuse(KernelStage::Intersect, "split")?;
            // The pcurves share the curve's knots, so the same parameter splits
            // them alike; a split that fails leaves both halves to the march.
            let (left_pcurves, right_pcurves) = match rest_pcurves.take() {
                Some([a, b]) => match (a.split(parameter), b.split(parameter)) {
                    (Ok((a0, a1)), Ok((b0, b1))) => (Some([a0, b0]), Some([a1, b1])),
                    _ => (None, None),
                },
                None => (None, None),
            };
            pieces.push((left, left_pcurves));
            rest = right;
            rest_pcurves = right_pcurves;
        }
        pieces.push((rest, rest_pcurves));

        let debug_process = env_read!("BREP_DEBUG_PROCESS_CURVE").is_some();
        if debug_process {
            let spans: Vec<String> = pieces
                .iter()
                .map(|(piece, _)| {
                    piece
                        .domain()
                        .map(|[a, b]| format!("[{a:.4},{b:.4}]"))
                        .unwrap_or_else(|_| "[?]".into())
                })
                .collect();
            eprintln!(
                "process_curve[{:?}/{:?}]: {} piece(s): {}",
                first.key(),
                second.key(),
                pieces.len(),
                spans.join(" ")
            );
        }
        // The ends of every sub-segment minted below: `(t0, t1, start, end,
        // start radius, end radius)`, what a pending split must land on.
        let mut minted_ends: Vec<(f64, f64, Vec3, Vec3, f64, f64)> = Vec::new();
        for (piece, piece_pcurves) in pieces {
            let [t0, t1] = piece.domain().or_refuse(KernelStage::Intersect, "domain")?;
            if debug_process {
                eprintln!(
                    "process_curve[{:?}/{:?}]: ENTER piece [{t0:.4},{t1:.4}] end_dist={:.3e} rough_len={:.3e}",
                    first.key(),
                    second.key(),
                    piece.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?.sub(piece.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?).length(),
                    curve_length_rough(&piece)?
                );
            }
            if piece.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?.sub(piece.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?).length() <= self.tolerance * 10.0
                && curve_length_rough(&piece)? <= self.tolerance * 100.0
            {
                if debug_process {
                    let p = piece.evaluate((t0 + t1) / 2.0).or_refuse(KernelStage::Intersect, "evaluate")?;
                    eprintln!(
                        "process_curve[{:?}/{:?}]: sub-seg SKIP short len={:.3e} mid=({:.5},{:.5},{:.5})",
                        first.key(),
                        second.key(),
                        curve_length_rough(&piece)?,
                        p.x, p.y, p.z
                    );
                }
                continue;
            }
            let midpoint = piece.evaluate((t0 + t1) / 2.0).or_refuse(KernelStage::Intersect, "evaluate")?;
            let mut statuses = HashMap::default();
            for face in test_faces {
                let classify = |point| -> Result<PolygonClass, KernelRefusal> {
                    let projection = project_point_to_surface(&face.face.surface, point)
                        .or_refuse(KernelStage::Intersect, "project_point_to_surface")?;
                    parameter_point_in_face(face.face, Vec2 { x: projection.u, y: projection.v }, 1e-7)
                        .or_refuse(KernelStage::Intersect, "csg.imprint.builder")
                };
                let mut status = classify(midpoint)?;
                if status == PolygonClass::Boundary && !self.face_has_seam_at(*face, midpoint)? {
                    // A tangential trim contact is not an interval boundary:
                    // a section may touch the rim at its midpoint and otherwise
                    // lie inside the face. Check both nearby and farther points
                    // on each side before treating the entire piece as a rim.
                    // Riding boundaries and mixed/ambiguous probes retain the
                    // original boundary handling, including seam ownership.
                    let mut flank = None;
                    for fraction in [0.25, 0.49, 0.51, 0.75] {
                        let point = piece.evaluate(t0 + fraction * (t1 - t0))
                            .or_refuse(KernelStage::Intersect, "evaluate")?;
                        let class = classify(point)?;
                        if class == PolygonClass::Boundary || flank.is_some_and(|old| old != class) {
                            flank = None;
                            break;
                        }
                        flank = Some(class);
                    }
                    if let Some(class) = flank { status = class; }
                }
                statuses.insert(face.key(), status);
            }
            if statuses
                .values()
                .any(|status| *status == PolygonClass::Outside)
            {
                if debug_process {
                    eprintln!(
                        "process_curve[{:?}/{:?}]: sub-seg SKIP outside len={:.3e} mid=({:.5},{:.5},{:.5}) statuses={:?}",
                        first.key(),
                        second.key(),
                        curve_length_rough(&piece)?,
                        midpoint.x, midpoint.y, midpoint.z,
                        statuses
                    );
                }
                continue;
            }
            let mut attach = Vec::new();
            let mut invalid_boundary = false;
            for face in target_faces {
                if statuses.get(&face.key()) == Some(&PolygonClass::Boundary) {
                    if !self.face_has_seam_at(*face, midpoint)? {
                        // Open offset sheets have no neighbouring material face
                        // to own this cut. Keep the accurate marched section on
                        // the other sheet, but do not duplicate a boundary copy.
                        let recover = self.open_carriers
                            && refine
                            && target_faces.len() == 2
                            && !self.pieces.iter().any(|piece| {
                                piece.support_faces == [first.key(), second.key()]
                            })
                            && self.rides_sheet_surface(*face, midpoint)?;
                        if !recover {
                            invalid_boundary = true;
                            break;
                        }
                    }
                } else {
                    attach.push(*face);
                }
            }
            if invalid_boundary || attach.is_empty() {
                if debug_process {
                    eprintln!(
                        "process_curve[{:?}/{:?}]: sub-seg SKIP {} len={:.3e} mid=({:.5},{:.5},{:.5})",
                        first.key(),
                        second.key(),
                        if invalid_boundary { "invalid-boundary" } else { "attach-empty" },
                        curve_length_rough(&piece)?,
                        midpoint.x, midpoint.y, midpoint.z
                    );
                }
                continue;
            }
            let mut start = self.polish_endpoint(
                piece.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?,
                &first.face.surface,
                &second.face.surface,
            )?;
            let mut end = self.polish_endpoint(
                piece.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?,
                &first.face.surface,
                &second.face.surface,
            )?;
            let fuzzy_at = |point: Vec3| {
                fuzzy_junctions
                    .iter()
                    .filter_map(|(junction, radius)| {
                        let distance = junction.sub(point).length();
                        (distance <= radius.max(1e-5)).then_some((*junction, *radius, distance))
                    })
                    .min_by(|a, b| a.2.total_cmp(&b.2))
            };
            let start_fuzzy = fuzzy_at(start);
            let end_fuzzy = fuzzy_at(end);
            let start_radius = start_fuzzy.map(|value| value.1).unwrap_or(0.0);
            let end_radius = end_fuzzy.map(|value| value.1).unwrap_or(0.0);
            if let Some((junction, _, _)) = start_fuzzy {
                start = junction;
            }
            if let Some((junction, _, _)) = end_fuzzy {
                end = junction;
            }
            if debug_process {
                let raw_start = piece.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?;
                let raw_end = piece.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?;
                eprintln!(
                    "process_curve[{:?}/{:?}]: ENDS raw=({:.7},{:.7},{:.7})->({:.7},{:.7},{:.7}) snapped=({:.7},{:.7},{:.7})->({:.7},{:.7},{:.7}) fuzzy=({},{}) radii=({start_radius:.3e},{end_radius:.3e})",
                    first.key(), second.key(), raw_start.x, raw_start.y, raw_start.z, raw_end.x, raw_end.y, raw_end.z,
                    start.x, start.y, start.z, end.x, end.y, end.z, start_fuzzy.is_some(), end_fuzzy.is_some()
                );
            }
            let ((start_vertex_id, canonical_start), (end_vertex_id, canonical_end)) =
                self.section_vertices(start, start_radius, end, end_radius);
            if debug_process {
                eprintln!("process_curve[{:?}/{:?}]: VERTS start=v{start_vertex_id} end=v{end_vertex_id}", first.key(), second.key());
            }
            for (vertex_id, fuzzy) in [(start_vertex_id, start_fuzzy.is_some()), (end_vertex_id, end_fuzzy.is_some())] {
                let source = if fuzzy { JunctionSource::EdgePoint } else { JunctionSource::FacePoint };
                let entry = self.vertex_sources.entry(vertex_id).or_insert(source);
                *entry = (*entry).min(source);
            }
            start = canonical_start;
            end = canonical_end;
            if start_vertex_id == end_vertex_id
                && curve_length_rough(&piece)?
                    < (4.0 * piece.evaluate(t0).or_refuse(KernelStage::Intersect, "evaluate")?.sub(piece.evaluate(t1).or_refuse(KernelStage::Intersect, "evaluate")?).length()).max(1e-3)
            {
                if debug_process {
                    eprintln!(
                        "process_curve[{:?}/{:?}]: sub-seg SKIP loopback v{start_vertex_id} len={:.3e} start=({:.5},{:.5},{:.5}) end=({:.5},{:.5},{:.5}) radii=({start_radius:.3e},{end_radius:.3e})",
                        first.key(),
                        second.key(),
                        curve_length_rough(&piece)?,
                        start.x, start.y, start.z,
                        end.x, end.y, end.z
                    );
                }
                continue;
            }
            let snapped = snap_curve_ends(&piece, start, end)?;
            let exact_for = |face: &TaggedFace<'_>| -> Option<&NurbsCurve> {
                let [on_first, on_second] = piece_pcurves.as_ref()?;
                if face.key() == first.key() {
                    Some(on_first)
                } else if face.key() == second.key() {
                    Some(on_second)
                } else {
                    None
                }
            };
            let check = self.exact_pcurve_check;
            let piece_id = self.next_id;
            let pcurve_started = profile.then(Instant::now);
            let pcurves = attach
                .iter()
                .map(|face| {
                    if let Some(exact) = exact_for(face) {
                        let exact = super::hermite::piece_pcurve_on_chart(exact, face.chart(), start, end)
                            .or_refuse(KernelStage::Intersect, "piece_pcurve_on_chart")?;
                        if check {
                            // Slice 1's census: the fit lane's pcurve stands,
                            // the exact one is measured against it.
                            let fitted = build_pcurve_on_surface_marched(face.chart(), &snapped)
                                .or_refuse(KernelStage::Intersect, "build_pcurve_on_surface_marched")?;
                            let (apart, worst_t) = pcurve_images_apart(face.chart(), &snapped, &fitted, &exact, 32)
                                .or_refuse(KernelStage::Intersect, "pcurve_images_apart")?;
                            exact_iso_census(|| {
                                let at = |pcurve: &NurbsCurve| {
                                    pcurve
                                        .domain()
                                        .and_then(|[q0, q1]| pcurve.evaluate(q0 + (q1 - q0) * (worst_t - t0) / (t1 - t0).max(1e-300)))
                                        .map(|uv| format!("({:.6},{:.6})", uv.x, uv.y))
                                        .unwrap_or_default()
                                };
                                format!(
                                    "pair={}x{} face={}/{} piece={piece_id} lifted={} fitted_vs_exact={:.3e} fitted_off_curve={:.3e} exact_off_curve={:.3e} tolerance={:.3e} worst_t={worst_t:.6} fitted_uv={} exact_uv={} domain_u={:?} domain_v={:?}",
                                    first.face.id, second.face.id, face.operand, face.face.id,
                                    face.lifted.is_some(), apart[0], apart[1], apart[2], self.tolerance,
                                    at(&fitted), at(&exact), face.chart().domain_u().unwrap_or_default(), face.chart().domain_v().unwrap_or_default()
                                )
                            });
                            return Ok(FacePcurve { operand: face.operand, face_id: face.face.id, pcurve: fitted });
                        }
                        return Ok(FacePcurve {
                            operand: face.operand,
                            face_id: face.face.id,
                            pcurve: exact,
                        });
                    }
                    Ok(FacePcurve {
                        operand: face.operand,
                        face_id: face.face.id,
                        // Seeded march (see build_pcurve_on_surface_marched): a
                        // section riding a compressed/self-overlapping carrier row
                        // must not alias interior samples onto a distant preimage
                        // sheet, which folds the pcurve across the trim and strands
                        // the shared section one-use. Fail-soft to the global build.
                        // On the face's CHART: a section crossing a lifted
                        // carrier's seam is ONE curve in the band the face's own
                        // loops are drawn in, where the carrier would break it at
                        // the seam and place half of it a period away.
                        pcurve: build_pcurve_on_surface_marched(face.chart(), &snapped).or_refuse(KernelStage::Intersect, "build_pcurve_on_surface_marched")?,
                    })
                })
                .collect::<Result<Vec<_>, KernelRefusal>>()?;
            if let Some(start) = pcurve_started {
                profile_line!("imprint.process_pcurves ms={:.3}", start.elapsed().as_secs_f64() * 1000.0);
            }
            let id = self.next_id;
            self.next_id += 1;
            for face in &attach {
                if exact_for(face).is_some() && !check {
                    self.emitted_pcurves.insert((id, face.key()));
                }
            }
            if debug_process {
                eprintln!(
                    "process_curve[{:?}/{:?}]: MINT piece {id} [{t0:.4},{t1:.4}] attach={:?}",
                    first.key(),
                    second.key(),
                    attach.iter().map(|face| face.key()).collect::<Vec<_>>()
                );
            }
            for face in &attach {
                self.by_face.entry(face.key()).or_default().push(id);
            }
            minted_ends.push((t0, t1, start, end, start_radius, end_radius));
            super::work_profile::add(|c| c.minted_pieces += 1);
            self.pieces.push(ImprintPieceRecord {
                id,
                curve: snapped,
                t0,
                t1,
                start_vertex_id,
                end_vertex_id,
                pcurves,
                support_faces: [first.key(), second.key()],
                shared_edge: None,
            });
        }
        // Commit the splits a minted sub-segment ends at; the rest were
        // crossings of sub-segments the trims rejected (`minted_splits_enabled`).
        let end_parameter_band = 1e-6f64.max(split_tolerance);
        let merge_base = self.tolerance * 10.0 * merge_scale(self.scale);
        for split in pending_splits {
            let claimed = !minted_only
                || minted_ends.iter().any(|(t0, t1, start, end, start_radius, end_radius)| {
                    (split.curve_parameter - t0).abs() <= end_parameter_band
                        || (split.curve_parameter - t1).abs() <= end_parameter_band
                        || split.point.sub(*start).length() <= overlap_limit.max(*start_radius).max(merge_base)
                        || split.point.sub(*end).length() <= overlap_limit.max(*end_radius).max(merge_base)
                });
            if claimed {
                self.add_edge_split(split.operand, split.edge, split.edge_parameter)?;
            } else if debug_process {
                eprintln!(
                    "process_curve[{:?}/{:?}]: DROP stray edge split op={} edge={} t={:.6} at ({:.5},{:.5},{:.5}): no minted sub-segment ends there",
                    first.key(),
                    second.key(),
                    split.operand,
                    split.edge.id,
                    split.edge_parameter,
                    split.point.x,
                    split.point.y,
                    split.point.z
                );
            }
        }
        if let Some(start) = emission_started {
            profile_line!("imprint.process_time crossing={crossing_ms:.3} emission={:.3}", start.elapsed().as_secs_f64() * 1000.0);
        }
        Ok(())
    }
}


/// `BREP_FEATURE_SCALE_GRAZING_CROSSING` (default on, `=0` off): a tangential hit
/// that crosses to the other side of the edge is a junction, however small
/// the angle. See GRAZING CROSSING in [`ImprintBuilder::process_curve`].
fn grazing_crossing_enabled() -> bool {
    crate::switch!("BREP_FEATURE_SCALE_GRAZING_CROSSING", true)
}

/// `BREP_EXACT_TANGENT_TOUCH` (default on; `=0` restores skipping every
/// tangential hit): see TANGENT TOUCH in [`ImprintBuilder::process_curve`].
/// Promoted once the watertight tessellation meshes a face whose arcs meet at
/// zero angle: midsphere-common's exact body meshes closed.
fn exact_tangent_touch_enabled() -> bool {
    crate::switch!("BREP_EXACT_TANGENT_TOUCH", true)
}