BREP_boolean 0.31.0

Rust B-rep CAD kernel (next.BREP.io): booleans and healing: imprint, fragment, boolean assembly, sewing and face merging.
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
use crate::{KernelRefusal, KernelStage, OrRefuse, RefusalClass};
use super::*;
use super::builder::{face_name_in_solids, snap_edge_curve_endpoints, source_edge, AssembleIndex};
use super::edge_conform::{conform_overlapping_one_use_edges, edge_lies_on};
use super::refusal_welds::{
    refresh_derived_genus, split_vertices_shared_across_shells, weld_identical_coincident_one_use_edges,
    weld_open_loop_corners, weld_tangency_duplicate_vertices,
};

/// Which result faces the operation TOUCHED, read off the touch census of
/// the fragments they were built from (`touch.rs`).
pub(in crate::boolean) struct AssemblyScope {
    /// Result faces built from a touched fragment.
    pub(in crate::boolean) touched: HashSet<u64>,
    /// The touched faces and every face sharing a vertex with one: the faces
    /// whose geometry the acceptance passes read. A face outside this set is
    /// an operand's face carried through unchanged, with every vertex it
    /// stands on shared only with faces carried through the same way.
    /// Under `touch::changed_ring_on` the ring is narrower: a neighbour
    /// joins only through a vertex of a touched face where an edge the
    /// operation made ends. At every other vertex each incident edge is an
    /// operand's own, bit for bit, so a neighbour standing only on such
    /// vertices meets the touched face exactly as it did in the operand.
    pub(in crate::boolean) examined: HashSet<u64>,
    /// Result face id → the operand its fragment came from.
    pub(in crate::boolean) operand_of: HashMap<u64, u8>,
    /// Result face id → the operand face its fragment came from.
    pub(in crate::boolean) source_of: HashMap<u64, crate::imprint::FaceKey>,
}

impl AssemblyScope {
    fn build(
        origins: &[(u64, u8, bool)],
        shells: &[ShellRecord],
        edges: &[EdgeRecord],
        aliases: &HashMap<u64, u64>,
        operand_edges: Option<&HashSet<[u64; 2]>>,
    ) -> Self {
        let canonical = |mut id: u64| {
            while let Some(&next) = aliases.get(&id) {
                id = next;
            }
            id
        };
        let edge_vertices: HashMap<u64, (u64, u64)> = edges
            .iter()
            .map(|edge| (edge.id, (canonical(edge.start_vertex_id), canonical(edge.end_vertex_id))))
            .collect();
        let touched: HashSet<u64> = origins
            .iter()
            .filter(|(_, _, touched)| *touched)
            .map(|(face_id, _, _)| *face_id)
            .collect();
        let operand_of: HashMap<u64, u8> =
            origins.iter().map(|(face_id, operand, _)| (*face_id, *operand)).collect();
        let mut vertex_faces: HashMap<u64, Vec<u64>> = HashMap::default();
        let mut face_vertices: HashMap<u64, Vec<u64>> = HashMap::default();
        for face in shells.iter().flat_map(|shell| &shell.faces) {
            for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
                let Some(&(start, end)) = edge_vertices.get(&coedge.edge_id) else {
                    continue;
                };
                for vertex in [start, end] {
                    let users = vertex_faces.entry(vertex).or_default();
                    if !users.contains(&face.id) {
                        users.push(face.id);
                    }
                    let owned = face_vertices.entry(face.id).or_default();
                    if !owned.contains(&vertex) {
                        owned.push(vertex);
                    }
                }
            }
        }
        // The vertices an edge the operation made ends at; None: every vertex.
        let changed: Option<HashSet<u64>> = operand_edges.map(|held| {
            edges
                .iter()
                .filter(|edge| !held.contains(&crate::boolean::touch::edge_content(edge)))
                .flat_map(|edge| [canonical(edge.start_vertex_id), canonical(edge.end_vertex_id)])
                .collect()
        });
        let mut examined = touched.clone();
        for face_id in &touched {
            for vertex in face_vertices.get(face_id).map(Vec::as_slice).unwrap_or(&[]) {
                if changed.as_ref().is_some_and(|changed| !changed.contains(vertex)) {
                    continue;
                }
                examined.extend(vertex_faces.get(vertex).into_iter().flatten().copied());
            }
        }
        if crate::profile::profile_enabled() {
            profile_line!(
                "assemble.scope faces={} touched={} examined={} changed_vertices={}",
                origins.len(),
                touched.len(),
                examined.len(),
                changed.as_ref().map_or(-1, |changed| changed.len() as i64)
            );
        }
        Self { touched, examined, operand_of, source_of: HashMap::default() }
    }
}

/// The faces the edge passes changed: every face using a moved vertex's edge
/// or a rebuilt edge, and every face holding a replaced trim.
fn changed_faces(
    solid: &BrepSolid,
    settled: &[super::vertices::VertexMove],
    rebuilt: &[super::edges::ReplacedEdge],
    trims: &[&[super::joints::ReplacedTrim]],
) -> HashSet<u64> {
    let moved: HashSet<u64> = settled.iter().map(|item| item.vertex_id).collect();
    let mut edges: HashSet<u64> = rebuilt.iter().map(|item| item.edge_id).collect();
    edges.extend(settled.iter().flat_map(|item| item.edges.iter().map(|edge| edge.0)));
    edges.extend(
        solid.edges.iter().filter(|edge| moved.contains(&edge.start_vertex_id) || moved.contains(&edge.end_vertex_id)).map(|edge| edge.id),
    );
    let ids: Vec<u64> = solid.shells.iter().flat_map(|shell| &shell.faces).map(|face| face.id).collect();
    let mut faces = HashSet::default();
    for item in trims.iter().flat_map(|list| list.iter()) {
        let (face, edge) = item.changed();
        faces.extend(ids.get(face).copied());
        edges.extend(edge);
    }
    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
        if face.loops.iter().flat_map(|loop_record| &loop_record.coedges).any(|coedge| edges.contains(&coedge.edge_id)) {
            faces.insert(face.id);
        }
    }
    faces
}

fn assemble_fragments_impl(
    selected: Vec<FaceFragmentRecord>,
    solids: &HashMap<u8, &BrepSolid>,
    imprint: &ImprintResultRecord,
    tolerance: f64,
    allow_open: bool,
    touch: Option<&TouchCensus>,
    touched_passes: bool,
    declared_kind: crate::BodyKind,
) -> Result<(BrepSolid, Option<AssemblyScope>), KernelRefusal> {
    let _wall = crate::wall_profile::Stage::open("assembly");
    if selected.is_empty() {
        return Err(KernelRefusal::new(
            RefusalClass::ConservativeEmptyOverlap,
            KernelStage::Sew,
            "boolean assembly: operation produced no boundary faces",
        ));
    }
    let selected = if canonical_fragment_order_enabled() { crate::fragment::canonical_fragment_order(selected) } else { selected };
    let mut assembler = Assembler {
        weld_candidates: super::builder::WeldCandidates::for_assembly(),
        tolerance,
        vertices: Vec::new(),
        vertex_aliases: HashMap::default(),
        edges: Vec::new(),
        edge_use_counts: HashMap::default(),
        edge_first_forward: HashMap::default(),
        edge_boundary_key: HashMap::default(),
        edge_piece: HashMap::default(),
            imprint_edges: Default::default(),
        next_vertex_id: 1,
        next_edge_id: 1,
        next_coedge_id: 1,
        next_loop_id: 1,
        next_face_id: 1,
        edge_by_boundary_key: HashMap::default(),
        edge_tangent_side: HashMap::default(),
        feature: super::builder::FeatureWeld::from_switch(),
        cellular: declared_kind == crate::BodyKind::Cellular,
    };
    let mut faces = Vec::new();
    let mut used_face_names = HashSet::<String>::default();
    let profile = crate::imprint::profile_enabled();
    let stage_started = Instant::now();
    // id-index over the immutable operands + imprint, built once. Replaces the
    // per-coedge linear scans of solid.edges/vertices/faces during assembly.
    let index = AssembleIndex::build(solids, imprint);
    let dbg_asm = std::env::var("BREP_DEBUG_ASM_EDGES").is_ok();
    let mut dbg_edge_src: HashMap<u64, Vec<String>> = HashMap::default();
    // (result face id, operand, touched) per face built, for the scope.
    let mut origins: Vec<(u64, u8, bool)> = Vec::new();
    // (result face id, the operand face its fragment came from), for the scope.
    let mut sources: Vec<(u64, crate::imprint::FaceKey)> = Vec::new();
    // The pieces an imprinted TANGENT section was minted as
    // (`TangentSectionRecord::piece_ids`): their coedges carry a material
    // side into the weld (`SourceEdge::tangent_side`).
    let tangent_pieces: HashSet<u64> = imprint
        .tangent_sections
        .iter()
        .flat_map(|section| section.piece_ids.iter().copied())
        .collect();
    // `BREP_BOOLEAN_SIGN_CHORDS`: (result face id, an interior point of its
    // fragment, the carrier's normal there) per face built, for the chords
    // that read the result's orientation in place of its volume.
    let sign_chords = sign_chords_mode();
    let mut aims: Vec<(u64, Vec3, Option<Vec3>)> = Vec::new();
    // `BREP_ASSEMBLY_FEATURE_WELD`: a source shorter than the band is a
    // feature only when another fragment carries a short source on the same
    // two ends, so both faces sharing it read it alike whatever kind each sees
    // (imprint piece on one, an operand edge's sub-span on the other); a short
    // source with no such mate is fitting noise and keeps the band reading.
    let short_mated = if assembler.feature.mode != super::builder::FeatureWeldMode::Off {
        super::builder::short_source_mates(&selected, &index, tolerance.max(1e-7))?
    } else {
        HashSet::default()
    };
    for (fragment_index, fragment) in selected.into_iter().enumerate() {
        let dbg_operand = fragment.operand;
        let dbg_face = fragment.source_face_id;
        if sign_chords != crate::env_read::Mode::Off {
            let normal = fragment.surface.normal(fragment.test_uv.x, fragment.test_uv.y).ok();
            aims.push((assembler.next_face_id, fragment.test_point, normal));
        }
        let mut untouched = false;
        if let Some(touch) = touch {
            let touched = touch.is_touched(fragment.operand, fragment.source_face_id);
            origins.push((assembler.next_face_id, fragment.operand, touched));
            sources.push((assembler.next_face_id, crate::imprint::FaceKey { operand: fragment.operand, face_id: fragment.source_face_id }));
            untouched = touched_passes && !touched;
        } else if declared_kind == crate::BodyKind::Cellular {
            origins.push((assembler.next_face_id, fragment.operand, true));
        }
        let mut loops = Vec::new();
        assembler.feature.fragment = Some((fragment.operand, fragment.source_face_id));
        let feature_band = assembler.tolerance.max(1e-7);
        for (loop_index, fragment_loop) in fragment.loops.into_iter().enumerate() {
            let mut coedges = Vec::new();
            // `BREP_ASSEMBLY_FEATURE_WELD`: every source of the loop is read
            // first, so each end's radius knows both edges that meet there.
            let mut sources = fragment_loop
                .coedges
                .iter()
                .map(|usage| source_edge(&usage.source, &index).map(|source| (source, usage.forward)))
                .collect::<Result<Vec<_>, KernelRefusal>>()?;
            if assembler.feature.mode != super::builder::FeatureWeldMode::Off {
                for (coedge_index, (source, _)) in sources.iter_mut().enumerate() {
                    if source.start.sub(source.end).length() <= feature_band {
                        source.distinct_ends = !source.degenerate
                            && short_mated.contains(&(fragment_index, (loop_index, coedge_index)));
                    }
                }
                let radii = super::builder::loop_feature_radii(&sources, feature_band);
                for ((source, _), radius) in sources.iter_mut().zip(radii) {
                    source.feature_radius = Some(radius);
                }
            }
            for (usage, (mut source, _)) in fragment_loop.coedges.into_iter().zip(sources) {
                if let crate::fragment::FragmentEdgeSource::Imprint { piece_id } = &usage.source {
                    if tangent_pieces.contains(piece_id) {
                        source.tangent_side = tangent_material_side(
                            &source,
                            usage.forward,
                            &usage.pcurve,
                            &fragment.surface,
                            fragment.same_sense,
                        );
                        // The result names its tangent edges: `tangent` after
                        // the section's face-pair name (`a|b|tangent`), or
                        // `tangent` alone on unnamed operands.
                        source.name = Some(match source.name.take() {
                            Some(name) => format!("{name}|{TANGENT_EDGE_NAME}"),
                            None => TANGENT_EDGE_NAME.to_string(),
                        });
                    }
                }
                let dbg_desc = if dbg_asm {
                    Some(format!(
                        "{:?} bkey={:?} name={:?} s=({:.5},{:.5},{:.5}) e=({:.5},{:.5},{:.5}) face={}:{}",
                        std::mem::discriminant(&usage.source),
                        source.boundary_key,
                        source.name,
                        source.start.x, source.start.y, source.start.z,
                        source.end.x, source.end.y, source.end.z,
                        dbg_operand, dbg_face,
                    ))
                } else {
                    None
                };
                let (edge_id, reversed) = if untouched {
                    assembler.edge_untouched(source, usage.forward)?
                } else {
                    assembler.edge(source, usage.forward)?
                };
                if let Some(desc) = dbg_desc {
                    dbg_edge_src.entry(edge_id).or_default().push(desc);
                }
                coedges.push(CoedgeRecord {
                    id: assembler.next_coedge_id,
                    edge_id,
                    forward: if reversed {
                        !usage.forward
                    } else {
                        usage.forward
                    },
                    pcurve: usage.pcurve,
                });
                assembler.next_coedge_id += 1;
            }
            loops.push(LoopRecord {
                id: assembler.next_loop_id,
                coedges,
            });
            assembler.next_loop_id += 1;
        }
        // The first fragment of a source face keeps its name; later
        // fragments of the same face (splits) get deterministic `_1`, `_2`
        // suffixes, mirroring the application's split convention.
        let name =
            face_name_in_solids(&index, fragment.operand, fragment.source_face_id).map(|base| {
                if used_face_names.insert(base.clone()) {
                    base
                } else {
                    let mut suffix = 1usize;
                    loop {
                        let candidate = format!("{base}_{suffix}");
                        if used_face_names.insert(candidate.clone()) {
                            break candidate;
                        }
                        suffix += 1;
                    }
                }
            });
        faces.push(FaceRecord {
            id: assembler.next_face_id,
            surface: fragment.surface,
            same_sense: fragment.same_sense,
            loops,
            name,
        });
        assembler.next_face_id += 1;
    }
    if assembler.feature.differences > 0 {
        eprintln!(
            "FEATURE_WELD check: {} decision(s) differ in this assembly ({} edges, {} vertices)",
            assembler.feature.differences,
            assembler.edges.len(),
            assembler.vertices.len()
        );
    }
    if profile {
        profile_line!(
            "assemble.weld_ms={:.2} edges={} vertices={} candidates={} exhaustive={}",
            stage_started.elapsed().as_secs_f64() * 1_000.0,
            assembler.edges.len(),
            assembler.vertices.len(),
            assembler.weld_candidates.offered, assembler.weld_candidates.exhaustive
        );
    }
    if dbg_asm {
        let only_oneuse = std::env::var("BREP_DEBUG_ASM_EDGES").as_deref() != Ok("all");
        for edge in &assembler.edges {
            let uses = assembler.edge_use_counts.get(&edge.id).copied().unwrap_or(0);
            if only_oneuse && uses > 1 {
                continue;
            }
            eprintln!("ASM edge {} uses={} sources:", edge.id, uses);
            for desc in dbg_edge_src.get(&edge.id).into_iter().flatten() {
                eprintln!("    {desc}");
            }
        }
    }
    let stage_started = Instant::now();
    // The index covers only the append-only construction above.
    assembler.weld_candidates.vertex_candidates = None;
    conform_overlapping_one_use_edges(&mut assembler, &mut faces)?;
    // A closed result must have NO one-use edges; any left are duplicated shared
    // boundaries that failed to weld. Fuse identical coincident duplicates so the
    // shell closes. Skipped for intentionally-open sheets (their boundary edges
    // are legitimately one-use).
    // A closed loop that walks from one section curve onto another at an
    // isolated tangent node arrives at a DIFFERENT vertex than it left (the
    // two curves were split at the node by two arrangements, a chord error
    // apart); weld those corners shut. Section-to-section corners only: a
    // gap against an operand edge belongs to the conformance lanes below.
    if !allow_open {
        weld_identical_coincident_one_use_edges(&mut assembler, &mut faces)?;
        // Section edges: the imprint's pieces and the sub-edges the
        // arrangement derived from them — every edge that is not an
        // operand's (those carry a boundary key).
        let section_edges: HashSet<u64> = assembler
            .edges
            .iter()
            .map(|edge| edge.id)
            .filter(|id| !assembler.edge_boundary_key.contains_key(id))
            .collect();
        let welded_corners = weld_open_loop_corners(
            &mut assembler.vertices,
            &mut assembler.edges,
            &faces,
            &section_edges,
            tolerance,
        );
        if !welded_corners.is_empty() && std::env::var("BREP_DEBUG_BOOL").is_ok() {
            eprintln!(
                "boolean assembly welded {} open loop corner(s) at vertices {:?}",
                welded_corners.len(),
                welded_corners
            );
        }
    }
    if profile {
        profile_line!(
            "assemble.conform_ms={:.2}",
            stage_started.elapsed().as_secs_f64() * 1_000.0
        );
    }
    let stage_started = Instant::now();

    let mut parent = (0..faces.len()).collect::<Vec<_>>();
    fn find(parent: &mut [usize], index: usize) -> usize {
        crate::union_find::find_root(parent, index)
    }
    let mut edge_faces: HashMap<u64, Vec<usize>> = HashMap::default();
    for (face_index, face) in faces.iter().enumerate() {
        for coedge in face
            .loops
            .iter()
            .flat_map(|loop_record| &loop_record.coedges)
        {
            edge_faces
                .entry(coedge.edge_id)
                .or_default()
                .push(face_index);
        }
    }
    for connected in edge_faces.values() {
        for pair in connected.windows(2) {
            let a = find(&mut parent, pair[0]);
            let b = find(&mut parent, pair[1]);
            if a != b {
                parent[a] = b;
            }
        }
    }
    let mut groups: HashMap<usize, Vec<FaceRecord>> = HashMap::default();
    for (index, face) in faces.into_iter().enumerate() {
        let root = find(&mut parent, index);
        groups.entry(root).or_default().push(face);
    }
    let mut shells = groups
        .into_values()
        .enumerate()
        .map(|(index, faces)| ShellRecord {
            id: index as u64 + 1,
            faces,
        })
        .collect::<Vec<_>>();
    let mut scope = touch.map(|_| {
        let mut scope = AssemblyScope::build(&origins, &shells, &assembler.edges, &assembler.vertex_aliases, touch.and_then(|touch| touch.operand_edges.as_ref()));
        scope.source_of = sources.iter().copied().collect();
        scope
    });
    // The geometry checks of a scoped validation read the examined faces
    // only; every structural check still reads the whole solid.
    let validate_in = |solid: &BrepSolid| {
        if profile {
            profile_line!("assemble.validate_reads faces={} examined={}", solid.shells.iter().map(|s| s.faces.len()).sum::<usize>(),
                scope.as_ref().map_or_else(|| solid.shells.iter().map(|s| s.faces.len()).sum::<usize>(), |s| s.examined.len()));
        }
        match &scope {
            Some(scope) => solid.validate_scoped(&scope.examined),
            None => solid.validate(),
        }
    };
    let used_edges = edge_faces.keys().copied().collect::<HashSet<_>>();
    assembler.edges.retain(|edge| used_edges.contains(&edge.id));
    let used_vertices = assembler
        .edges
        .iter()
        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
        .collect::<HashSet<_>>();
    assembler
        .vertices
        .retain(|vertex| used_vertices.contains(&vertex.id));
    if profile {
        profile_line!(
            "assemble.shells_ms={:.2}",
            stage_started.elapsed().as_secs_f64() * 1_000.0
        );
    }
    if allow_open || declared_kind == crate::BodyKind::Cellular {
        let cells = if declared_kind == crate::BodyKind::Cellular {
            let mut operands = solids.keys().copied().collect::<Vec<_>>();
            operands.sort_unstable();
            operands.into_iter().map(|operand| crate::CellRecord {
                id: operand as u64 + 1,
                faces: origins.iter().filter(|(_, source, _)| *source == operand)
                    .map(|(face, _, _)| (*face, true)).collect(),
                void: false,
            }).collect()
        } else { Vec::new() };
        let mut solid = BrepSolid {
            mass_properties_cache: Default::default(),
            cells,
            id: 1,
            vertices: assembler.vertices,
            edges: assembler.edges,
            shells,
            genus: 0,
            kind: declared_kind,
        };
        if declared_kind == crate::BodyKind::Cellular {
            let issues = solid.validate();
            if !issues.is_empty() {
                return Err(KernelRefusal::new(
                    RefusalClass::InvalidResultTopology { issues: issues.len() as u32 },
                    KernelStage::Validate, format!("Cellular contact assembly: {issues:?}")));
            }
            return Ok((solid, None));
        }
        // EDGE RECONSTRUCTION on the open path (`edges.rs`): the offset
        // shell's welded edges stand off their carriers from here on
        // (2026-09-30 record §8: arc 40 3.2e-6 off the offset ball while its
        // trims sit on it). Vertices and trims are untouched, so no mass
        // property moves; an open sheet has no validate() gate to re-run and
        // the pass's own bounds decide each edge.
        let stage_started = Instant::now();
        let settled = settle_vertices_onto_carriers(&mut solid, tolerance, &assembler.imprint_edges)?;
        if profile {
            profile_line!("assemble.open_settle_ms={:.2}", stage_started.elapsed().as_secs_f64() * 1_000.0);
        }
        let rebuilt = reconstruct_edges_from_carriers(&mut solid, tolerance)?;
        if profile {
            profile_line!("assemble.open_reconstruct_ms={:.2}", stage_started.elapsed().as_secs_f64() * 1_000.0);
        }
        let trims = close_trim_loop_joints(&mut solid, tolerance)?;
        if profile {
            profile_line!(
                "assemble.edges_ms={:.2} settled={} rebuilt={} trims={}",
                stage_started.elapsed().as_secs_f64() * 1_000.0,
                settled.len(),
                rebuilt.len(),
                trims.len()
            );
        }
        return Ok((solid, None));
    }
    let face_count: i64 = shells.iter().map(|shell| shell.faces.len() as i64).sum();
    let hole_count: i64 = shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .map(|face| face.loops.len().saturating_sub(1) as i64)
        .sum();
    let mut edge_count = assembler
        .edges
        .iter()
        .filter(|edge| !edge.degenerate)
        .count() as i64;
    let euler = assembler.vertices.len() as i64 - edge_count + face_count - hole_count;
    let mut numerator = shells.len() as i64 * 2 - euler;
    // CUSP BEFORE WELD: a point where one face's fans touch (a flat tangent to
    // a wall, two crescents meeting at the contact) counts once per fan. When
    // that alone makes the genus integral the assembly is right and no vertex
    // pair needs welding; the nearest pair in the band below can be two
    // distinct corners of a sliver (printmotor-assembly B517, 0.028 apart).
    // Tried on copies, so any other failing assembly goes on exactly as before.
    if (numerator < 0 || numerator % 2 != 0)
        && super::refusal_welds::pinch_vertex_fans_enabled()
        && std::env::var("BREP_CUSP_BEFORE_WELD").as_deref() != Ok("0")
    {
        let mut vertices = assembler.vertices.clone();
        let mut edges = assembler.edges.clone();
        let mut next_vertex_id = assembler.next_vertex_id;
        let split = super::refusal_welds::split_pinched_vertices_by_fan(&mut vertices, &mut edges, &shells, &mut next_vertex_id);
        let euler = vertices.len() as i64 - edge_count + face_count - hole_count;
        let candidate = shells.len() as i64 * 2 - euler;
        if split > 0 && candidate >= 0 && candidate % 2 == 0 {
            assembler.vertices = vertices;
            assembler.edges = edges;
            assembler.next_vertex_id = next_vertex_id;
            numerator = candidate;
            if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                eprintln!("boolean assembly split {split} cusp fan(s) before any weld (numerator now {numerator})");
            }
        }
    }
    if numerator < 0 || numerator % 2 != 0 {
        // TANGENCY DUPLICATE-VERTEX WELD (repair-not-refuse): where two blend
        // surfaces meet TANGENTIALLY (e.g. adjacent fillet cylinders sharing a
        // tangent plane at a chain corner), the marched SSI seam endpoint
        // converges only to O(√tol) — it lands a few 1e-5 from the operand's
        // exact tangent vertex, past the assembler's weld band, leaving one
        // extra vertex and a non-integral genus.  Weld nearest not-edge-
        // connected vertex pairs (greedy, deficit-gated: stop the moment the
        // genus is integral) and snap the drifted curve endpoints onto the
        // surviving vertex.  Only ever runs on an assembly that would refuse.
        let mut welded = 0usize;
        // Deficit gate: weld ONE nearest pair at a time and recheck the genus,
        // stopping the moment it is integral and non-negative. Welding the whole
        // greedy pair list in one shot overshoots (each vertex weld shifts the
        // numerator by +1), so a -1 deficit with two duplicate vertices lands at
        // +1 (non-integral again) instead of stopping at 0.
        while numerator < 0 || numerator % 2 != 0 {
            let step = weld_tangency_duplicate_vertices(
                &mut assembler.vertices,
                &mut assembler.edges,
                tolerance,
                1,
            );
            if step == 0 {
                break;
            }
            welded += step;
            let edge_count = assembler
                .edges
                .iter()
                .filter(|edge| !edge.degenerate)
                .count() as i64;
            let euler = assembler.vertices.len() as i64 - edge_count + face_count - hole_count;
            numerator = shells.len() as i64 * 2 - euler;
        }
        if welded > 0 && std::env::var("BREP_DEBUG_BOOL").is_ok() {
            eprintln!(
                "boolean assembly welded {welded} tangency duplicate vertices (numerator now {numerator})"
            );
        }
    }
    if numerator < 0 || numerator % 2 != 0 {
        // EDGE-CONFORMANCE REPAIR (sibling of the vertex weld above): where the
        // arrangement emitted the SAME boundary as two hairline-separated
        // one-use edge records, merge them; see
        // `conform_unmatched_one_use_edges`.  Only ever runs on an assembly
        // that would refuse.
        let conformed = conform_unmatched_one_use_edges(
            &mut assembler.vertices,
            &mut assembler.edges,
            &mut shells,
            tolerance,
        )?;
        if conformed > 0 {
            CONFORMANCE_REPAIRS.with(|count| count.set(count.get() + conformed as u64));
            edge_count = assembler
                .edges
                .iter()
                .filter(|edge| !edge.degenerate)
                .count() as i64;
            let euler = assembler.vertices.len() as i64 - edge_count + face_count - hole_count;
            numerator = shells.len() as i64 * 2 - euler;
            // The refusal diagnostics below read `edge_faces`; refresh it after
            // the merge (face records keep id == index + 1).
            edge_faces.clear();
            for shell in &shells {
                for face in &shell.faces {
                    for coedge in face
                        .loops
                        .iter()
                        .flat_map(|loop_record| &loop_record.coedges)
                    {
                        edge_faces
                            .entry(coedge.edge_id)
                            .or_default()
                            .push(face.id as usize - 1);
                    }
                }
            }
            if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                eprintln!(
                    "boolean assembly conformed {conformed} unmatched one-use edges (numerator now {numerator})"
                );
            }
        }
    }
    if (numerator < 0 || numerator % 2 != 0) && super::refusal_welds::pinch_vertex_fans_enabled() {
        // PINCH VERTICES: a shell that touches itself at a point counts that
        // point once per fan (`split_pinched_vertices_by_fan`).
        let split = super::refusal_welds::split_pinched_vertices_by_fan(
            &mut assembler.vertices,
            &mut assembler.edges,
            &shells,
            &mut assembler.next_vertex_id,
        );
        if split > 0 {
            let euler = assembler.vertices.len() as i64 - edge_count + face_count - hole_count;
            numerator = shells.len() as i64 * 2 - euler;
            if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                eprintln!("boolean assembly split {split} pinch vertex fan(s) (numerator now {numerator})");
            }
        }
    }
    if numerator < 0 || numerator % 2 != 0 {
        // Roadmap T4.4: before REFUSING a closed assembly whose one-use edges
        // (open boundaries from intersection-endpoint drift) knock the genus
        // off an integer, offer the same heal chain the offset pipeline runs.
        // This is reached ONLY when `!allow_open` (the open path returned
        // early above), so it never touches a currently succeeding boolean.
        if !allow_open {
            let provisional = BrepSolid {
                mass_properties_cache: Default::default(),
                cells: Default::default(),
                id: 1,
                vertices: assembler.vertices.clone(),
                edges: assembler.edges.clone(),
                shells: shells.clone(),
                genus: 0,
                kind: crate::BodyKind::Solid,
            };
            if let Some(repaired) = repair_open_assembly_via_heal_chain(provisional, tolerance) {
                if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                    let one_use_before =
                        edge_faces.values().filter(|faces| faces.len() == 1).count();
                    eprintln!(
                        "boolean assembly repaired {one_use_before} one-use edges via heal chain"
                    );
                }
                // The heal chain rebuilt the body; nothing passes through it.
                return Ok((repaired, None));
            }
        }
        let one_use = edge_faces
            .iter()
            .filter(|(_, faces)| faces.len() == 1)
            .map(|(edge_id, _)| *edge_id)
            .collect::<Vec<_>>();
        let overused = edge_faces
            .iter()
            .filter(|(_, faces)| faces.len() > 2)
            .map(|(edge_id, faces)| (*edge_id, faces.len()))
            .collect::<Vec<_>>();
        let mut one_use_by_face = HashMap::<usize, usize>::default();
        for faces in edge_faces.values().filter(|faces| faces.len() == 1) {
            *one_use_by_face.entry(faces[0] + 1).or_default() += 1;
        }
        let shell_faces = shells
            .iter()
            .map(|shell| shell.faces.iter().map(|face| face.id).collect::<Vec<_>>())
            .collect::<Vec<_>>();
        let one_use_geometry = one_use
            .iter()
            .filter_map(|edge_id| {
                let edge = assembler.edges.iter().find(|edge| edge.id == *edge_id)?;
                let start = assembler
                    .vertices
                    .iter()
                    .find(|vertex| vertex.id == edge.start_vertex_id)?
                    .point;
                let end = assembler
                    .vertices
                    .iter()
                    .find(|vertex| vertex.id == edge.end_vertex_id)?
                    .point;
                let middle = edge
                    .curve
                    .evaluate((edge.t0 + edge.t1) / 2.0)
                    .unwrap_or(start);
                Some((
                    *edge_id,
                    edge.degenerate,
                    edge.curve.degree,
                    start,
                    middle,
                    end,
                ))
            })
            .take(40)
            .collect::<Vec<_>>();
        let mut geometric_matches = Vec::new();
        for (index, first_id) in one_use.iter().enumerate() {
            let first = assembler
                .edges
                .iter()
                .find(|edge| edge.id == *first_id)
                .unwrap();
            for second_id in one_use.iter().skip(index + 1) {
                let second = assembler
                    .edges
                    .iter()
                    .find(|edge| edge.id == *second_id)
                    .unwrap();
                if edge_lies_on(first, second, 2e-3).unwrap_or(false)
                    || edge_lies_on(second, first, 2e-3).unwrap_or(false)
                {
                    geometric_matches.push((*first_id, *second_id));
                }
            }
        }
        return Err(KernelRefusal::new(
            RefusalClass::NonIntegralGenus {
                shells: shells.len() as u32,
                euler: assembler.vertices.len() as i64 - edge_count as i64 + face_count as i64
                    - hole_count as i64,
            },
            KernelStage::Validate,
            format!(
            "boolean assembly: non-integral genus \
             (V={} E={} F={} H={} S={} shell_faces={:?} \
             one_use={} {:?} one_use_geometry={one_use_geometry:?} \
             geometric_matches={geometric_matches:?} \
             one_use_by_face={:?} overused={} {:?}); on faces [{}]",
            assembler.vertices.len(),
            edge_count,
            face_count,
            hole_count,
            shells.len(),
            shell_faces,
            one_use.len(),
            one_use.iter().take(24).collect::<Vec<_>>(),
            one_use_by_face,
            overused.len(),
            overused.iter().take(24).collect::<Vec<_>>(),
            {
                // The same faces by name (face records keep id == index + 1).
                let mut named = one_use_by_face.iter().collect::<Vec<_>>();
                named.sort();
                named
                    .into_iter()
                    .map(|(id, count)| {
                        let name = shells
                            .iter()
                            .flat_map(|shell| &shell.faces)
                            .find(|face| face.id == *id as u64)
                            .and_then(|face| face.name.clone())
                            .unwrap_or_default();
                        format!("{id} '{name}' x{count}")
                    })
                    .collect::<Vec<_>>()
                    .join(", ")
            },
        )));
    }
    // A vertex used by edges of two edge-disconnected shells is a point
    // contact between two bodies (the subtract that cuts a cylinder with an
    // equal-radius crossing cylinder leaves two pieces touching at the two
    // tangent points). Each shell gets its own vertex there: two closed
    // manifold shells, no pinch, and a genus read off each one's own count.
    // Runs after the Euler-gated welds above, whose nearest-pair search would
    // otherwise merge the copies straight back.
    if shells.len() > 1 {
        let split = split_vertices_shared_across_shells(
            &mut assembler.vertices,
            &mut assembler.edges,
            &shells,
            &mut assembler.next_vertex_id,
        );
        if split > 0 {
            edge_count = assembler
                .edges
                .iter()
                .filter(|edge| !edge.degenerate)
                .count() as i64;
            let euler = assembler.vertices.len() as i64 - edge_count + face_count - hole_count;
            numerator = shells.len() as i64 * 2 - euler;
            if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                eprintln!(
                    "boolean assembly split {split} welded node vertex/vertices between shells (numerator now {numerator})"
                );
            }
        }
    }
    let solid = BrepSolid {
        mass_properties_cache: Default::default(),
        cells: Default::default(),
        id: 1,
        vertices: assembler.vertices,
        edges: assembler.edges,
        shells,
        genus: numerator / 2,
        kind: crate::BodyKind::Solid,
    };
    let (touched_faces, examined_faces) = match (&scope, touched_passes) {
        (Some(scope), true) => (Some(&scope.touched), Some(&scope.examined)),
        _ => (None, None),
    };
    let touched_vertices: Option<HashSet<u64>> = touched_faces.map(|faces| {
        let edge_vertices: HashMap<u64, (u64, u64)> = solid
            .edges
            .iter()
            .map(|edge| (edge.id, (edge.start_vertex_id, edge.end_vertex_id)))
            .collect();
        solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .filter(|face| faces.contains(&face.id))
            .flat_map(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges))
            .filter_map(|coedge| edge_vertices.get(&coedge.edge_id))
            .flat_map(|&(start, end)| [start, end])
            .collect()
    });
    let stage_started = Instant::now();
    let mut solid = match &touched_vertices {
        Some(vertices) => crate::coalesce::merge_curve_continuation_edges_at(&solid, tolerance, vertices)?,
        None => merge_curve_continuation_edges(&solid, tolerance)?,
    };
    if profile {
        profile_line!(
            "assemble.continuation_ms={:.2}",
            stage_started.elapsed().as_secs_f64() * 1_000.0
        );
    }
    let stage_started = Instant::now();
    let polished = polish_triple_junction_vertices_in(&mut solid, tolerance, touched_vertices.as_ref())?;
    if profile {
        profile_line!(
            "assemble.junction_ms={:.2} polished={polished}",
            stage_started.elapsed().as_secs_f64() * 1_000.0
        );
    }
    // Genus is derived bookkeeping and every post-assembly pass (edge
    // continuation merges, junction polish) shifts the V/E counts it came
    // from; a stale value makes the Euler validation reject a perfectly
    // manifold result (two touching shells: assembly-time chi drifted while
    // genus kept its old value). Recompute at the validation boundary with
    // the same shell-aware formula validate() checks against.
    refresh_derived_genus(&mut solid);
    let stage_started = Instant::now();
    let mut issues = validate_in(&solid);
    if profile {
        profile_line!(
            "assemble.validate_ms={:.2}",
            stage_started.elapsed().as_secs_f64() * 1_000.0
        );
    }
    if !issues.is_empty() {
        // EDGE-CONFORMANCE RETRY at the validation boundary: the overshoot
        // lanes can leave a hairline one-use sliver bridging an OPEN loop gap
        // (the neighbour's arrangement split at the drifted SSI endpoint, this
        // face's at the exact station) that only surfaces here.  The pass runs
        // exclusively on this refusal path and the re-validate below still
        // gates the result.
        let conformed = conform_unmatched_one_use_edges(
            &mut solid.vertices,
            &mut solid.edges,
            &mut solid.shells,
            tolerance,
        )?;
        if conformed > 0 {
            CONFORMANCE_REPAIRS.with(|count| count.set(count.get() + conformed as u64));
            refresh_derived_genus(&mut solid);
            issues = validate_in(&solid);
            if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                eprintln!(
                    "boolean assembly conformed {conformed} unmatched one-use edges at validation ({} issues remain)",
                    issues.len()
                );
            }
        }
    }
    if !issues.is_empty()
        && issues.iter().all(|issue| {
            issue.severity == "error"
                && matches!(issue.kind, crate::IssueKind::CurveVertexGap { .. })
        })
    {
        // GEOMETRIC ENDPOINT-GAP REPAIR (repair-not-refuse): a TOPOLOGICALLY
        // CLOSED assembly (no open/over-used edges, integral genus) can still
        // carry an edge whose CURVE endpoint lands a couple 1e-4 off its
        // assigned vertex — an SSI march that reached the triple point only to
        // O(1e-4) on imported geometry, where the vertex is the authoritative
        // datum (a shared operand corner) and the curve end is the drifted one.
        // When EVERY remaining issue is such a curve<->vertex gap within a
        // commit-scale band, pin each offending edge's curve endpoint onto its
        // vertex via `snap_edge_curve_endpoints`. Purely geometric: vertex
        // positions and topology never change, and the re-validate below still
        // gates the result, so a mixed or larger issue set refuses exactly as
        // before.
        let gap_band = commit_weld(tolerance) * 10.0;
        let vertex_points = solid
            .vertices
            .iter()
            .map(|vertex| (vertex.id, vertex.point))
            .collect::<HashMap<_, _>>();
        let mut snapped_any = false;
        for edge in &mut solid.edges {
            if edge.degenerate {
                continue;
            }
            let (Some(&start), Some(&end)) = (
                vertex_points.get(&edge.start_vertex_id),
                vertex_points.get(&edge.end_vertex_id),
            ) else {
                continue;
            };
            let start_gap = edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?.sub(start).length();
            let end_gap = edge.curve.evaluate(edge.t1).or_refuse(KernelStage::Sew, "evaluate")?.sub(end).length();
            if start_gap <= 1e-9 && end_gap <= 1e-9 {
                continue;
            }
            if start_gap > gap_band || end_gap > gap_band {
                continue;
            }
            let curve = snap_edge_curve_endpoints(edge.curve.clone(), edge.t0, edge.t1, start, end)?;
            let [t0, t1] = curve.domain().or_refuse(KernelStage::Sew, "domain")?;
            edge.curve = curve;
            edge.t0 = t0;
            edge.t1 = t1;
            snapped_any = true;
        }
        if snapped_any {
            refresh_derived_genus(&mut solid);
            issues = validate_in(&solid);
            if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                eprintln!(
                    "boolean assembly snapped curve endpoints onto vertices ({} issues remain)",
                    issues.len()
                );
            }
        }
    }
    if issues.is_empty() {
        // EDGE RECONSTRUCTION (repair-not-refuse; `edges.rs`): a two-use edge
        // that stands off one of its carriers is replaced by the exact image
        // of a planar use's trim with its ends pinned to the vertices.
        // validate() holds edges to a 4e-3 contract and never sees these
        // standoffs, so this runs on the validated result; a set the
        // validator then disagrees with is put back whole.
        let stage_started = Instant::now();
        let mut pass_started = Instant::now();
        let pass_ms = |label: &str, pass_started: &mut Instant| {
            if profile {
                profile_line!("assemble.edges.{label}_ms={:.2}", pass_started.elapsed().as_secs_f64() * 1_000.0);
                *pass_started = Instant::now();
            }
        };
        let settled = settle_vertices_onto_carriers_in(&mut solid, tolerance, &assembler.imprint_edges, touched_vertices.as_ref())?;
        pass_ms("settle", &mut pass_started);
        let rebuilt = reconstruct_edges_from_carriers_in(&mut solid, tolerance, touched_faces)?;
        pass_ms("reconstruct", &mut pass_started);
        let trims = close_trim_loop_joints_in(&mut solid, tolerance, examined_faces)?;
        pass_ms("joints", &mut pass_started);
        // The DERIVED inherited-trim challenger (`inherited.rs`): output uses
        // of operand edges only, restored first if the stage goes back.
        let separated = super::inherited::separated_faces(&solid, solids, &origins, tolerance);
        let inherited = super::inherited::challenge_inherited_trims_scoped(&mut solid, tolerance, &assembler.edge_boundary_key, &assembler.imprint_edges,
            std::env::var("BREP_INHERITED_TRIM_REFIT").as_deref() != Ok("0"), examined_faces, Some(&separated))?;
        pass_ms("inherited", &mut pass_started);
        if !rebuilt.is_empty() || !settled.is_empty() || !trims.is_empty() || !inherited.is_empty() {
            // Under the changed ring the gate also reads every face these
            // passes changed: they run on the whole solid, so a face outside
            // the ring can hold a rebuilt edge or a refitted trim. A kept
            // change makes its faces examined from here on.
            let widened = match &scope {
                Some(scope) if crate::boolean::touch::changed_ring_on() => {
                    let mut faces = scope.examined.clone();
                    faces.extend(changed_faces(&solid, &settled, &rebuilt, &[&trims, &inherited]));
                    Some(faces)
                }
                _ => None,
            };
            let after = match &widened {
                Some(faces) => solid.validate_scoped(faces),
                None => validate_in(&solid),
            };
            let count = rebuilt.len();
            if after.is_empty() {
                if let (Some(scope), Some(faces)) = (&mut scope, widened) {
                    scope.examined = faces;
                }
                if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                    eprintln!("boolean assembly settled {} vertices and reconstructed {count} edges from their planar trims; {} inherited trims refit", settled.len(), inherited.len());
                }
            } else {
                restore_trims(&mut solid, inherited);
                restore_trims(&mut solid, trims);
                restore_edges(&mut solid, rebuilt);
                restore_vertices(&mut solid, settled);
                if std::env::var("BREP_DEBUG_BOOL").is_ok() {
                    eprintln!(
                        "boolean assembly restored {count} reconstructed edges: validate() reported {} issues on them",
                        after.len()
                    );
                }
            }
        }
        if profile {
            profile_line!(
                "assemble.edges_ms={:.2}",
                stage_started.elapsed().as_secs_f64() * 1_000.0
            );
        }
    }
    if !issues.is_empty() {
        let mut use_counts = HashMap::<u64, usize>::default();
        for coedge in solid
            .shells
            .iter()
            .flat_map(|shell| &shell.faces)
            .flat_map(|face| &face.loops)
            .flat_map(|loop_record| &loop_record.coedges)
        {
            *use_counts.entry(coedge.edge_id).or_default() += 1;
        }
        let open_edges = solid
            .edges
            .iter()
            .filter(|edge| use_counts.get(&edge.id).copied().unwrap_or(0) == 1)
            .map(|edge| {
                let start = solid
                    .vertices
                    .iter()
                    .find(|vertex| vertex.id == edge.start_vertex_id)
                    .map(|vertex| vertex.point);
                let end = solid
                    .vertices
                    .iter()
                    .find(|vertex| vertex.id == edge.end_vertex_id)
                    .map(|vertex| vertex.point);
                format!("{}:{start:?}->{end:?}", edge.id)
            })
            .collect::<Vec<_>>();
        if std::env::var("BREP_DEBUG_VALIDATE").is_ok() {
            for issue in &issues {
                if let Some(rest) = issue.message.strip_prefix("coedge ") {
                    if let Some(edge_part) = rest.split("edge ").nth(1) {
                        if let Some(edge_id) = edge_part
                            .split_whitespace()
                            .next()
                            .and_then(|token| token.parse::<u64>().ok())
                        {
                            if let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) {
                                let [d0, d1] = edge.curve.domain().unwrap_or([0.0, 0.0]);
                                eprintln!(
                                    "VALIDATE edge {}: name={:?} degen={} t=[{:.6},{:.6}] domain=[{:.6},{:.6}] cps={}",
                                    edge.id,
                                    edge.name,
                                    edge.degenerate,
                                    edge.t0,
                                    edge.t1,
                                    d0,
                                    d1,
                                    edge.curve.control_points.len()
                                );
                                for fraction in [0.0f64, 0.5, 1.0] {
                                    if let Ok(point) = edge
                                        .curve
                                        .evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction)
                                    {
                                        eprintln!(
                                            "  edge point {:.2}: ({:.6},{:.6},{:.6})",
                                            fraction, point.x, point.y, point.z
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // The faces holding the open edges, by name: a name is its source
        // face's, so the refusal says which operand faces lost a partner — the
        // pair to measure — not only which minted edge ids did.
        let mut open_faces: Vec<(u64, String, usize)> = Vec::new();
        for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
            let count = face
                .loops
                .iter()
                .flat_map(|loop_record| &loop_record.coedges)
                .filter(|coedge| use_counts.get(&coedge.edge_id).copied().unwrap_or(0) == 1)
                .count();
            if count > 0 {
                open_faces.push((face.id, face.name.clone().unwrap_or_default(), count));
            }
        }
        let open_faces = open_faces
            .iter()
            .map(|(id, name, count)| format!("{id} '{name}' x{count}"))
            .collect::<Vec<_>>();
        return Err(KernelRefusal::new(
            RefusalClass::DegenerateArrangement {
                open_edges: open_edges.len() as u32,
                issues: issues.len() as u32,
            },
            KernelStage::Validate,
            format!(
            "boolean assembly produced invalid topology (S={} genus={}): {issues:?}; open edges [{}]; on faces [{}]",
            solid.shells.len(),
            solid.genus,
            open_edges.join(", "),
            open_faces.join(", ")
        )));
    }
    // Exercise exact integration here so a geometrically inverted shell is
    // rejected at the kernel boundary instead of reaching the application.
    // Volume-only: the gate reads nothing but the sign, so it reads
    // `solid_signed_volume_for_sign`, which skips the sliver corrections on
    // chords whose pcurve is straight in uv (a bore's rims: 105 of the plate
    // case's 128 ms assembly were those corrections) and otherwise is the
    // exact integration, including bit for bit whenever the reading sits
    // within its margin of the bar.
    let stage_started = Instant::now();
    let _caller = crate::mass_caller("assemble.mass_check");
    let bar = tolerance.powi(3);
    // `BREP_BOOLEAN_SIGN_CHORDS`: where no imprint coincidence or tangent
    // contact could leave a shell of no thickness, chords through every face
    // built from a touched fragment read the orientation in place of the
    // volume. A positive reading stands for the volume check under `on`;
    // under `check` both run and a positive reading the volume refuses is
    // reported.
    let chords_admitted = sign_chords != crate::env_read::Mode::Off
        && !allow_open
        && declared_kind == crate::BodyKind::Solid
        && imprint.cosurface_pairs.is_empty()
        && imprint.tangent_sections.is_empty()
        && sign_check_void_shells_enabled()
        && (!sign_chords_analytic_only_enabled() || every_face_analytic(&solid));
    let chords_positive = chords_admitted
        && orientation_by_chords(&solid, &aims, scope.as_ref(), tolerance, profile || sign_chords == crate::env_read::Mode::Check);
    if chords_positive && sign_chords == crate::env_read::Mode::On {
        if profile {
            profile_line!("assemble.mass_check_ms={:.2} by=chords", stage_started.elapsed().as_secs_f64() * 1_000.0);
        }
        return Ok((solid, scope));
    }
    // A shell with no touched face is an operand's shell as the operand held
    // it; its sign is the operand's and it is left out of the check. With no
    // shell touched (a disjoint union) there is nothing to integrate.
    let volume = match &scope {
        Some(scope) => {
            let touched_shells = solid
                .shells
                .iter()
                .filter(|shell| shell.faces.iter().any(|face| scope.touched.contains(&face.id)))
                .collect::<Vec<_>>();
            if touched_shells.is_empty() {
                None
            } else if touched_shells.len() == solid.shells.len() {
                Some(solid_signed_volume_for_sign(&solid, bar).or_refuse(KernelStage::Sew, "solid_signed_volume")?)
            } else {
                let subset = BrepSolid {
                    mass_properties_cache: Default::default(),
                    cells: Default::default(),
                    id: solid.id,
                    vertices: solid.vertices.clone(),
                    edges: solid.edges.clone(),
                    shells: touched_shells.into_iter().cloned().collect(),
                    genus: 0,
                    kind: crate::BodyKind::Solid,
                };
                let subset_volume = solid_signed_volume_for_sign(&subset, bar).or_refuse(KernelStage::Sew, "solid_signed_volume")?;
                // VOID SHELLS (`BREP_SIGN_CHECK_VOID_SHELLS`): when every touched
                // shell bounds a void (a post grown up into a hollow dome's cavity
                // touches only the cavity), the subset reads negative by design;
                // the sign that matters is the whole solid's.
                if subset_volume <= bar && sign_check_void_shells_enabled() {
                    Some(solid_signed_volume_for_sign(&solid, bar).or_refuse(KernelStage::Sew, "solid_signed_volume")?)
                } else {
                    Some(subset_volume)
                }
            }
        }
        None => Some(solid_signed_volume_for_sign(&solid, bar).or_refuse(KernelStage::Sew, "solid_signed_volume")?),
    };
    if profile {
        profile_line!(
            "assemble.mass_check_ms={:.2}",
            stage_started.elapsed().as_secs_f64() * 1_000.0
        );
    }
    if chords_positive {
        if let Some(volume) = volume.filter(|volume| *volume <= bar) {
            eprintln!(
                "boolean.sign_chords DISAGREE: the chords read a positive orientation, the volume reads {volume:.6e} (bar {bar:.3e}); faces {}",
                solid.shells.iter().map(|shell| shell.faces.len()).sum::<usize>()
            );
        }
    }
    if volume.is_some_and(|volume| volume <= bar) {
        return Err(KernelRefusal::new(
            RefusalClass::NonPositiveVolume,
            KernelStage::Validate,
            "boolean assembly produced non-positive volume",
        ));
    }
    Ok((solid, scope))
}


/// `BREP_BOOLEAN_SIGN_CHORDS` (default on; `0`/`off` reads the volume on every
/// result as before; `check` runs the chords and the volume both and reports
/// a positive reading the volume refuses): the boolean
/// assembly's non-positive-volume check reads the result's orientation along
/// chords where it can ([`orientation_by_chords`]).
fn sign_chords_mode() -> crate::env_read::Mode {
    crate::mode_switch!("BREP_BOOLEAN_SIGN_CHORDS", true)
}

/// `BREP_SIGN_CHORDS_ANALYTIC_ONLY` (default on; `0`/`off` lets chords read any
/// result): the chords read a result only when every one of its faces has a
/// recognised analytic carrier (`NurbsSurface::analytic`: planes, revolution
/// quadrics and tori, and revolutions of a spline generatrix). A chord
/// meets every face in its path, and against a freeform wall each crossing is
/// a Newton search over the whole patch: on a screw thread's helicoidal walls
/// the chords cost 3.2 s where the volume certificate they replace costs a
/// fraction of that (a fine thread with sharp crests: 4.2 s off, 7.3 s on, release build).
/// Every result that gained from the chords on the floor rows is all analytic.
fn sign_chords_analytic_only_enabled() -> bool {
    switch!("BREP_SIGN_CHORDS_ANALYTIC_ONLY", true)
}

fn every_face_analytic(solid: &BrepSolid) -> bool {
    let extrusions = sign_chords_extrusions_enabled();
    solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .all(|face| face.surface.analytic().is_some() || (extrusions && face.surface.linear_extrusion().is_some()))
}

/// `BREP_SIGN_CHORDS_EXTRUSIONS` (on by default; `=0` keeps the gate to analytic
/// carriers): the analytic-only gate of the
/// sign chords ([`sign_chords_analytic_only_enabled`]) also admits a face
/// whose carrier is a recognised linear extrusion (a profile swept straight:
/// a sweep slid along a line). A chord still crosses such a face by the
/// sampled Newton search a non-analytic face takes, but over a patch straight
/// along its rulings that search is short; a screw thread's helicoid, where
/// it costs seconds, is no extrusion and stays with the volume. A ring leaning 35 degrees pushed into a block: the
/// sign check fell from 370 ms to 37 ms, the body the same to the bit.
fn sign_chords_extrusions_enabled() -> bool {
    switch!("BREP_SIGN_CHORDS_EXTRUSIONS", true)
}

/// Whether chords read the assembled solid as positively oriented at every
/// face built from a touched fragment (every face built when there is no
/// scope).
///
/// The volume check refuses a result whose touched shells hold no material:
/// inside out, or of no thickness. With no imprint coincidence and no tangent
/// contact (the caller's gate), a closed shell has thickness, and the sign is
/// its orientation. The solid's topology is valid here: every edge is used
/// twice in opposite senses, so a face reversed against its neighbours shows
/// as hits that fail to alternate. Each aimed face is crossed by a chord
/// through its fragment's interior point
/// ([`crate::classification::SolidClassifier::chord_orientation`]), along the carrier's
/// normal there and, where that chord cannot tell, along the classifier's
/// fixed directions; every aimed face must read positive, each chord
/// checking every face it crosses. A face with no aim, a chord that cannot
/// tell along any direction, or any inside-out reading answers `false`, and
/// the volume is read as before.
fn orientation_by_chords(
    solid: &BrepSolid,
    aims: &[(u64, Vec3, Option<Vec3>)],
    scope: Option<&AssemblyScope>,
    tolerance: f64,
    profile: bool,
) -> bool {
    const DIRECTIONS: [Vec3; 4] = [
        Vec3 { x: 0.577215, y: 0.618034, z: 0.532088 },
        Vec3 { x: -0.707107, y: 0.267949, z: 0.654321 },
        Vec3 { x: 0.316228, y: -0.741657, z: 0.585786 },
        Vec3 { x: -0.414214, y: -0.552786, z: -0.723607 },
    ];
    let started = Instant::now();
    let built: HashSet<u64> = solid.shells.iter().flat_map(|shell| &shell.faces).map(|face| face.id).collect();
    let aimed = |id: &u64| built.contains(id) && scope.is_none_or(|scope| scope.touched.contains(id));
    let wanted = solid
        .shells
        .iter()
        .flat_map(|shell| &shell.faces)
        .filter(|face| aimed(&face.id))
        .count();
    let reading = (|| {
        let classifier = crate::classification::SolidClassifier::new(solid, tolerance).ok()?;
        let mut read = 0usize;
        for (face_id, point, normal) in aims.iter().filter(|(id, _, _)| aimed(id)) {
            let verdict = normal
                .iter()
                .chain(DIRECTIONS.iter())
                .find_map(|direction| classifier.chord_orientation(*point, *direction).ok().flatten());
            if verdict != Some(true) {
                if profile {
                    profile_line!("assemble.sign_chords face={face_id} verdict={verdict:?}");
                }
                return None;
            }
            read += 1;
        }
        Some(read)
    })();
    let positive = wanted > 0 && reading == Some(wanted);
    if profile {
        profile_line!(
            "assemble.sign_chords positive={positive} faces={wanted} read={reading:?} ms={:.2}",
            started.elapsed().as_secs_f64() * 1_000.0
        );
    }
    positive
}

/// `BREP_SIGN_CHECK_VOID_SHELLS` (default on; `=0` restores reading the touched
/// shells alone): the assembly's sign check reads the whole solid when its
/// touched shells alone read non-positive, as a set of void shells does.
fn sign_check_void_shells_enabled() -> bool {
    switch!("BREP_SIGN_CHECK_VOID_SHELLS", true)
}

/// `BREP_FRAGMENT_CANONICAL_ORDER` (lane X, fillet-bore-notch): the assembler
/// builds the fragments in [`crate::fragment::canonical_fragment_order`], so the
/// `_1`, `_2` names of a split face's pieces and every id do not follow a tie
/// between near-equal areas. On by default (promoted on the 239-document
/// census: 21 documents changed, every body geometrically identical, every
/// moved fragment swapped with one whose area lies within 4.2e-10 of its own);
/// `0`/`off` disables it.
fn canonical_fragment_order_enabled() -> bool {
    switch!(live "BREP_FRAGMENT_CANONICAL_ORDER", true)
}


pub fn assemble_fragments(
    selected: Vec<FaceFragmentRecord>,
    solids: &HashMap<u8, &BrepSolid>,
    imprint: &ImprintResultRecord,
    tolerance: f64,
) -> Result<BrepSolid, KernelRefusal> {
    assemble_fragments_impl(selected, solids, imprint, tolerance, false, None, false, crate::BodyKind::Solid).map(|(solid, _)| solid)
}

/// [`assemble_fragments`] reporting which result faces the operation touched
/// (`BooleanOptions::untouched_passthrough`): the acceptance passes inside
/// read the geometry of the touched faces and their neighbours only, and the
/// caller's passes read the returned scope the same way. With
/// `touched_passes` (`BooleanOptions::touched_assembly`) the weld finds an
/// untouched face's mate by key and the settle, reconstruction, joint,
/// inherited-trim, junction and continuation passes read the touched faces
/// (and their neighbours where the pass reaches across an edge) only.
pub(in crate::boolean) fn assemble_fragments_scoped(
    selected: Vec<FaceFragmentRecord>,
    solids: &HashMap<u8, &BrepSolid>,
    imprint: &ImprintResultRecord,
    tolerance: f64,
    touch: &TouchCensus,
    touched_passes: bool,
) -> Result<(BrepSolid, Option<AssemblyScope>), KernelRefusal> {
    assemble_fragments_impl(selected, solids, imprint, tolerance, false, Some(touch), touched_passes, crate::BodyKind::Solid)
}

pub fn assemble_open_fragments(
    selected: Vec<FaceFragmentRecord>,
    solids: &HashMap<u8, &BrepSolid>,
    imprint: &ImprintResultRecord,
    tolerance: f64,
) -> Result<BrepSolid, KernelRefusal> {
    assemble_fragments_impl(selected, solids, imprint, tolerance, true, None, false, crate::BodyKind::Solid).map(|(solid, _)| solid)
}

/// The producer declares the Cellular kind before assembly. It is admitted
/// only after the boolean has kept both complete operand boundaries.
pub(in crate::boolean) fn assemble_cellular_fragments(
    selected: Vec<FaceFragmentRecord>,
    solids: &HashMap<u8, &BrepSolid>,
    imprint: &ImprintResultRecord,
    tolerance: f64,
) -> Result<BrepSolid, KernelRefusal> {
    assemble_fragments_impl(selected, solids, imprint, tolerance, false, None, false,
        crate::BodyKind::Cellular).map(|(solid, _)| solid)
}


/// The name a tangent section's edge records carry in the result (alone on
/// unnamed operands, after the face-pair name otherwise).
pub const TANGENT_EDGE_NAME: &str = "tangent";

/// The direction INTO a face from a tangent section's midpoint, `n_out × t`
/// (see `SourceEdge::tangent_side`): the face's outward normal at the
/// section's midpoint crossed with the coedge's direction of travel along
/// the section. `None` where the geometry cannot be read (a pole, a collapsed
/// span), which leaves the coedge to the arrival-order weld.
fn tangent_material_side(
    source: &SourceEdge,
    forward: bool,
    pcurve: &NurbsCurve,
    surface: &crate::NurbsSurface,
    same_sense: bool,
) -> Option<Vec3> {
    let middle = 0.5 * (source.t0 + source.t1);
    let derivatives = source.curve.derivatives(middle, 1).ok()?;
    let mut travel = derivatives.get(1).copied()?.normalized().ok()?;
    if !forward {
        travel = travel.scale(-1.0);
    }
    let [p0, p1] = pcurve.domain().ok()?;
    let uv = pcurve.evaluate(0.5 * (p0 + p1)).ok()?;
    let normal = surface.normal(uv.x, uv.y).ok()?;
    let outward = if same_sense { normal } else { normal.scale(-1.0) };
    let side = outward.cross(travel);
    (side.length() > 1e-9).then(|| side.normalized().ok()).flatten()
}