Skip to main content

brep_offset/offset/offset_shell/
pipeline.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4/// Put every face on one normal convention (surface normal on the CCW
5/// parameter-winding side) and then restore outward normals. The offset shell's
6/// source and offset skins are assembled as independent components whose
7/// per-face `same_sense` can follow opposite conventions; `validate()` only
8/// checks coedge-direction coherence (the `forward` flags), so a joined,
9/// watertight, coedge-coherent manifold can still be normal-incoherent and
10/// report the wrong volume. Re-deriving `same_sense` from the loop winding makes
11/// the coedge-coherent manifold normal-coherent; the signed-volume flip then
12/// orients it outward. Only invoked after a non-coplanar rim weld, so the
13/// coplanar cylinder/prism shells keep their exact assembled orientation.
14/// `BREP_OFFSET_ONE_CALL_IMPRINT` (lane P3b row 6, 2026-10-26): one
15/// `build_imprints` over a composite of every carrier instead of one call per
16/// pair. On by default (promoted 2026-10-27 after the 98 + 144 case oracle
17/// census); `0`/`off` retains the per-pair calls. Re-pinned by independent
18/// oracles, not byte-identical (piece and vertex numbering is the single
19/// call's).
20fn one_call_imprint_enabled() -> bool {
21    switch!("BREP_OFFSET_ONE_CALL_IMPRINT", true)
22}
23
24thread_local! {
25    static ONE_CALL_RUNS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
26}
27
28
29fn coheres_face_normals(solid: &mut BrepSolid) -> Result<(), KernelRefusal> {
30    for face in solid.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
31        face.same_sense = parameter_space_area(face).or_refuse(KernelStage::Sew, "parameter_space_area")? > 0.0;
32    }
33    // Outward is a PER-SHELL property: a through-hole shelled at both ends
34    // legitimately produces two disjoint closed components (the outer wall
35    // tube and the hole wall tube), and a single global signed-volume flip
36    // cannot orient both.
37    for shell_index in 0..solid.shells.len() {
38        let single = BrepSolid {
39            mass_properties_cache: Default::default(),
40            cells: Default::default(),
41            id: solid.id,
42            vertices: solid.vertices.clone(),
43            edges: solid.edges.clone(),
44            shells: vec![solid.shells[shell_index].clone()],
45            genus: 0,
46            kind: crate::BodyKind::Solid,
47        };
48        // Read for its SIGN only, through the per-face term memo
49        // (`solid_signed_volume_for_sign`: the verdict against the bar is the
50        // exact integral's, and a face read about the same reference before —
51        // the next feature's push, the boolean assembler's own check — is
52        // served its term). The exact read here cost 0.26 s on the shelled-box
53        // report's 34-face shell, 42 of its faces fitted.
54        if crate::signed_volume_against(&single, 0.0).or_refuse(KernelStage::Sew, "solid_signed_volume")? < 0.0 {
55            flip_shell_faces(&mut solid.shells[shell_index])?;
56        }
57    }
58    Ok(())
59}
60
61/// Mint a vertex at every SELF-TOUCH of the source's faces before the shell
62/// reads their trims.
63///
64/// A face whose loops touch at an EDGE INTERIOR is a pinched region: the
65/// reported 2026-09-09 document's r = 6 through-hole kisses both r = 4 fillet
66/// setbacks on the top face, at (16, 20, 10) and (10, 20, 16), with no vertex
67/// there.  The fragment stage's 2D arrangement resolves such a pinch by
68/// carving the touched-off corner into its own region, whose loop walks the
69/// closed hole chain in a PARTIAL run — which `build_loop` can only assemble
70/// when the touch is a vertex of both touching edges, and otherwise refuses
71/// with "chain N fragmented into an incomplete run".
72///
73/// The boolean lane mints that vertex inside `build_imprints`
74/// (`imprint/self_touch.rs`).  Nothing minted it here: the shell fragments
75/// its SOURCE against an EMPTY imprint, and its offset carriers — whose trims
76/// are copied from the source faces — deliberately keep their boundaries
77/// un-split, so both arrived at the arrangement pinched.  Splitting the
78/// source once, before the carriers are built from it, fixes both: every
79/// carrier inherits the split trim by construction.
80///
81/// Returns `None` when no face self-touches, so every part that was never
82/// pinched keeps its exact previous path.  Escape hatch:
83/// `BREP_SELF_TOUCH_SPLIT=0`, the same one the imprint lane honours.
84fn split_self_touching_source(source: &BrepSolid) -> Result<Option<BrepSolid>, KernelRefusal> {
85    if std::env::var("BREP_SELF_TOUCH_SPLIT").as_deref() == Ok("0") {
86        return Ok(None);
87    }
88    // The same derivation `offset_shell_impl` uses for every other band, so
89    // the source scan and the carrier-pair scans agree on what "touching"
90    // means.
91    let scale = crate::solid_scale(source);
92    let tolerance = 1e-7f64.max(scale * 1e-9);
93    let edge_splits = crate::imprint::self_touch_edge_splits(source, SOURCE_OPERAND, tolerance, scale)?;
94    if edge_splits.is_empty() {
95        return Ok(None);
96    }
97    os_debug!(
98        "self-touch: source split on {} edge(s): {:?}",
99        edge_splits.len(),
100        edge_splits
101            .iter()
102            .map(|split| split.edge_id)
103            .collect::<Vec<_>>(),
104    );
105    let imprint = ImprintResultRecord {
106        edge_splits,
107        ..empty_imprint()
108    };
109    Ok(Some(apply_edge_splits(source, SOURCE_OPERAND, &imprint)?))
110}
111
112/// How far past the grown outline a planar opening wall that meets a RULED
113/// opening is padded, in units of the offset-skin band the wall selection reads
114/// (see the wall construction).
115///
116/// Measured on the torus wedge through the pipeline, grown by 0.05, 0.1, 0.5
117/// and 0.999 (band 2e-3): a clearance of 2 or 2.5 bands still shreds the cap
118/// into 22 to 36 faces with the area 5% to 11% high; from 4 bands on every
119/// member builds its 6 faces, and from 4 to 32 bands each member's volume moves
120/// by at most 1.2e-7. 16 sits four times above the first clean reading.
121const RULED_NEIGHBOUR_CLEARANCE_BANDS: f64 = 16.0;
122
123/// How far past its opening plane an inward carrier is grown, as a fraction of
124/// the shell distance (see the fall-short reach in the carrier loop).
125const REACH_CLEARANCE: f64 = 0.25;
126
127/// What the pipeline assembles.
128#[derive(Clone, Copy, Debug, Eq, PartialEq)]
129pub(super) enum Body {
130    /// A shell: the retained source faces, their offset skins and the walls
131    /// at the openings, bounding the material between source and offset.
132    Shell,
133    /// The offset body itself: the offset skins alone, closed by their
134    /// mutual sections; `opening_face_ids` are HELD faces, copied at
135    /// distance zero as walls, with no source face assembled and no skin
136    /// flipped. The whole-solid offset and the boolean fallback's offset
137    /// body are built this way.
138    Whole,
139}
140
141
142#[cfg(not(test))]
143fn forced_direct_refusal() -> Option<KernelRefusal> {
144    None
145}
146
147/// `BREP_OFFSET_EVERY_SKIN_PIECE` (default on; `=0` keeps the seed's one
148/// piece): see EVERY SKIN PIECE in the offset selection.
149fn every_skin_piece_enabled() -> bool {
150    crate::switch!("BREP_OFFSET_EVERY_SKIN_PIECE", true)
151}
152
153/// `BREP_OFFSET_EVERY_SEEDED_SKIN_PIECE` (default on; `=0` restores): when an
154/// inward shell's assembly fails, EVERY SKIN PIECE is retried on the seeded
155/// path too. Past 2.0 a reported box and pin model's bore skin comes apart into one piece
156/// per corner channel and the seed answered for one of them. Only as a retry:
157/// a shell the seed's choice closes keeps that answer.
158fn every_seeded_skin_piece_enabled() -> bool {
159    crate::switch!("BREP_OFFSET_EVERY_SEEDED_SKIN_PIECE", true)
160}
161
162/// `BREP_OFFSET_WALL_INSIDE_SOURCE_LANE` (default on; `=0` restores): an
163/// outward shell whose wall selection keeps a fragment inside the source
164/// refuses by name (`offset_shell_wall_inside_source`), which takes the boolean
165/// lane, instead of returning a shell with a fin in it.
166fn wall_inside_source_lane_on() -> bool {
167    crate::switch!("BREP_OFFSET_WALL_INSIDE_SOURCE_LANE", true)
168}
169
170pub fn offset_shell(
171    source: &BrepSolid,
172    opening_face_ids: &[u64],
173    distance: f64,
174) -> Result<OffsetShellResultRecord, KernelRefusal> {
175    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
176        let mut record = offset_shell(&scaled.source, opening_face_ids, scaled.distance).map_err(|error| scaled.refusal(error))?;
177        record.solid = scaled.back(&record.solid, "offset_shell")?;
178        return Ok(record);
179    }
180    let direct = match forced_direct_refusal() {
181        Some(forced) => Err(forced),
182        None => offset_body(source, opening_face_ids, distance, Body::Shell, "offset_shell"),
183    };
184    let mut shelled = offset_shell_lanes(source, opening_face_ids, distance, direct)?;
185    if membrane_shells_on() {
186        drop_folded_shells(&mut shelled.solid, distance);
187        let membranes = membrane_shell_indices(&shelled.solid, distance);
188        let paired = paired_face_ids(&shelled.solid);
189        if !membranes.is_empty() || !paired.is_empty() {
190            for (first, second) in &paired {
191                let shell = shelled.solid.shells.iter().position(|shell| shell.faces.iter().any(|face| face.id == *first));
192                os_debug!(
193                    "membrane pair: faces {first} and {second} in shell {shell:?} of {:?} faces",
194                    shell.map(|index| shelled.solid.shells[index].faces.len())
195                );
196            }
197            return Err(KernelRefusal::unsupported(KernelStage::Validate, "offset_shell_membrane", format!(
198                "offset_shell: at this distance the result has {} shell(s) enclosing no volume and \
199                 {} pair(s) of faces bounded by the same edges{} (zero-thickness membranes \
200                 beside the cavity), which no solid carries",
201                membranes.len(),
202                paired.len(),
203                paired.first().map(|(a, b)| format!(", first faces {a} and {b}")).unwrap_or_default()
204            )));
205        }
206    }
207    Ok(shelled)
208}
209
210/// `BREP_OFFSET_MEMBRANE_SHELLS` (default on; `=0` restores): a shell of the
211/// result that encloses nothing (made only of FOLDED faces, each loop running
212/// along its edges once in each direction, closed by point edges; or of zero
213/// volume over its area; or a bag, its faces pairing up on the same edges) is
214/// removed with the edges and vertices only it used, when the
215/// rest still validates. Otherwise, and for two faces of one real shell bounded
216/// by the same edges (a zero-thickness fin), the shell is refused as a
217/// membrane.
218///
219/// Cause (a reported box and pin model): at 2.38 and 2.40 the result reported
220/// three shells, two of them single folded faces of about 6.5e-6 mm^2 at the
221/// floor/wall corner; at 2.46 (with the corner-debris switch) six more, folded
222/// faces and two-face bags of volume 1e-8 over area 4e-3. None shares an edge
223/// with the cavity's shell. `validate()` accepts them all and the volume is
224/// right, but the shell count is not, nor is anything that walks the shells.
225///
226/// Every test is scaled by the offset distance, since a real piece of the shell
227/// is about |distance| thick: a folded or bag shell is removed only when its
228/// volume is at most 1% of |distance| × its area (a sphere face, whose seam
229/// also runs both ways, encloses the sealed cavity of a sphere-cut shell), and
230/// the zero-volume bar never exceeds 1e-3 × |distance| (a shell 1e-7 thick is
231/// a real sliver, not a membrane).
232fn membrane_shells_on() -> bool {
233    switch!("BREP_OFFSET_MEMBRANE_SHELLS", true)
234}
235
236/// Whether every non-degenerate edge of `face`'s loops is used once forward
237/// and once reversed by the face itself.
238fn face_is_folded(face: &FaceRecord, edges: &HashMap<u64, &EdgeRecord>) -> bool {
239    let mut balance: HashMap<u64, (usize, usize)> = HashMap::default();
240    for coedge in face.loops.iter().flat_map(|l| &l.coedges) {
241        if edges.get(&coedge.edge_id).is_some_and(|edge| edge.degenerate) {
242            continue;
243        }
244        let entry = balance.entry(coedge.edge_id).or_default();
245        if coedge.forward {
246            entry.0 += 1;
247        } else {
248            entry.1 += 1;
249        }
250    }
251    !balance.is_empty() && balance.values().all(|&(forward, reversed)| forward == 1 && reversed == 1)
252}
253
254/// Whether every face of `shell` shares its whole set of non-degenerate edges
255/// with exactly one other face of it: two-sided sheets with nothing between.
256fn shell_is_bag(shell: &ShellRecord, edges: &HashMap<u64, &EdgeRecord>) -> bool {
257    let mut sets: HashMap<Vec<u64>, usize> = HashMap::default();
258    for face in &shell.faces {
259        let mut set: Vec<u64> = face
260            .loops
261            .iter()
262            .flat_map(|l| &l.coedges)
263            .map(|coedge| coedge.edge_id)
264            .filter(|id| !edges.get(id).is_some_and(|edge| edge.degenerate))
265            .collect();
266        set.sort_unstable();
267        set.dedup();
268        if set.is_empty() {
269            return false;
270        }
271        *sets.entry(set).or_default() += 1;
272    }
273    !sets.is_empty() && sets.values().all(|&count| count == 2)
274}
275
276/// Removes the shells made only of folded faces, then the edges and vertices
277/// no remaining face uses. Keeps `solid` unchanged when that would leave no
278/// shell or a result that does not validate. A folded or bag shell qualifies
279/// only when its volume is at most 1% of |distance| × its area.
280pub fn drop_folded_shells(solid: &mut BrepSolid, distance: f64) {
281    let edges: HashMap<u64, &EdgeRecord> = solid.edges.iter().map(|edge| (edge.id, edge)).collect();
282    let empty = membrane_shell_indices(solid, distance);
283    let folded: Vec<usize> = (0..solid.shells.len())
284        .filter(|&index| {
285            let shell = &solid.shells[index];
286            empty.contains(&index)
287                || ((shell.faces.iter().all(|face| face_is_folded(face, &edges)) || shell_is_bag(shell, &edges))
288                    && shell_volume_and_area(solid, index)
289                        .is_some_and(|(volume, area)| volume.abs() <= 1e-2 * distance.abs() * area))
290        })
291        .collect();
292    if folded.is_empty() || folded.len() == solid.shells.len() {
293        return;
294    }
295    let mut trimmed = solid.clone();
296    let mut index = 0;
297    trimmed.shells.retain(|_| {
298        let keep = !folded.contains(&index);
299        index += 1;
300        keep
301    });
302    let used_edges: HashSet<u64> = trimmed
303        .shells
304        .iter()
305        .flat_map(|shell| &shell.faces)
306        .flat_map(|face| &face.loops)
307        .flat_map(|l| &l.coedges)
308        .map(|coedge| coedge.edge_id)
309        .collect();
310    trimmed.edges.retain(|edge| used_edges.contains(&edge.id));
311    let used_vertices: HashSet<u64> = trimmed
312        .edges
313        .iter()
314        .flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id])
315        .collect();
316    trimmed.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
317    crate::boolean::refresh_derived_genus(&mut trimmed);
318    let issues = trimmed.validate();
319    if !issues.is_empty() {
320        os_debug!("folded shells {folded:?} kept: without them the result does not validate: {issues:?}");
321        return;
322    }
323    os_debug!("dropped folded shells {folded:?}");
324    *solid = trimmed;
325}
326
327/// Pairs of faces of one shell bounded by exactly the same non-degenerate
328/// edges: two sides of a zero-thickness fin. By face id.
329pub fn paired_face_ids(solid: &BrepSolid) -> Vec<(u64, u64)> {
330    let mut pairs = Vec::new();
331    let degenerate: HashSet<u64> = solid.edges.iter().filter(|edge| edge.degenerate).map(|edge| edge.id).collect();
332    for shell in &solid.shells {
333        let mut seen: HashMap<Vec<u64>, u64> = HashMap::default();
334        for face in &shell.faces {
335            let mut edges: Vec<u64> = face
336                .loops
337                .iter()
338                .flat_map(|l| &l.coedges)
339                .map(|c| c.edge_id)
340                .filter(|id| !degenerate.contains(id))
341                .collect();
342            edges.sort_unstable();
343            if edges.len() < 2 {
344                continue;
345            }
346            match seen.get(&edges) {
347                Some(&other) => pairs.push((other, face.id)),
348                None => {
349                    seen.insert(edges, face.id);
350                }
351            }
352        }
353    }
354    pairs
355}
356
357/// The volume and area of shell `index` of `solid` on its own.
358fn shell_volume_and_area(solid: &BrepSolid, index: usize) -> Option<(f64, f64)> {
359    let mut alone = solid.clone();
360    alone.shells = vec![solid.shells[index].clone()];
361    crate::solid_mass_properties(&alone).ok().map(|mass| (mass.volume, mass.surface_area))
362}
363
364/// The shells of `solid` that enclose no volume, by index: |V| at most
365/// min(1e-6 × the bounding-box diagonal, 1e-3 × |distance|) × the shell's
366/// area. A shell whose mass properties cannot be measured is never reported.
367pub fn membrane_shell_indices(solid: &BrepSolid, distance: f64) -> Vec<usize> {
368    if solid.vertices.is_empty() {
369        return Vec::new();
370    }
371    let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
372    let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
373    for vertex in &solid.vertices {
374        lo = Vec3::new(lo.x.min(vertex.point.x), lo.y.min(vertex.point.y), lo.z.min(vertex.point.z));
375        hi = Vec3::new(hi.x.max(vertex.point.x), hi.y.max(vertex.point.y), hi.z.max(vertex.point.z));
376    }
377    let thickness = (1e-6 * hi.sub(lo).length()).min(1e-3 * distance.abs());
378    (0..solid.shells.len())
379        .filter(|&index| {
380            shell_volume_and_area(solid, index).is_some_and(|(volume, area)| volume.abs() <= thickness * area)
381        })
382        .collect()
383}
384
385fn offset_shell_lanes(
386    source: &BrepSolid,
387    opening_face_ids: &[u64],
388    distance: f64,
389    direct: Result<OffsetShellResultRecord, KernelRefusal>,
390) -> Result<OffsetShellResultRecord, KernelRefusal> {
391    match direct {
392        Ok(result) => Ok(result),
393        // The boolean lane answers the direct construction's own named
394        // refusals; when it refuses too, the direct refusal is the one
395        // reported, because it names the cause.
396        Err(direct) if super::solid::direct_refusal_takes_the_boolean_lane(&direct) => {
397            os_debug!("direct pipeline refused ({direct}); taking the boolean lane");
398            match super::solid::offset_shell_by_boolean(source, opening_face_ids, distance) {
399                Ok(result) => Ok(result),
400                Err(boolean) => {
401                    os_debug!("boolean lane refused too ({boolean})");
402                    // An outward wall through a curved opening on a sphere or
403                    // a cylinder: the grown body cut by the opening's own
404                    // surface (`opening_surface_cut`).
405                    if distance < 0.0
406                        && super::opening_surface_cut::answers(&direct)
407                        && super::opening_surface_cut::opening_surface_cut_on()
408                    {
409                        match super::opening_surface_cut::build(source, opening_face_ids, distance) {
410                            Ok(result) => return Ok(result),
411                            Err(cut) => os_debug!("opening-surface cut refused too ({cut})"),
412                        }
413                    }
414                    Err(direct)
415                }
416            }
417        }
418        Err(direct) => Err(direct),
419    }
420}
421
422/// The pipeline's one timed entry: `offset_shell` and `offset_solid` both run
423/// through it, so the `timing.*` split and the acceptance step are the same.
424/// Lane O row 38's switch, default on since batch 17 (`0`/`off` restores the fit): it asks the offset pipeline's
425/// imprints for the planar-iso lane's exact pcurves (`ImprintOptions::
426/// exact_iso_pcurves`, parity slice 1): a section the lane answers is an
427/// iso-curve of the ruled carrier and an affine image on the plane, so its
428/// pcurves are written down instead of fitted. Booleans keep their own
429/// default; `BREP_EXACT_ISO_PCURVES` still overrides every imprint.
430fn offset_exact_iso_pcurves_on() -> bool {
431    switch!("BREP_OFFSET_EXACT_ISO_PCURVES", true)
432}
433
434
435pub(super) fn offset_body(
436    source: &BrepSolid,
437    opening_face_ids: &[u64],
438    distance: f64,
439    body: Body,
440    entry: &str,
441) -> Result<OffsetShellResultRecord, KernelRefusal> {
442    profile::reset();
443    // Lane P3b row 3: one stderr write per operation for every profile line
444    // emitted below (`crate::imprint::ProfileSink`).
445    let _profile_sink = crate::imprint::ProfileSink::open();
446    let started = web_time::Instant::now();
447    let result = offset_shell_any_lane(source, opening_face_ids, distance, body).and_then(|result| {
448        let mut clock = web_time::Instant::now();
449        let connected = outward_shell_is_connected(source, distance, &result);
450        profile::lap(&mut clock, profile::ACCEPTANCE);
451        connected.map(|()| result)
452    });
453    profile::add(profile::TOTAL, started.elapsed());
454    profile::report(entry);
455    result
456}
457
458/// Every shell of an OUTWARD result must bound volume. The shell is the grown
459/// body less the source with the openings held, so it can be disconnected
460/// (opening a cylinder's lateral face leaves its two grown caps as two
461/// slabs), but each of its shells encloses material. A shell that encloses
462/// none, a lone face that happened to close, is a fragment of an assembly that
463/// went wrong and still validated. Measured on 2026-09-26: a free-form D whose
464/// fitted opening wall sat within the fit tolerance of its carriers' sections
465/// returned its body plus 62 single-face shells of volume under 3e-24, each
466/// valid, with the right total volume. So this refuses by name for EVERY
467/// outward shell, not only for the lane that produced those.
468pub fn outward_shell_is_connected(
469    source: &BrepSolid,
470    distance: f64,
471    result: &OffsetShellResultRecord,
472) -> Result<(), KernelRefusal> {
473    if distance >= 0.0 || result.solid.shells.len() <= 1 {
474        return Ok(());
475    }
476    let scale = crate::solid_scale(source).max(1.0);
477    let volumes = result
478        .solid
479        .shells
480        .iter()
481        .map(|shell| {
482            let mut one = result.solid.clone();
483            one.shells = vec![shell.clone()];
484            crate::solid_mass_properties(&one)
485                .map(|properties| properties.volume)
486                .or_refuse(KernelStage::Validate, "solid_mass_properties")
487        })
488        .collect::<Result<Vec<f64>, KernelRefusal>>()?;
489    let total = volumes.iter().map(|volume| volume.abs()).sum::<f64>();
490    let floor = (1e-9 * total).max(1e-12 * scale * scale * scale);
491    let empty = volumes.iter().filter(|volume| volume.abs() <= floor).count();
492    if empty == 0 {
493        return Ok(());
494    }
495    Err(refusals::empty_shell(result.solid.shells.len(), empty, floor).into())
496}
497
498fn offset_shell_any_lane(
499    source: &BrepSolid,
500    opening_face_ids: &[u64],
501    distance: f64,
502    body: Body,
503) -> Result<OffsetShellResultRecord, KernelRefusal> {
504    // Pinched source faces are un-modellable by the arrangement until the
505    // touch is a vertex; do it once here so BOTH `offset_shell_impl` attempts
506    // and every carrier built from the source see the same topology.
507    let prepared = split_self_touching_source(source)?;
508    let source = prepared.as_ref().unwrap_or(source);
509    // The revolved-wedge lane answers a SHELL question (the material between
510    // a revolve and its grown image); the offset body takes the pipeline.
511    if body == Body::Whole {
512        // Row 36 (`BREP_OFFSET_SPHERE_BODY`, default off): the offset body of a
513        // ball is the ball scaled about its centre (`sphere_body.rs`); it
514        // declines to the pipeline on anything else.
515        if opening_face_ids.is_empty() {
516            if let Some(result) = sphere_body::sphere_body(source, distance) {
517                return Ok(result);
518            }
519            // `BREP_OFFSET_TORUS_APPLE` (default on; `=0` restores): a whole torus grown
520            // past its hole is the revolved apple (`torus_body.rs`).
521            if let Some(result) = super::torus_body::torus_apple(source, distance) {
522                return Ok(result);
523            }
524        }
525        return imprint_attempts(source, opening_face_ids, distance, body);
526    }
527    // An outward shell of the one circular face of a partial revolve is planar
528    // in the meridian half-plane, fold band and all: build it there and revolve
529    // it once (`revolved_wedge.rs`). Anything else declines and takes the
530    // imprint pipeline, unchanged.
531    if let Some(result) = revolved_wedge::retained_cap_shell(source, opening_face_ids, distance) {
532        return Ok(result);
533    }
534    match revolved_wedge::recognize(source, opening_face_ids, distance) {
535        Ok(revolved_wedge::Recognition::Wedge(wedge)) => {
536            os_debug!("revolved wedge lane: {}", wedge.report());
537            return revolved_wedge::build(&wedge, source);
538        }
539        Ok(revolved_wedge::Recognition::Declined(reason)) => {
540            os_debug!("revolved wedge lane declined: {reason}");
541        }
542        // A source the lane cannot even read is not one it takes; the pipeline
543        // owns every refusal.
544        Err(error) => {
545            os_debug!("revolved wedge lane declined: could not read the source ({error})");
546        }
547    }
548    // `BREP_OFFSET_SPHERE_CUT_SHELL` (default on; `=0` restores): an inward shell of a ball cut by
549    // planes is the source less the moved ball cut by the moved planes
550    // (`sphere_cut_shell.rs`); it declines to the pipeline on anything else.
551    if let Some(result) = sphere_cut_shell::sphere_cut_shell(source, opening_face_ids, distance) {
552        return Ok(result);
553    }
554    // Row 32 (`BREP_OFFSET_PLANAR_SHELL`, default on; `=0` restores): an outward shell of a
555    // convex polyhedron in closed form (`planar_shell.rs`); it declines to the
556    // pipeline on anything else.
557    if let Some(result) = planar_shell::planar_shell(source, opening_face_ids, distance) {
558        return Ok(result);
559    }
560    imprint_attempts(source, opening_face_ids, distance, body)
561}
562
563
564fn imprint_attempts(
565    source: &BrepSolid,
566    opening_face_ids: &[u64],
567    distance: f64,
568    body: Body,
569) -> Result<OffsetShellResultRecord, KernelRefusal> {
570    // An OUTWARD pass that refused after holding back a concave side runs once
571    // more with it continued round its arc (`concave_arc_retry_on`); the
572    // first refusal stands if that fails too.
573    let held = super::outward_side_widen::concave_held();
574    let first = imprint_attempts_once(source, opening_face_ids, distance, body);
575    match first {
576        Err(error) if distance < 0.0 || body == Body::Whole => {
577            if !super::outward_side_widen::concave_arc_retry_on() || super::outward_side_widen::concave_held() == held {
578                return Err(error);
579            }
580            os_debug!("outward pass refused with concave sides held back ({error}); retrying with them continued round their arc");
581            match super::outward_side_widen::with_concave_arc(|| imprint_attempts_once(source, opening_face_ids, distance, body)) {
582                Ok(result) => Ok(result),
583                Err(_) => Err(error),
584            }
585        }
586        other => other,
587    }
588}
589
590fn imprint_attempts_once(
591    source: &BrepSolid,
592    opening_face_ids: &[u64],
593    distance: f64,
594    body: Body,
595) -> Result<OffsetShellResultRecord, KernelRefusal> {
596    // First try with oblique hole-wall carriers extended past their opening
597    // planes (the lane that closes tilted/conical through-holes). If that
598    // extension fired but the arrangement could not assemble the harder
599    // configuration it produced (e.g. the extended bore genuinely intersects
600    // other offset walls), fall back to the un-extended pipeline so every
601    // previously-supported shape keeps its exact path and every refusal keeps
602    // the canonical honesty-gate message.
603    let mut extension_fired = false;
604    let mut reflex_rebuilds = 0usize;
605    let mut shadowed_points = Vec::new();
606    let mut omitted = HashSet::default();
607    let mut vacated_notes = Vec::new();
608    let result = match offset_shell_impl(
609        source,
610        opening_face_ids,
611        distance,
612        body,
613        true,
614        &mut extension_fired,
615        &mut reflex_rebuilds,
616        &HashSet::default(),
617        &HashSet::default(),
618        false,
619        &mut shadowed_points,
620        &mut omitted,
621        &mut vacated_notes,
622    ) {
623        Ok(result) => {
624            // Attribution marker: which pipeline produced this result. A
625            // retry-produced Ok can silently mask a broken extension lane —
626            // always say which attempt won. The reflex-rebuild count rides
627            // along because that lane fires on BOTH attempts: "extension
628            // idle" alone would misread as "the plain pipeline did this".
629            os_debug!(
630                "offset_shell result: FIRST attempt (extension {}, reflex-rebuilt {})",
631                if extension_fired { "fired" } else { "idle" },
632                reflex_rebuilds,
633            );
634            Ok(result)
635        }
636        Err(error) if extension_fired => {
637            os_debug!("extended pipeline failed ({error}); retrying without carrier extension");
638            let mut unused = false;
639            let mut retry_reflex = 0usize;
640            shadowed_points.clear();
641            omitted.clear();
642            let retried = offset_shell_impl(
643                source,
644                opening_face_ids,
645                distance,
646                body,
647                false,
648                &mut unused,
649                &mut retry_reflex,
650                &HashSet::default(),
651                &HashSet::default(),
652                false,
653                &mut shadowed_points,
654                &mut omitted,
655                &mut vacated_notes,
656            );
657            os_debug!(
658                "offset_shell result: RETRY without extension ({}, reflex-rebuilt {retry_reflex})",
659                if retried.is_ok() { "ok" } else { "err" },
660            );
661            retried
662        }
663        Err(error) => Err(error),
664    };
665    // A refusal from a shell whose selection saw two offsets CROSS inside
666    // material thinner than twice the distance says so first: a rib thinner
667    // than 2d shelled inward is that configuration, and the assembly's own
668    // message names only the symptom. A refusal that already names its cause
669    // keeps it. The crossing is looked for here, on the failure path only.
670    match result {
671        // A refusal that already names its CAUSE keeps its own sentence; one
672        // that names a symptom ("connector edge left its plane", an assembly
673        // message) is worth a cause in front of it. Reading the whole prefix as
674        // "anything this module wrote" was too wide: the twin bosses came out
675        // led by a notch sentence when their cause was the shadow cascade, and
676        // the partial cone lost its junction cause behind a connector's.
677        // Each cause is put IN FRONT of the symptom with `with_message`, so the
678        // symptom's class (an assembly's `NonIntegralGenus`, …) survives.
679        Err(error) if !refusal_names_its_cause(&error.message) => {
680            let crossing = name_offset_crossing(source, opening_face_ids, distance, &shadowed_points);
681            let junction = crossing
682                .is_none()
683                .then(|| name_retained_opening_junction(source, opening_face_ids, distance))
684                .flatten();
685            Err(cause_in_front(error, crossing, junction, vacated_notes.first()))
686        }
687        result => result,
688    }
689}
690
691/// The symptom `error` with the first named cause IN FRONT of it: an offset
692/// crossing, else a retained/opening junction, else a vacated rim's note.
693/// Each prefix is a `with_message`, so the symptom's CLASS (an assembly's
694/// `NonIntegralGenus`, …) survives the sentence put before it.
695pub fn cause_in_front(
696    error: KernelRefusal,
697    crossing: Option<String>,
698    junction: Option<String>,
699    note: Option<&String>,
700) -> KernelRefusal {
701    if let Some(crossing) = crossing {
702        return error.with_message(|error| {
703            format!(
704                "offset_shell: {crossing}; a skin partly shadowed that way is not yet \
705                 assembled ({error})"
706            )
707        });
708    }
709    if let Some(junction) = junction {
710        return error.with_message(|error| format!("offset_shell: {junction} ({error})"));
711    }
712    // A rim the closure could not bridge, with what it measured, in front of
713    // whatever the assembly then said about the hole it left.
714    match note {
715        Some(note) => error.with_message(|error| {
716            format!(
717                "offset_shell: a rim vacated by an omitted support was left open — {note} \
718                 ({error})"
719            )
720        }),
721        None => error,
722    }
723}
724
725/// The refusals this module's own cause-naming lanes produce. Anything else is
726/// a symptom another stage reported, and takes a cause in front of it.
727fn refusal_names_its_cause(error: &str) -> bool {
728    [
729        " coincide near ",
730        " touch tangentially near ",
731        "is sealed off from the opening",
732        "cannot tell whether",
733        "omitting the shadowed offsets of source faces",
734        "reads shadowed over its whole extent, so omitting it again",
735        "nested passes without settling",
736        "no retained face keeps any offset skin",
737        "is shadowed at every one of its",
738        "a rim vacated by an omitted support was left open",
739        "junction, so its offset ends inside the cavity",
740        "cross near",
741        "which meet tangentially along source edge",
742        // The opening-wall lane's own named refusals, so a cause of mine never
743        // arrives in front of one of theirs.
744        "folds where the carve",
745        "is curved and not a ruled surface",
746        "cannot be built",
747    ]
748    .iter()
749    .any(|name| error.contains(name))
750}
751
752/// The deepest nesting of `offset_shell_impl` passes one shell may take.
753/// Every re-run changes an input that only grows (the omitted supports, the
754/// cavity bounds, the every-seed flag), so the depth is bounded by the face
755/// count already; this bound makes a re-run that fails to grow its input a
756/// named refusal instead of a stack overflow, whatever the cause.
757pub(super) const MAXIMUM_PASS_DEPTH: usize = 24;
758
759std::thread_local! {
760    static PASS_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
761}
762
763/// One nested pass, counted while it lives.
764struct PassDepth;
765
766impl PassDepth {
767    fn enter() -> Result<Self, KernelRefusal> {
768        let depth = PASS_DEPTH.with(|cell| {
769            let depth = cell.get() + 1;
770            cell.set(depth);
771            depth
772        });
773        let pass = PassDepth;
774        if depth > MAXIMUM_PASS_DEPTH {
775            return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::PASS_BUDGET, format!(
776                "offset_shell: the construction re-ran {MAXIMUM_PASS_DEPTH} nested passes without settling \
777                 which offset supports to omit"
778            )));
779        }
780        Ok(pass)
781    }
782}
783
784impl Drop for PassDepth {
785    fn drop(&mut self) {
786        PASS_DEPTH.with(|cell| cell.set(cell.get().saturating_sub(1)));
787    }
788}
789
790
791
792fn offset_shell_impl(
793    source: &BrepSolid,
794    opening_face_ids: &[u64],
795    distance: f64,
796    body: Body,
797    extend_oblique_carriers: bool,
798    extension_fired: &mut bool,
799    reflex_rebuilds: &mut usize,
800    shadowed_supports: &HashSet<u64>,
801    cavity_bounds: &HashSet<u64>,
802    every_seeded_piece: bool,
803    shadowed_points: &mut Vec<(Vec3, u64)>,
804    omitted_supports: &mut HashSet<u64>,
805    vacated_notes: &mut Vec<String>,
806) -> Result<OffsetShellResultRecord, KernelRefusal> {
807    let _pass = PassDepth::enter()?;
808    profile::attempt();
809    let _sharp_rims = super::carriers::SharpOpeningRims::set(if super::carriers::ruled_miter_on() {
810        super::carriers::sharp_opening_rims(source, opening_face_ids)
811    } else {
812        HashSet::default()
813    });
814    let mut clock = web_time::Instant::now();
815    omitted_supports.clone_from(shadowed_supports);
816    vacated_notes.clear();
817    if !distance.is_finite() || distance.abs() <= MINIMUM_DISTANCE {
818        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_distance", "offset_shell: distance must be finite and non-zero"));
819    }
820    if opening_face_ids.is_empty() && body == Body::Shell {
821        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_no_opening", "offset_shell: at least one opening face is required"));
822    }
823    let source_faces = source
824        .shells
825        .iter()
826        .flat_map(|shell| &shell.faces)
827        .collect::<Vec<_>>();
828    let opening_set = opening_face_ids.iter().copied().collect::<HashSet<_>>();
829    if opening_set
830        .iter()
831        .any(|id| !source_faces.iter().any(|face| face.id == *id))
832    {
833        return Err(KernelRefusal::input(KernelStage::Collect, "offset_shell_foreign_opening", "offset_shell: opening face does not belong to source"));
834    }
835    let retained = source_faces
836        .iter()
837        .filter(|face| !opening_set.contains(&face.id))
838        .map(|face| face.id)
839        .collect::<Vec<_>>();
840    if retained.is_empty() {
841        return Err(refusals::no_retained_face().into());
842    }
843    let mut carriers = Vec::new();
844    let mut open_section_reach = false;
845    if distance < 0.0 && std::env::var("BREP_OFFSET_OPEN_SECTION_REACH").as_deref() != Ok("0") {
846        for face in &source_faces {
847            if retained.contains(&face.id) && open_profile_has_construction_headroom(face)? {
848                open_section_reach = true;
849                break;
850            }
851        }
852    }
853    // Faces whose folded part was carved away, by source face id. Later stages
854    // that read a retained face's TRIM — the apex-cap scan below is the one —
855    // must read the carved trim, not the one the source still carries.
856    let mut carved_supports = HashMap::<u64, FaceRecord>::default();
857    // Lane O item 705: (neighbour face, opening face, rim edge) of every
858    // tangent junction with a curved opening the neighbour cannot reach.
859    let mut tangent_rim_rounds: Vec<(u64, u64, u64)> = Vec::new();
860    // Supports omitted because their offset collapsed (`planar_rim_tube`).
861    let mut collapsed_supports: Vec<u64> = Vec::new();
862    // The carriers that are such tubes, by index, with the opening each
863    // tube's mouth lies on.
864    let mut rim_tubes: HashMap<usize, u64> = HashMap::default();
865    // The tubes of SURVIVING rounds, by carrier index: such a tube rides its
866    // round's id, so reading it shadowed must drop only the tube, never the
867    // round's own offset.
868    let mut surviving_tubes = HashSet::<usize>::default();
869    let mut shielded_cusps = HashSet::<u64>::default();
870
871    for face_id in &retained {
872        let face = source_faces.iter().find(|face| face.id == *face_id).unwrap();
873        profile::lap(&mut clock, profile::CARRIER_TRIM);
874        let collapsed = profile::detail("offset_support_collapsed", || offset_support_collapsed(face, distance))?;
875        profile::lap(&mut clock, profile::CARRIER_REGULARITY);
876        if collapsed {
877            os_debug!("omitting collapsed offset support for source face {face_id}");
878            collapsed_supports.push(*face_id);
879            continue;
880        }
881        // A support a previous pass found SHADOWED contributes no skin, and its
882        // carrier must not imprint its neighbours either — see the selection.
883        if shadowed_supports.contains(face_id) {
884            os_debug!("omitting shadowed offset support for source face {face_id}");
885            continue;
886        }
887        // A planar carrier whose source face meets a neighbour at a REFLEX
888        // (concave) edge extends its trim by |distance|: at such a junction
889        // the offset skin must GROW past the source footprint to meet the
890        // neighbour's offset (a pocket wall's source [5,15] → skin
891        // [3.5,16.5]); a source-sized trim leaves a gap no miter can bridge.
892        // The surplus at the face's convex ends is clipped by the imprints +
893        // on-skin filter. Convex-only faces keep their exact source-sized
894        // trim — extending them perturbs delicately-selected fragment
895        // landscapes for no benefit.
896        let miter = source_faces
897            .iter()
898            .find(|face| face.id == *face_id)
899            .map(|face| face_reflex_miter_tan(source, face))
900            .transpose()?
901            .flatten();
902        // The offsets of two faces joined at a reflex edge meet d·tan(θn/2)
903        // past the source rim — d only for a perpendicular join. Scale the
904        // extension to the worst sampled miter (×1.5 headroom so the true
905        // intersection lands strictly INSIDE the extended trim, never on its
906        // boundary where the arrangement drops boundary-coincident cuts) and
907        // cap it: a near-tangential join would ask for an unbounded trim.
908        let reflex_extension = miter.map(|worst_tan| {
909            (distance.abs() * worst_tan * 1.5)
910                .max(distance.abs())
911                .min(distance.abs() * 12.0)
912        });
913        if let Some(extension) = reflex_extension {
914            os_debug!("carrier for src face {face_id}: reflex-extended by {extension:.4}");
915        }
916        // OUTWARD: every retained carrier grows by |distance| across its
917        // sharp and opening-facing sides (the offsets of a convex junction
918        // meet past both source rims; a wall plane cuts the surplus), and
919        // by nothing across a smooth junction into a retained neighbour —
920        // see `outward_carrier_extension`. A reflex junction needs no
921        // outward growth at all (those offsets cross inside the trims).
922        let mut curved_reach = None;
923        let planar_reach = planar_opening_reach(face, &source_faces, &opening_set, distance)?;
924        let mut thin_padded = false;
925        let extension = if distance < 0.0 {
926            outward_carrier_extension(source, face, &source_faces, &opening_set, distance.abs())?
927        } else {
928            let mut inward = crate::CarrierExtension::uniform(reflex_extension.unwrap_or(0.0));
929            // Only a carrier that becomes its trim box's full rectangle (an
930            // affine plane with a curved outline element, below) has the box's
931            // room past a reflex rim INSIDE the box; a slid trim (a straight
932            // L-shaped outline) needs every side's pad for its inner corners.
933            if reflex_extension.is_some()
934                && super::carrier_rebuild::reflex_pad_convex_sides_on()
935                && face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
936                && outline_has_curved_element(source, face)?
937            {
938                let [u_min, u_max, v_min, v_max] = super::carrier_rebuild::convex_box_sides(source, face, reflex_extension.unwrap_or(0.0))?;
939                // Never every side: an all-zero extension is not a carrier
940                // the size of its trim but NO slide at all, which leaves an
941                // affine plane at its whole source net (a boss's floor, a
942                // third of its plane's domain, ran far past its convex rims
943                // and the shell crossed itself). A face
944                // whose sides are all convex keeps the uniform pad.
945                if !(u_min && u_max && v_min && v_max) {
946                    if u_min { inward.u_min = 0.0; }
947                    if u_max { inward.u_max = 0.0; }
948                    if v_min { inward.v_min = 0.0; }
949                    if v_max { inward.v_max = 0.0; }
950                }
951                os_debug!("carrier for src face {face_id}: reflex pad u=({:.4},{:.4}) v=({:.4},{:.4})", inward.u_min, inward.u_max, inward.v_min, inward.v_max);
952            }
953            // `BREP_OFFSET_THIN_SKIN_PAD` (default on; `=0` restores): a skin thinner than
954            // the fragmenter's graze band is padded past its source rims
955            // (`thin_skin_pad`), so its sections end far from its corners.
956            if let Some(pad) = thin_skin_pad(source, face, distance)? {
957                inward = crate::CarrierExtension { u_min: inward.u_min.max(pad), u_max: inward.u_max.max(pad), v_min: inward.v_min.max(pad), v_max: inward.v_max.max(pad) };
958                os_debug!("carrier for src face {face_id}: thin skin padded by {pad:.6}");
959                thin_padded = true;
960            }
961            if let Some(reach) = planar_reach {
962                let grown = reach + REACH_CLEARANCE * distance;
963                inward = crate::CarrierExtension { u_min: inward.u_min.max(grown), u_max: inward.u_max.max(grown), v_min: inward.v_min.max(grown), v_max: inward.v_max.max(grown) };
964                os_debug!("carrier for src face {face_id}: planar reach to its opening {reach:.6}");
965            }
966            if reflex_extension.is_some() {
967                let [u_min, u_max, v_min, v_max] =
968                    apex_corner_reach(source, face, &source_faces, &opening_set, distance)?;
969                if u_min.max(u_max).max(v_min).max(v_max) > 0.0 {
970                    inward.u_min = inward.u_min.max(u_min);
971                    inward.u_max = inward.u_max.max(u_max);
972                    inward.v_min = inward.v_min.max(v_min);
973                    inward.v_max = inward.v_max.max(v_max);
974                    os_debug!(
975                        "carrier for src face {face_id}: apex corner reach u=({:.4},{:.4}) v=({:.4},{:.4})",
976                        inward.u_min, inward.u_max, inward.v_min, inward.v_max,
977                    );
978                }
979            }
980            // An INWARD carrier that falls short of the planar opening it meets
981            // is grown until it crosses that plane, so the imprint cuts the
982            // skin there instead of leaving a rim for the ruled weld to cork
983            // below the opening (`fallshort_opening_reach`).
984            if let Some((at_v_max, reach)) =
985                fallshort_opening_reach(source, face, &source_faces, &opening_set, distance)?
986            {
987                // Past the plane by a quarter of the shell's own thickness, so
988                // the section is strictly inside the carrier's trim rather than
989                // on its boundary. Measured 2026-09-17 over the offset-shell
990                // suite: every fraction from 0.01 to 2.0 of |d| gives the same
991                // 73 passing members, while a margin sized in COINCIDENCE BANDS
992                // (1 to 32 of them, 2e-5 each here) breaks the sphere-under-
993                // frustum member by 9.4e-2 — the fragile margins are the ones
994                // far below the construction's own length.
995                let grown = reach + REACH_CLEARANCE * distance.abs();
996                if at_v_max {
997                    inward.v_max = inward.v_max.max(grown);
998                } else {
999                    inward.v_min = inward.v_min.max(grown);
1000                }
1001                os_debug!(
1002                    "carrier for src face {face_id}: inward reach to its opening plane {reach:.6}                      at v_{} ",
1003                    if at_v_max { "max" } else { "min" },
1004                );
1005            }
1006            // A CURVED opening has no such construction, and the pipeline
1007            // closes the cavity with whatever completion reaches for: measured
1008            // 7.6% short on the hemisphere cup shelled through its dome.
1009            if let Some((opening, gap)) =
1010                offset_falls_short_of_curved_opening(source, face, &source_faces, &opening_set, distance)?
1011            {
1012                if std::env::var("BREP_OFFSET_CURVED_REACH").as_deref() != Ok("0") {
1013                    curved_reach = curved_opening_reach_source(source, face, distance)?;
1014                }
1015                // `BREP_OFFSET_CURVED_RULED_REACH` (default on; `=0` restores): where the
1016                // rectangle continuation declines (a u-closed band, a tangent
1017                // junction), a v-ruled carrier is grown along its rulings
1018                // until it crosses the curved opening, as the planar reach
1019                // does for a plane (`curved_fallshort_reach`).
1020                let mut ruled_reach = false;
1021                if curved_reach.is_none() {
1022                    if let Some((at_v_max, reach)) =
1023                        curved_fallshort_reach(source, face, &source_faces, &opening_set, distance)?
1024                    {
1025                        let grown = reach + REACH_CLEARANCE * distance.abs();
1026                        if at_v_max {
1027                            inward.v_max = inward.v_max.max(grown);
1028                        } else {
1029                            inward.v_min = inward.v_min.max(grown);
1030                        }
1031                        ruled_reach = true;
1032                        os_debug!(
1033                            "carrier for src face {face_id}: ruled reach to its curved opening {opening} {reach:.6} at v_{}",
1034                            if at_v_max { "max" } else { "min" },
1035                        );
1036                    }
1037                }
1038                // Lane O item 705 (`BREP_OFFSET_TANGENT_RIM_ROUND`, default off):
1039                // a face that meets its curved opening TANGENTIALLY never
1040                // reaches it — its skin runs parallel to the opening at
1041                // exactly d — and the wall there is a round of radius d about
1042                // the rim (`rim_round.rs`). Record the rim; the round carrier
1043                // is emitted beside the apex caps, and this face's carrier is
1044                // built as it is.
1045                if curved_reach.is_none() && !ruled_reach && super::rim_round::tangent_rim_round_enabled() {
1046                    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1047                        let Some((mate, mate_use)) = junction_mate(&source_faces, face, coedge.edge_id) else {
1048                            continue;
1049                        };
1050                        if mate.id != opening || !uses_are_tangent(face, coedge, mate, mate_use)? {
1051                            continue;
1052                        }
1053                        os_debug!("tangent rim round: source face {face_id} meets opening {opening} tangentially along edge {}", coedge.edge_id);
1054                        tangent_rim_rounds.push((*face_id, opening, coedge.edge_id));
1055                    }
1056                }
1057                if curved_reach.is_none() && !ruled_reach && !tangent_rim_rounds.iter().any(|(id, _, _)| id == face_id) {
1058                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_curved_opening_short", format!(
1059                        "offset_shell: the offset skin of source face {face_id} stops {gap:.3e} short of \
1060                         curved opening face {opening}; only a planar opening's skin is grown to meet it"
1061                    )));
1062                }
1063            }
1064            inward
1065        };
1066        if distance < 0.0 {
1067            os_debug!(
1068                "carrier for src face {face_id}: outward extension u=({:.3},{:.3}) v=({:.3},{:.3})",
1069                extension.u_min,
1070                extension.u_max,
1071                extension.v_min,
1072                extension.v_max,
1073            );
1074        }
1075        // CARVE: a support whose offset folds over PART of its trim keeps the
1076        // regular part and drops the rest, instead of being built whole with
1077        // the fold in it. The carrier is built over the CARVED source, so the
1078        // trim it clones stops at the fold locus — and, because that trim no
1079        // longer reaches past the offset's pinch, `offset_surface`'s apex-cone
1080        // pinch retrim does not fire and the cloned pcurves still name the
1081        // pointwise offset.
1082        //
1083        // A carve that cannot be made is not a licence to build the folded
1084        // support anyway: the refusal is the answer, because a carrier with an
1085        // inverted patch in it welds into a shell that validates and bounds the
1086        // wrong solid.
1087        profile::lap(&mut clock, profile::CARRIER_TRIM);
1088        let carved = profile::detail("carve_folded_support", || carve_shell_support(source, face, distance, opening_face_ids))?;
1089        profile::lap(&mut clock, profile::CARRIER_REGULARITY);
1090        // A CUT RIM — the face's rim with a planar opening running across
1091        // its surface rather than along a v end — has the trim rebuilt over
1092        // the surface's full rectangle so the opening plane truncates the
1093        // offset skin (`cut_rim_full_rectangle_source`); like the carve, a
1094        // substitute source the carrier is built over.
1095        let cut_rim = if carved.is_none() && curved_reach.is_none() {
1096            cut_rim_full_rectangle_source(source, face, &source_faces, &opening_set, distance)?
1097        } else {
1098            None
1099        };
1100        // A curved face's SHARP outward u-side: the carrier is built over the
1101        // surface continued past it, so it reaches the mitre with its sharp
1102        // neighbour's offset (`sharp_side_continued_source`). Its INWARD
1103        // reflex u-side widens the trim inside the surface's own domain
1104        // instead (`reflex_side_widened_source`).
1105        let sharp_side = if carved.is_none() && cut_rim.is_none() && curved_reach.is_none() {
1106            match sharp_side_continued_source(source, face, &source_faces, &opening_set, distance, &extension)? {
1107                Some(continued) => Some(continued),
1108                None => match band_reach_continued_source(source, face, distance, &extension)? {
1109                    Some(widened) => Some(widened),
1110                    None => match reflex_side_widened_source(source, face, &source_faces, &opening_set, distance, &extension)? {
1111                        Some(widened) => Some(widened),
1112                        None => super::outward_side_widen::outward_sharp_side_widened_source(
1113                            source,
1114                            face,
1115                            &source_faces,
1116                            &opening_set,
1117                            distance,
1118                            &extension,
1119                        )?,
1120                    },
1121                },
1122            }
1123        } else {
1124            None
1125        };
1126        let carrier_source = match (&carved, &cut_rim) {
1127            (None, None) if curved_reach.is_some() => curved_reach.as_ref().unwrap(),
1128            (None, None) if sharp_side.is_some() => sharp_side.as_ref().unwrap(),
1129            (None, Some(rebuilt)) => rebuilt,
1130            (Some(carved), _) => {
1131                os_debug!(
1132                    "carving the fold off source face {face_id}: {:.1}% of its trim kept, \
1133                     {} new boundary pcurve(s)",
1134                    carved.kept_fraction * 100.0,
1135                    carved.fold_boundary
1136                );
1137                carved_supports.insert(*face_id, carved.face.clone());
1138                if carved.shielded_cusp {
1139                    shielded_cusps.insert(*face_id);
1140                }
1141                &carved.solid
1142            }
1143            (None, None) => source,
1144        };
1145        profile::lap(&mut clock, profile::CARRIER_TRIM);
1146        let (mut carrier, lane) = carrier_solid_sided_lane(carrier_source, *face_id, distance, &extension)?;
1147        os_debug!(
1148            "carrier for src face {face_id}: lane {lane:?} carved {} surface u {:?} v {:?} source face u {:?} v {:?}",
1149            carved.is_some(),
1150            carrier.shells[0].faces[0].surface.domain_u().ok(),
1151            carrier.shells[0].faces[0].surface.domain_v().ok(),
1152            carrier_source.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == *face_id).and_then(|f| f.surface.domain_u().ok()),
1153            carrier_source.shells.iter().flat_map(|shell| &shell.faces).find(|f| f.id == *face_id).and_then(|f| f.surface.domain_v().ok()),
1154        );
1155        profile::carrier_built(lane, clock.elapsed());
1156        clock = web_time::Instant::now();
1157        if (distance < 0.0 || reflex_extension.is_some()) && face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1158            // PADDED planes: the pad slides the plane's net while the trim's
1159            // loops are cloned in uv, so an INTERIOR loop (a bore or boss rim
1160            // in the face) is carried outward with the grown outline instead
1161            // of following the neighbour's offset.
1162            //   OUTWARD: a bore's rim grew (r=4.68 → 5.15) while the shrunk
1163            //   offset bore (r=3.68) that must hole this plane fell inside the
1164            //   enlarged void, so neither the imprint nor the orphan-rim weld
1165            //   could cut it.
1166            //   INWARD, reflex-extended: the same slide moves a REFLEX hole
1167            //   rim the wrong way — a sphere sitting under a frustum's base
1168            //   annulus (the user's 2026-09-07 document) had its r=8.3 rim
1169            //   scaled to 9.22 while the shrunk offset sphere (r=7.3) crosses
1170            //   the offset plane at r=7.23, inside the enlarged hole: the
1171            //   pair imprint found nothing and the rim stayed one-use.
1172            // Drop the interior loops (as the wall carriers do): the
1173            // neighbour's carrier imprints — or its rim, welded in as a
1174            // hole — cut the true opening, and the seeded selection drops
1175            // the disk over it. A CONVEX interior rim on the same face (a
1176            // through-bore in a pocket floor) is safe to drop too: its
1177            // offset bore imprints at r+d and the ring inside is rejected by
1178            // class (Out) or by the on-skin filter, no seed involved.
1179            drop_wall_interior_loops(&mut carrier)?;
1180            // A free-form outline grown uniformly outward is trimmed by its
1181            // outline OFFSET, not the slid net's scaled trim
1182            // (`outline_offset_carrier`).
1183            let pads = [extension.u_min, extension.u_max, extension.v_min, extension.v_max];
1184            let widest = pads.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1185            let narrowest = pads.iter().copied().fold(f64::INFINITY, f64::min);
1186            // `BREP_OFFSET_CONVEX_POLYGON_OUTLINE`: pads equal but for their last
1187            // bits (a tetrahedron's turned sides read 2.121 four ways, not
1188            // bit-equal) are the uniform pad too.
1189            let uniform = (extension.u_min == extension.u_max
1190                && extension.u_min == extension.v_min
1191                && extension.u_min == extension.v_max)
1192                || (convex_polygon_outline_enabled() && widest - narrowest <= 1e-9 * widest.abs());
1193            if distance < 0.0 && uniform {
1194                // Past the walls' sections by the same clearance a planar
1195                // neighbour of a ruled wall gets, so each section lies
1196                // strictly INSIDE the fitted trim rather than on it.
1197                let clearance =
1198                    RULED_NEIGHBOUR_CLEARANCE_BANDS * offset_skin_band(crate::solid_scale(source), distance);
1199                if let Some(rebuilt) = outline_offset_carrier(source, face, widest, clearance, &carrier)? {
1200                    os_debug!(
1201                        "carrier for src face {face_id}: outline trimmed by its offset by {:.4}",
1202                        widest + clearance
1203                    );
1204                    carrier = rebuilt;
1205                } else if super::outward_side_widen::slid_trim_falls_short(
1206                    source,
1207                    face,
1208                    &source_faces,
1209                    &carrier,
1210                    distance,
1211                    narrowest,
1212                )? {
1213                    // `BREP_OFFSET_OUTWARD_SIDE_WIDEN`: a slid trim short of
1214                    // its pad takes the plane's rectangle, and the
1215                    // neighbours' offsets cut the skin from it.
1216                    os_debug!("carrier for src face {face_id}: slid trim falls short, full rectangle");
1217                    carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1218                    // Only the rectangle's own edges: a section along the
1219                    // replaced trim's records would be dropped as lying on
1220                    // this carrier's boundary.
1221                    super::outward_side_widen::keep_used_edges(&mut carrier);
1222                }
1223            }
1224        }
1225        // An inward reflex junction needs a construction plane extending PAST
1226        // the source rim. Sliding the net under a free-form trim scales that
1227        // trim instead: a notched revolve cap's notch grows, and clips away the
1228        // sections with the box's offsets. Even its curved convex boundary can
1229        // fall inside the neighbouring offset section after that scaling.
1230        // Use the extended plane's full rectangle and let the neighbouring
1231        // carriers cut the skin. The source face and the offset surface stay
1232        // unchanged. Circular outlines need the same construction: scaling a
1233        // reflex arc can also clip away its offset cylinder's section. Unlike
1234        // an outline offset, this needs no approximation of
1235        // the planar rim's parallel curve (which may collapse at a tight turn).
1236        //
1237        // A THIN-SKIN pad (`thin_skin_pad`) slides the net the same way, by
1238        // much more than the distance, and a trim that is not star-shaped
1239        // about the slide's centre moves some of its sides INWARD: an end
1240        // wall joined to a disc had its straight side carried 0.084 into the
1241        // face at d = 0.06, short of the neighbouring wall's offset, and the
1242        // skin never reached it. Such a carrier takes the rectangle too.
1243        if distance > 0.0
1244            && face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
1245            && ((reflex_extension.is_some() && outline_has_curved_element(source, face)?)
1246                || (thin_padded && thin_pad_rectangle_enabled() && outline_has_curved_element(source, face)?))
1247        {
1248            carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1249        }
1250        if planar_reach.is_some() {
1251            // A chamfer's trimmed polygon can cut diagonally across its
1252            // patch. Scaling that polygon with the net can still clip the
1253            // opening section. Let the opening and neighbouring offsets
1254            // trim the grown construction rectangle instead.
1255            carrier = full_rectangle_face(&carrier, &carrier.shells[0].faces[0])?;
1256        }
1257        if open_section_reach {
1258            if let Some(continued) = open_section_construction(source, face, &carrier, &extension, distance)? {
1259                carrier = continued;
1260                os_debug!("carrier for src face {face_id}: open section uses its natural construction rectangle");
1261            }
1262        }
1263        // The rim a shadowed support's removal VACATED in this carrier's trim:
1264        // a slot narrower than 2|d| that runs out through this face leaves a
1265        // notch its own skin has to close, because the dilation fills the slot.
1266        // The source face keeps its notch; only the carrier is bridged.
1267        if distance < 0.0 && !shadowed_supports.is_empty() {
1268            let report = close_vacated_rims(
1269                &mut carrier,
1270                source_faces
1271                    .iter()
1272                    .find(|face| face.id == *face_id)
1273                    .copied()
1274                    .unwrap_or(face),
1275                &source_faces,
1276                shadowed_supports,
1277            )?;
1278            if report.closed > 0 {
1279                os_debug!(
1280                    "carrier for src face {face_id}: {} vacated rim run(s) bridged",
1281                    report.closed
1282                );
1283            }
1284            for declined in &report.declined {
1285                os_debug!("carrier for src face {face_id}: vacated rim left alone — {declined}");
1286                vacated_notes.push(format!("source face {face_id}: {declined}"));
1287            }
1288        }
1289        carriers.push(Carrier {
1290            solid: carrier,
1291            source_face_id: *face_id,
1292            kind: OffsetFaceRole::Offset,
1293        });
1294    }
1295    profile::lap(&mut clock, profile::CARRIER_TRIM);
1296    // APEX-CAP carriers: a retained face whose DEGENERATE edge (an apex
1297    // point, e.g. a conic crater's tip) offsets into a RING is an EXTERIOR
1298    // cone offset — the parallel surface truncates at the ring and the exact
1299    // rolling-ball offset closes it with a SPHERE of radius |distance| about
1300    // the apex. Emit that sphere as an extra carrier: the ring imprint
1301    // (sphere × offset frustum) splits it, the on-skin filter keeps exactly
1302    // the cap sector (its points are |d| from the apex and ≥|d| from the
1303    // rest of the face), and the ring becomes two-use.
1304    let mut apex_cap_sources = HashSet::default();
1305    let mut apex_cap_pairs: Vec<(usize, usize)> = Vec::new();
1306    {
1307        let retained_count = carriers.len();
1308        for index in 0..retained_count {
1309            // A CARVED support's trim is the carved one. Its coedges name edges
1310            // that live only in the carved clone, so the `source.edges` lookup
1311            // below finds nothing and the apex-cap lane skips the face — which
1312            // is right: the carve already ended that carrier at the offset's own
1313            // pinch, and there is no apex ring left to cap.
1314            let carved_face = carved_supports.get(&carriers[index].source_face_id);
1315            let source_face = carved_face
1316                .or_else(|| source_by_id_lookup(&source_faces, carriers[index].source_face_id));
1317            let Some(source_face) = source_face else {
1318                continue;
1319            };
1320            let carrier_surface = carriers[index].solid.shells[0].faces[0].surface.clone();
1321            for coedge in source_face
1322                .loops
1323                .iter()
1324                .flat_map(|loop_record| &loop_record.coedges)
1325            {
1326                let Some(edge) = source
1327                    .edges
1328                    .iter()
1329                    .find(|edge| edge.id == coedge.edge_id)
1330                else {
1331                    continue;
1332                };
1333                if !edge.degenerate {
1334                    continue;
1335                }
1336                // Image of the degenerate edge on the offset surface.
1337                let [p0, p1] = coedge.pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
1338                let mut ring = Vec::new();
1339                for sample in 0..=8 {
1340                    let uv = coedge
1341                        .pcurve
1342                        .evaluate(p0 + (p1 - p0) * sample as f64 / 8.0).or_refuse(KernelStage::Sew, "evaluate")?;
1343                    ring.push(carrier_surface.evaluate(uv.x, uv.y).or_refuse(KernelStage::Sew, "evaluate")?);
1344                }
1345                let spread = ring
1346                    .iter()
1347                    .map(|point| point.sub(ring[0]).length())
1348                    .fold(0.0f64, f64::max);
1349                if spread <= distance.abs() * 1e-2 {
1350                    continue;
1351                }
1352                let apex = source
1353                    .vertices
1354                    .iter()
1355                    .find(|vertex| vertex.id == edge.start_vertex_id)
1356                    .map(|vertex| vertex.point)
1357                    .ok_or_else(|| "offset_shell: apex vertex missing".to_string()).or_refuse(KernelStage::Sew, "offset_shell_apex_vertex_missing")?;
1358                let centroid = ring
1359                    .iter()
1360                    .fold(Vec3::default(), |sum, point| sum.add(*point))
1361                    .scale(1.0 / ring.len() as f64);
1362                let axis = apex.sub(centroid);
1363                let axis = if axis.length() > 1e-9 {
1364                    axis.normalized().or_refuse(KernelStage::Sew, "normalized")?
1365                } else {
1366                    Vec3::new(0.0, 0.0, 1.0)
1367                };
1368                os_debug!(
1369                    "apex-cap carrier for src face {} at ({:.3},{:.3},{:.3}) r={:.3}",
1370                    carriers[index].source_face_id,
1371                    apex.x,
1372                    apex.y,
1373                    apex.z,
1374                    distance.abs(),
1375                );
1376                apex_cap_sources.insert(index);
1377                apex_cap_sources.insert(carriers.len());
1378                apex_cap_pairs.push((index, carriers.len()));
1379                carriers.push(Carrier {
1380                    solid: crate::make_sphere_brep(apex, distance.abs(), axis).or_refuse(KernelStage::Sew, "make_sphere_brep")?,
1381                    source_face_id: carriers[index].source_face_id,
1382                    kind: OffsetFaceRole::Offset,
1383                });
1384            }
1385        }
1386    }
1387    // Lane O item 705: the ROUND carriers about tangent opening rims, emitted
1388    // as the apex caps are (an extra Offset carrier of the neighbour face) and
1389    // handled by the same exemptions and coincident-edge splits for now.
1390    if !tangent_rim_rounds.is_empty() {
1391        let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1392        for (neighbour_id, opening_id, edge_id) in &tangent_rim_rounds {
1393            let Some(neighbour_index) = carriers.iter().position(|carrier| carrier.source_face_id == *neighbour_id && matches!(carrier.kind, OffsetFaceRole::Offset)) else {
1394                continue;
1395            };
1396            let Some(edge) = source.edges.iter().find(|edge| edge.id == *edge_id) else { continue };
1397            let Some(opening_face) = source_by_id_lookup(&source_faces, *opening_id) else { continue };
1398            match super::rim_round::circular_rim_round(edge, opening_face, distance, tolerance)? {
1399                Some(round) => {
1400                    os_debug!("tangent rim round: torus about edge {edge_id} (neighbour {neighbour_id}, opening {opening_id}) as carrier {}", carriers.len());
1401                    apex_cap_sources.insert(neighbour_index);
1402                    apex_cap_sources.insert(carriers.len());
1403                    apex_cap_pairs.push((neighbour_index, carriers.len()));
1404                    carriers.push(Carrier { solid: round, source_face_id: *neighbour_id, kind: OffsetFaceRole::Offset });
1405                }
1406                None => {
1407                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_tangent_rim_round", format!(
1408                        "offset_shell: the round about the tangent rim (edge {edge_id}) between source face {neighbour_id} and \
1409                         curved opening face {opening_id} is built only for a circular rim inside its own circle"
1410                    )));
1411                }
1412            }
1413        }
1414    }
1415    // A collapsed round's END on a planar opening: the tube about it
1416    // (`rim_round::planar_rim_tube`), riding the round's id as a synthetic
1417    // carrier the way an apex cap rides its cone's.
1418    if distance > 0.0 && super::rim_round::collapsed_rim_tube_enabled() {
1419        let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1420        // A tube a previous pass read SHADOWED is omitted with its round, as
1421        // every shadowed support is: building it again would read shadowed
1422        // again and ask for the same re-run.
1423        // A SURVIVING round (`BREP_OFFSET_SURVIVING_RIM_TUBE`) takes its tube
1424        // too: its offset ends `distance` under the rim, and the quarter tube
1425        // runs from there to the mouth.
1426        let surviving = retained
1427            .iter()
1428            .filter(|id| super::rim_round::surviving_rim_tube_enabled() && !collapsed_supports.contains(id))
1429            .map(|id| (*id, true));
1430        let rounds = collapsed_supports.iter().map(|id| (*id, false)).chain(surviving).collect::<Vec<_>>();
1431        for (collapsed_id, survives) in rounds.iter().filter(|(id, _)| !shadowed_supports.contains(id)) {
1432            let Some(face) = source_by_id_lookup(&source_faces, *collapsed_id) else { continue };
1433            for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1434                let Some((mate, mate_use)) = junction_mate(&source_faces, face, coedge.edge_id) else { continue };
1435                // Planarity is read from the geometry in `planar_rim_tube`
1436                // (a plane may arrive degree-elevated or revolved).
1437                if !opening_set.contains(&mate.id)
1438                    || !uses_are_tangent(face, coedge, mate, mate_use)?
1439                {
1440                    continue;
1441                }
1442                let Some(edge) = source.edges.iter().find(|edge| edge.id == coedge.edge_id) else { continue };
1443                // A circle's tube ends ON the plane (its mouth an orphan rim);
1444                // a line's runs past it (cut by the wall like any skin).
1445                let (tube, on_plane) = match super::rim_round::planar_rim_tube(edge, mate, distance, tolerance, *survives)? {
1446                    Some(tube) => (Some(tube), true),
1447                    None if super::rim_round::surviving_rim_tube_enabled() => {
1448                        (super::rim_round::planar_line_rim_tube(edge, mate, distance, tolerance, *survives)?, false)
1449                    }
1450                    None => (None, false),
1451                };
1452                if let Some(tube) = tube {
1453                    os_debug!(
1454                        "rim tube: about edge {} (face {collapsed_id}, {}, opening {}) as carrier {}",
1455                        edge.id,
1456                        if *survives { "surviving" } else { "collapsed" },
1457                        mate.id,
1458                        carriers.len()
1459                    );
1460                    if on_plane {
1461                        rim_tubes.insert(carriers.len(), mate.id);
1462                    }
1463                    if *survives {
1464                        surviving_tubes.insert(carriers.len());
1465                    }
1466                    carriers.push(Carrier { solid: tube, source_face_id: *collapsed_id, kind: OffsetFaceRole::Offset });
1467                }
1468            }
1469        }
1470    }
1471    profile::lap(&mut clock, profile::APEX_CAPS);
1472    // A fold the carve's probe did not see (`outward_fold_the_carve_missed`):
1473    // a band too thin for its grid is built whole, and the torus wedge grown by
1474    // 1.001 then held the reflected lemon beyond its axis. Asked of every
1475    // retained face the carve neither carved nor omitted, on every outward
1476    // shell: a ruled wall is what first let the pipeline CLOSE such a shape,
1477    // but the geometry is the trigger. Refused by name, the tangent onset
1478    // included; a partial revolve of that kind is the revolved-wedge lane's
1479    // question, and that lane runs in front of this pipeline.
1480    if distance < 0.0 {
1481        for face_id in &retained {
1482            if carved_supports.contains_key(face_id)
1483                || !carriers.iter().any(|carrier| carrier.source_face_id == *face_id)
1484            {
1485                continue;
1486            }
1487            let face = source_by_id_lookup(&source_faces, *face_id).unwrap();
1488            if let Some(fold) = profile::detail("outward_fold_the_carve_missed", || outward_fold_the_carve_missed(face, distance))? {
1489                return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_outward_fold_band", format!(
1490                    "offset_shell: the outward offset of source face {face_id} folds where the carve \
1491                     saw no fold (area factor {:.3e} at u={:.6}, v={:.6}); a fold band that thin is \
1492                     not built",
1493                    fold.factor, fold.u, fold.v
1494                )));
1495            }
1496        }
1497    }
1498    profile::lap(&mut clock, profile::CARRIER_REGULARITY);
1499    // Wall carriers built as a RULED opening face extended along itself, by
1500    // carrier index: the in-front guard reads their sides off the surface
1501    // normal where it would read a plane's.
1502    let mut ruled_walls = HashSet::default();
1503    // Inward walls at reflex rims need construction area beyond the source
1504    // opening too. Track them for source imprints and material-side selection.
1505    let mut inward_extended_walls = HashSet::default();
1506    let mut reflex_wall_neighbors = HashMap::default();
1507    // OUTWARD through a CURVED opening. A ruled one — the cone a revolved
1508    // straight profile edge sweeps, a cylinder — has its wall built as the
1509    // opening face held in place and EXTENDED along itself, exactly as a plane
1510    // is padded (`extended_ruled_wall`); the pad is the plane's, read off the
1511    // same convex junctions. Built first, so the planar walls know which
1512    // neighbours are ruled walls.
1513    //
1514    // Any other curved opening is refused by name. Its wall used to be the
1515    // unpadded source face, which never reaches the grown offset: on a torus
1516    // wedge whose chord revolves to a cone, the pair offset x cone cut 0
1517    // pieces, the cone's one fragment was dropped as a void cross-section, and
1518    // the result read "completion produced non-integral genus" with 12 open
1519    // edges. No outward shell in the kernel suites or the case corpus closed
1520    // through that wall (census, 2026-09-17).
1521    let mut ruled_built = HashMap::<u64, BrepSolid>::default();
1522    if distance < 0.0 {
1523        for face_id in opening_face_ids {
1524            let source_face = source_by_id_lookup(&source_faces, *face_id).unwrap();
1525            if source_face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1526                continue;
1527            }
1528            if !ruled_opening(source_face)? {
1529                return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_curved_opening", format!(
1530                    "offset_shell: opening face {face_id} is curved and not a ruled surface; an \
1531                     outward wall is built only on a planar or ruled opening"
1532                )));
1533            }
1534            let pad = outward_wall_pad(
1535                source,
1536                source_face,
1537                &source_faces,
1538                &opening_set,
1539                distance.abs(),
1540            )?;
1541            let tolerance = 1e-7f64.max(crate::solid_scale(source) * 1e-9);
1542            match extended_ruled_wall(source, source_face, pad, tolerance)? {
1543                Ok(wall) => {
1544                    os_debug!(
1545                        "wall for opening face {face_id}: ruled, pad {pad:.4}, sides reach {:.4?}",
1546                        wall.reached
1547                    );
1548                    ruled_built.insert(*face_id, wall.solid);
1549                }
1550                Err(reason) => {
1551                    return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_ruled_wall", format!(
1552                        "offset_shell: the outward wall of ruled opening face {face_id} cannot be \
1553                         built: {reason}"
1554                    )));
1555                }
1556            }
1557        }
1558    }
1559    let ruled_openings = ruled_built
1560        .keys()
1561        .filter_map(|id| source_by_id_lookup(&source_faces, *id))
1562        .collect::<Vec<_>>();
1563    for face_id in opening_face_ids {
1564        let source_face = source_faces
1565            .iter()
1566            .find(|face| face.id == *face_id)
1567            .unwrap();
1568        if let Some(wall) = ruled_built.remove(face_id) {
1569            ruled_walls.insert(carriers.len());
1570            carriers.push(Carrier {
1571                solid: wall,
1572                source_face_id: *face_id,
1573                kind: OffsetFaceRole::Wall,
1574            });
1575            continue;
1576        }
1577        if distance > 0.0
1578            && source_face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")?
1579        {
1580            if let Some((pad, neighbors)) =
1581                inward_wall_pad(source, source_face, &source_faces, &opening_set, distance)?
1582            {
1583                // Scaling a notched/free-form outline can still clip the new
1584                // rim. Use the whole plane rectangle; source and offset
1585                // imprints below recover both exact boundaries of the wall.
1586                let padded = carrier_solid(source, *face_id, 0.0, pad)?;
1587                let wall = full_rectangle_face(&padded, &padded.shells[0].faces[0])?;
1588                inward_extended_walls.insert(carriers.len());
1589                reflex_wall_neighbors.insert(carriers.len(), neighbors);
1590                carriers.push(Carrier {
1591                    solid: wall,
1592                    source_face_id: *face_id,
1593                    kind: OffsetFaceRole::Wall,
1594                });
1595                continue;
1596            }
1597        }
1598        carriers.push(Carrier {
1599            solid: if distance < 0.0 && source_face.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
1600                let pad = outward_wall_pad(
1601                    source,
1602                    source_face,
1603                    &source_faces,
1604                    &opening_set,
1605                    distance.abs(),
1606                )?;
1607                // A plane meeting a RULED opening is padded past the grown
1608                // outline, not onto it. Padded by exactly the pad, its trim's
1609                // arc lands ON the grown offset's section wherever the join is
1610                // perpendicular, and the ruled wall's section then ENDS on that
1611                // coincident pair: on the torus wedge the cap shredded into 60
1612                // slivers along the grown circle. The clearance is counted in
1613                // the band that decides whether the strip beyond the grown
1614                // outline is wall or void, so the strip always resolves as its
1615                // own fragment and is dropped as void.
1616                let pad = if ruled_openings
1617                    .iter()
1618                    .any(|ruled| source_faces_adjacent(source_face, ruled))
1619                {
1620                    pad + RULED_NEIGHBOUR_CLEARANCE_BANDS
1621                        * offset_skin_band(crate::solid_scale(source), distance)
1622                } else if outline_has_free_element(source, source_face)? {
1623                    // A free-form outline's wall is a FIT: without the same
1624                    // clearance its outline sits within the fit tolerance of
1625                    // the carriers' own sections on the plane, and the
1626                    // near-coincident curves shred the wall's imprint (26 to
1627                    // 121 fragments on the free-form D band, 2026-09-26). With
1628                    // it, the surplus ring is cut away cleanly.
1629                    pad + RULED_NEIGHBOUR_CLEARANCE_BANDS * offset_skin_band(crate::solid_scale(source), distance)
1630                } else {
1631                    pad
1632                };
1633                os_debug!("wall for opening face {face_id}: outward pad {pad:.4}");
1634                // The wall is the opening's outline OFFSET by the pad in its
1635                // own plane (`outline_offset.rs`). The pad used to SCALE that
1636                // outline about the patch centre, which is the offset only for
1637                // a rectangle filling its patch or a circle centred on it: an
1638                // L-shaped opening's notch edges pass through the centre and
1639                // did not move at all, so the notch faces' grown offsets
1640                // crossed the plane outside the wall ("non-integral genus",
1641                // `l-step-open-bottom` at d = −1.5 in the membrane census).
1642                //
1643                // An outline this module does not offset keeps the scaled wall,
1644                // but only when that wall still COVERS the offset outline along
1645                // every edge a retained face meets — which is what the sections
1646                // have to land inside. Otherwise the shell refuses by name
1647                // rather than assembling an open rim.
1648                let mut scaled = carrier_solid(source, *face_id, 0.0, pad)?;
1649                drop_wall_interior_loops(&mut scaled)?;
1650                let mut wall = match profile::detail("offset_outline_wall", || offset_outline_wall(source, source_face, pad))? {
1651                    Ok(outline) => {
1652                        // Where the scaled wall already trims the offset
1653                        // outline's own region — a rectangle filling its patch,
1654                        // a circle centred on it — it is kept, so no shell that
1655                        // was right before is rebuilt on a different patch.
1656                        let same = profile::detail("walls_trim_the_same_region", || walls_trim_the_same_region(
1657                            &outline,
1658                            &scaled,
1659                            1e-9f64.max(crate::solid_scale(source) * 1e-11),
1660                        ))?;
1661                        if same {
1662                            os_debug!("wall for opening face {face_id}: scaled, which IS its outline offset");
1663                            scaled
1664                        } else {
1665                            os_debug!("wall for opening face {face_id}: outline offset by {pad:.4}");
1666                            outline
1667                        }
1668                    }
1669                    Err(reason) => {
1670                        let carrier_surfaces = carriers
1671                            .iter()
1672                            .filter(|carrier| matches!(carrier.kind, OffsetFaceRole::Offset))
1673                            .map(|carrier| (carrier.source_face_id, &carrier.solid.shells[0].faces[0].surface))
1674                            .collect::<Vec<_>>();
1675                        if let Err(uncovered) = scaled_wall_covers_offset(
1676                            source,
1677                            source_face,
1678                            &scaled,
1679                            pad,
1680                            &source_faces,
1681                            &opening_set,
1682                            &carrier_surfaces,
1683                        )? {
1684                            return Err(KernelRefusal::unsupported(KernelStage::Refine, "offset_shell_opening_wall_coverage", format!(
1685                                "offset_shell: opening face {face_id}'s outline is not offset \
1686                                 ({reason}), and its scaled outward wall does not contain every \
1687                                 retained neighbour's grown offset section (a point of one lies \
1688                                 {uncovered:.3e} outside)"
1689                            )));
1690                        }
1691                        os_debug!(
1692                            "wall for opening face {face_id}: scaled, which covers its offset ({reason})"
1693                        );
1694                        scaled
1695                    }
1696                };
1697                // The pad extends the wall by STRETCHING the plane's 2x2 net
1698                // while the trim pcurves are cloned in UV, so every loop
1699                // scales about the patch centre by (w+2|d|)/w. For the OUTER
1700                // loop of a full-domain rectangle that lands exactly on the
1701                // grown outline — the intended wall extent. But an INTERIOR
1702                // loop (a carve outline: a bore, gouge or crater rim in the
1703                // opening face) is scaled OUTWARD too, and the enlarged hole
1704                // then swallows both circles the wall must be cut by (the
1705                // source carve rim from the wall x source imprint and the
1706                // shrunk rim from the wall x offset-carrier imprint) — the
1707                // imprints clip to nothing and the rims dangle one-use. Drop
1708                // interior loops instead: the wall covers the carve mouth,
1709                // the imprints cut the true rims, and selection (void-wall
1710                // guard + on-skin filter) drops the fragments over the void.
1711                drop_wall_interior_loops(&mut wall)?;
1712                wall
1713            } else {
1714                standalone_face(source, *face_id)?
1715            },
1716            source_face_id: *face_id,
1717            kind: OffsetFaceRole::Wall,
1718        });
1719    }
1720    if carriers.len() >= SOURCE_OPERAND as usize {
1721        return Err(KernelRefusal::unsupported(KernelStage::Collect, "offset_shell_carrier_count", "offset_shell: too many carrier faces for current ABI"));
1722    }
1723    profile::lap(&mut clock, profile::WALLS);
1724    // The characteristic length every tolerance below is derived from.  This
1725    // was `max ‖vertex‖` — the distance from the WORLD ORIGIN — until audit
1726    // slice 0: that form made every band widen as the part was moved away from
1727    // the origin while ignoring the part's actual size, so the same shell
1728    // solved to different tolerances depending only on where it was modelled.
1729    // `solid_scale` is the bbox diagonal, floored at 1.0 exactly as the old
1730    // fold was, so this changes ONE thing: placement-dependence.
1731    let scale = crate::solid_scale(source);
1732    crate::report_scale_migration("offset_shell", scale, || {
1733        source
1734            .vertices
1735            .iter()
1736            .map(|vertex| vertex.point.length())
1737            .fold(1.0, f64::max)
1738    });
1739    let smooth = synchronize_smooth_offset_boundaries(&mut carriers, &source_faces, scale)?;
1740    // Reflex-rim rebuilds run on BOTH attempts: the fallback for a broken
1741    // extension is an honest refusal, but the fallback for a skipped reflex
1742    // rebuild is a silently WRONG (membrane-capped) shell.
1743    let reflex_rebuilt = rebuild_reflex_rim_carriers(
1744        &mut carriers,
1745        source,
1746        &source_faces,
1747        &smooth.pairs,
1748        scale,
1749        distance,
1750    )?;
1751    *reflex_rebuilds = reflex_rebuilt.len();
1752    if extend_oblique_carriers {
1753        let oblique_extended = extend_offset_carriers_past_open_hole_rims(
1754            &mut carriers,
1755            source,
1756            &source_faces,
1757            &opening_set,
1758            &smooth.pairs,
1759            scale,
1760        )?;
1761        let mut already_extended = oblique_extended.clone();
1762        already_extended.extend(reflex_rebuilt.iter().copied());
1763        let fallshort_extended = extend_fallshort_curved_carriers(
1764            &mut carriers,
1765            source,
1766            &source_faces,
1767            &opening_set,
1768            &smooth.pairs,
1769            &already_extended,
1770            scale,
1771            distance,
1772        )?;
1773        *extension_fired = !oblique_extended.is_empty() || fallshort_extended > 0;
1774        os_debug!(
1775            "extended {} oblique + {fallshort_extended} fall-short carriers past their opening planes",
1776            oblique_extended.len(),
1777        );
1778    }
1779    profile::lap(&mut clock, profile::EXTENSION);
1780    let tolerance = 1e-7f64.max(scale * 1e-9);
1781    let pair_tolerance = (scale * 1e-8).max(2e-6);
1782    let reach = distance.abs() * 4.0 + pair_tolerance;
1783    let carrier_samples = carriers
1784        .iter()
1785        .map(|carrier| carrier_extent_points(&carrier.solid))
1786        .collect::<Result<Vec<_>, _>>()?;
1787    let carrier_bounds = carrier_samples
1788        .iter()
1789        .map(|samples| Bounds::from_nonempty_points(samples))
1790        .collect::<Option<Vec<_>>>()
1791        .ok_or_else(|| "offset_shell: carrier has no boundary samples".to_string()).or_refuse(KernelStage::Sew, "offset_shell_carrier_has_no_boundary_samples")?;
1792    let source_by_id = source_faces
1793        .iter()
1794        .map(|face| (face.id, *face))
1795        .collect::<HashMap<_, _>>();
1796    let source_samples = source_faces
1797        .iter()
1798        .map(|face| {
1799            let standalone = standalone_face(source, face.id)?;
1800            Ok((face.id, edge_sample_points(&standalone)?))
1801        })
1802        .collect::<Result<HashMap<_, _>, KernelRefusal>>()?;
1803    if debug_enabled() {
1804        for (index, carrier) in carriers.iter().enumerate() {
1805            let face = &carrier.solid.shells[0].faces[0];
1806            let samples = &carrier_samples[index];
1807            let bounds =
1808                samples
1809                    .iter()
1810                    .fold((Vec3::default(), Vec3::default()), |(low, high), point| {
1811                        (
1812                            Vec3 {
1813                                x: low.x.min(point.x),
1814                                y: low.y.min(point.y),
1815                                z: low.z.min(point.z),
1816                            },
1817                            Vec3 {
1818                                x: high.x.max(point.x),
1819                                y: high.y.max(point.y),
1820                                z: high.z.max(point.z),
1821                            },
1822                        )
1823                    });
1824            let surface = &face.surface;
1825            let rational = surface
1826                .control_points
1827                .iter()
1828                .flatten()
1829                .any(|point| (point.w - 1.0).abs() > 1e-12);
1830            os_debug!(
1831                "carrier[{index}] kind={:?} source_face={} loops={} deg=({},{}) net={}x{} rational={rational} bounds=({:.3},{:.3},{:.3})..({:.3},{:.3},{:.3})",
1832                carrier.kind, carrier.source_face_id, face.loops.len(),
1833                surface.degree_u, surface.degree_v,
1834                surface.control_points.len(),
1835                surface.control_points.first().map(|row| row.len()).unwrap_or(0),
1836                bounds.0.x, bounds.0.y, bounds.0.z, bounds.1.x, bounds.1.y, bounds.1.z,
1837            );
1838        }
1839        for (index, carrier) in carriers.iter().enumerate() {
1840            if !matches!(carrier.kind, OffsetFaceRole::Offset) {
1841                continue;
1842            }
1843            let source_face = source_by_id[&carrier.source_face_id];
1844            let carrier_surface = &carrier.solid.shells[0].faces[0].surface;
1845            let (ku, kv) = (
1846                crate::KnotVector::new(
1847                    source_face.surface.knots_u.clone(),
1848                    source_face.surface.degree_u,
1849                ),
1850                crate::KnotVector::new(
1851                    source_face.surface.knots_v.clone(),
1852                    source_face.surface.degree_v,
1853                ),
1854            );
1855            if let (Ok(ku), Ok(kv)) = (ku, kv) {
1856                let [u0, u1] = ku.domain();
1857                let [v0, v1] = kv.domain();
1858                let mut worst = 0.0f64;
1859                let mut worst_at = (0.0f64, 0.0f64);
1860                for iu in 0..=24 {
1861                    for iv in 0..=24 {
1862                        let u = u0 + (u1 - u0) * iu as f64 / 24.0;
1863                        let v = v0 + (v1 - v0) * iv as f64 / 24.0;
1864                        let expected = face_offsets(source_face)
1865                            .at(u, v, -distance)
1866                            .map(|sample| sample.point);
1867                        let actual = carrier_surface.evaluate(u, v);
1868                        if let (Ok(expected), Ok(actual)) = (expected, actual) {
1869                            let error = expected.sub(actual).length();
1870                            if error > worst {
1871                                worst = error;
1872                                worst_at = (u, v);
1873                            }
1874                        }
1875                    }
1876                }
1877                let mut normal_swing = 0.0f64;
1878                let mut previous: Option<Vec3> = None;
1879                for iu in 0..=48 {
1880                    let u = u0 + (u1 - u0) * iu as f64 / 48.0;
1881                    let v = (v0 + v1) / 2.0;
1882                    if let Ok(normal) = face_normal(source_face, u, v) {
1883                        if let Some(previous) = previous {
1884                            normal_swing = normal_swing.max(previous.sub(normal).length());
1885                        }
1886                        previous = Some(normal);
1887                    }
1888                }
1889                let weights = source_face
1890                    .surface
1891                    .control_points
1892                    .iter()
1893                    .flatten()
1894                    .map(|point| point.w)
1895                    .fold((f64::MAX, f64::MIN), |(low, high), w| {
1896                        (low.min(w), high.max(w))
1897                    });
1898                os_debug!(
1899                    "carrier[{index}] offset fit error max={worst:.6} at=({:.4},{:.4}) domain_u=({u0:.4},{u1:.4}) normal_step_max={normal_swing:.4} src_net={}x{} src_deg=({},{}) src_w=({:.4},{:.4}) knots_u={:?}",
1900                    worst_at.0, worst_at.1,
1901                    source_face.surface.control_points.len(),
1902                    source_face.surface.control_points.first().map(|row| row.len()).unwrap_or(0),
1903                    source_face.surface.degree_u, source_face.surface.degree_v,
1904                    weights.0, weights.1,
1905                    &source_face.surface.knots_u,
1906                );
1907            }
1908        }
1909        os_debug!("smooth pairs: {:?}", smooth.pairs);
1910    }
1911    let mut imprint = empty_imprint();
1912    let mut next_piece_id = 1;
1913    let mut next_vertex_id = 1;
1914    // Lane P3b row 2 (2026-10-26): where the IMPRINT phase spends its time
1915    // outside `build_imprints`, one `offset_shell.imprint_split` line under
1916    // BREP_PROFILE: the carrier-pair builds and merges, the wall x source
1917    // builds, their standalone face copies and merges, the apex ring splits,
1918    // the smooth-split sync and the boundary-coincidence filter.
1919    let split_profile = crate::imprint::profile_enabled();
1920    let mut split_ms = [0.0f64; 9];
1921    let mut split_clock = split_profile.then(web_time::Instant::now);
1922    let mut split_lap = |slot: usize, clock: &mut Option<web_time::Instant>| {
1923        if let Some(started) = clock {
1924            let now = web_time::Instant::now();
1925            split_ms[slot] += (now - *started).as_secs_f64() * 1e3;
1926            *started = now;
1927        }
1928    };
1929    // The pair skip rules, one closure for both imprint paths below (the
1930    // per-pair calls and row 6's one-call composite).
1931    // TANGENT RIM CUTS, planned before the imprint (`tangent_rim_cuts.rs`).
1932    let tangent_rim_cuts = if super::tangent_rim_cuts::tangent_rim_cuts_enabled() {
1933        super::tangent_rim_cuts::plan_tangent_rim_cuts(&carriers, &source_faces, &smooth.pairs, tolerance, scale)?
1934    } else {
1935        Vec::new()
1936    };
1937    let pair_admitted = |first: usize, second: usize| -> bool {
1938            let first_source = source_by_id[&carriers[first].source_face_id];
1939            let second_source = source_by_id[&carriers[second].source_face_id];
1940            if matches!(carriers[first].kind, OffsetFaceRole::Wall)
1941                && matches!(carriers[second].kind, OffsetFaceRole::Wall)
1942            {
1943                // Unextended inward walls are the opening faces themselves:
1944                // they never overlap; adjacent ones only touch along their
1945                // shared edge, so there is nothing to imprint. OUTWARD walls
1946                // are the opening planes EXTENDED by |distance|: the walls of
1947                // two ADJACENT openings cross along the line of their shared
1948                // source edge, and each wall ring must stop there (the sheet
1949                // past that line lies in front of the other opening). Without
1950                // the cut the wall × source chain below stays open on the
1951                // shared-edge side (its neighbour there is an opening, not a
1952                // retained face), the wall never fragments into its ring, and
1953                // every source rim along both openings dangles one-use.
1954                // Extended inward walls need those mutual cuts as well.
1955                if (distance > 0.0
1956                    && !inward_extended_walls.contains(&first)
1957                    && !inward_extended_walls.contains(&second))
1958                    || !source_faces_adjacent(first_source, second_source)
1959                {
1960                    return false;
1961                }
1962            }
1963            if smooth.pairs.contains(&(first, second)) {
1964                os_debug!("pair ({first},{second}) skipped: smooth");
1965                return false;
1966            }
1967            if !carrier_bounds[first].intersects_upper(carrier_bounds[second], pair_tolerance) {
1968                os_debug!("pair ({first},{second}) skipped: bounds");
1969                return false;
1970            }
1971            if !source_faces_adjacent(first_source, second_source)
1972                && sample_separation(
1973                    &source_samples[&first_source.id],
1974                    &source_samples[&second_source.id],
1975                ) > reach
1976            {
1977                os_debug!("pair ({first},{second}) skipped: separation");
1978                return false;
1979            }
1980            true
1981    };
1982    // The wall x source pairs: an extended opening wall (outward, or inward
1983    // at a reflex rim) against each retained source face adjacent to its
1984    // opening (see the note at the per-pair loop below).
1985    let mut wall_source_pairs: Vec<(usize, u64)> = Vec::new();
1986    if body == Body::Shell && (distance < 0.0 || !inward_extended_walls.is_empty()) {
1987        for index in 0..carriers.len() {
1988            if !matches!(carriers[index].kind, OffsetFaceRole::Wall) {
1989                continue;
1990            }
1991            if distance > 0.0 && !inward_extended_walls.contains(&index) {
1992                continue;
1993            }
1994            let opening = source_by_id[&carriers[index].source_face_id];
1995            for retained_id in &retained {
1996                if source_faces_adjacent(opening, source_by_id[retained_id]) {
1997                    wall_source_pairs.push((index, *retained_id));
1998                }
1999            }
2000        }
2001    }
2002    let one_call = one_call_imprint_enabled();
2003    let mut one_call_done = false;
2004    if one_call {
2005        // ONE-CALL IMPRINT (`BREP_OFFSET_ONE_CALL_IMPRINT`, lane P3b row 6):
2006        // every carrier and every retained source face a wall is cut against
2007        // go into one open sheet solid (ids renumbered per member), one
2008        // `build_imprints` processes exactly the admitted pairs, and its
2009        // post-passes run once over the whole piece set. The record comes
2010        // back in the shell's operand space. A failure of the single call
2011        // falls back to the per-pair path below, which tolerates a failed
2012        // pair on its own.
2013        let mut members: Vec<(u8, &BrepSolid)> = carriers.iter().enumerate().map(|(index, carrier)| (index as u8, &carrier.solid)).collect();
2014        let mut source_members: Vec<(u64, BrepSolid)> = Vec::new();
2015        for (_, retained_id) in &wall_source_pairs {
2016            if !source_members.iter().any(|(id, _)| id == retained_id) {
2017                source_members.push((*retained_id, standalone_face(source, *retained_id)?));
2018            }
2019        }
2020        for (_, solid) in &source_members {
2021            members.push((SOURCE_OPERAND, solid));
2022        }
2023        let composite = compose_imprint_operands(&members);
2024        let mut admitted: HashSet<(usize, usize)> = HashSet::default();
2025        for first in 0..carriers.len() {
2026            for second in first + 1..carriers.len() {
2027                if pair_admitted(first, second) {
2028                    admitted.insert((composite.face_index[first], composite.face_index[second]));
2029                }
2030            }
2031        }
2032        for (index, retained_id) in &wall_source_pairs {
2033            let member = carriers.len() + source_members.iter().position(|(id, _)| id == retained_id).unwrap();
2034            let (a, b) = (composite.face_index[*index], composite.face_index[member]);
2035            admitted.insert((a.min(b), a.max(b)));
2036        }
2037        split_lap(0, &mut split_clock);
2038        match crate::imprint::build_carrier_imprints_within(
2039            &composite.solid,
2040            &|first, second| admitted.contains(&(first, second)),
2041            &ImprintOptions {
2042                tolerance,
2043                maximum_fit_points: 96,
2044                local_fit: false,
2045                fit_chunk_points: None,
2046                maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2047                span_budget: None,
2048                hermite_sections: false,
2049                tangent_curve_lane: false,
2050                exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2051                march_starts: false,
2052                two_radius_junctions: false,
2053                tangent_curve_imprint: false,
2054            },
2055            !shielded_cusps.is_empty(),
2056        ) {
2057            Ok(record) => {
2058                split_lap(1, &mut split_clock);
2059                imprint = translate_composite_imprint(record, &composite, tolerance, scale)?;
2060                next_piece_id = imprint.pieces.iter().map(|piece| piece.id).max().unwrap_or(0) + 1;
2061                next_vertex_id = imprint.vertices.iter().map(|vertex| vertex.id).max().unwrap_or(0) + 1;
2062                one_call_done = true;
2063                ONE_CALL_RUNS.with(|count| count.set(count.get() + 1));
2064                split_lap(2, &mut split_clock);
2065                os_debug!(
2066                    "one-call imprint: {} members, {} admitted pairs, {} pieces",
2067                    members.len(),
2068                    admitted.len(),
2069                    imprint.pieces.len(),
2070                );
2071            }
2072            Err(error) => {
2073                os_debug!("one-call imprint failed, per-pair path: {error}");
2074            }
2075        }
2076    }
2077    for first in 0..carriers.len() {
2078        for second in first + 1..carriers.len() {
2079            if one_call_done {
2080                break;
2081            }
2082            if !pair_admitted(first, second) {
2083                continue;
2084            }
2085            split_lap(0, &mut split_clock);
2086            let pair = match crate::imprint::build_carrier_imprints(
2087                &carriers[first].solid,
2088                &carriers[second].solid,
2089                &ImprintOptions {
2090                    tolerance,
2091                    maximum_fit_points: 96,
2092                    // The GLOBAL interpolation lane. `local_fit: true` until
2093                    // 2026-09-13, which cost three orders on every smooth
2094                    // section: measured on the apex cone's base circle, the
2095                    // local lane needs 3,070 control points to reach 2.0e-5
2096                    // where the global one reaches 1.4e-8 with 384. What the
2097                    // local lane is for — a rim through a corner, where its
2098                    // monotonicity limiter holds a kink the global cubic rings
2099                    // across, 4.9x measured — is now the fit's own fallback:
2100                    // `fit_polyline` re-runs the other lane whenever the asked
2101                    // one cannot meet the tolerance and returns the better
2102                    // MEASURED curve, so this flag chooses which ladder is
2103                    // paid for first, never which curve is delivered.
2104                    local_fit: false,
2105                    fit_chunk_points: None,
2106                    // Offset carriers can meet in short, tightly curved
2107                    // branches. The general SSI default (diagonal / 15) is
2108                    // too coarse here and lets independently fitted branches
2109                    // miss a shared junction when thickness crosses one of
2110                    // those branches.
2111                    maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2112                    span_budget: None,
2113                    hermite_sections: false,
2114                    tangent_curve_lane: false,
2115                    exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2116                    march_starts: false,
2117                    two_radius_junctions: false,
2118                    tangent_curve_imprint: false,
2119                },
2120                !shielded_cusps.is_empty(),
2121            ) {
2122                Ok(pair) => pair,
2123                // A failed pair imprint (e.g. the marching SSI exhausting its
2124                // step budget on a long closed sphere/plane intersection) is
2125                // not fatal to the shell: the affected rim simply stays
2126                // unsplit and the rim-weld passes below get to close it. The
2127                // final watertightness gate still refuses anything the welds
2128                // cannot reach, so tolerating the miss only enlarges the
2129                // honest success set.
2130                Err(error) => {
2131                    os_debug!("pair ({first},{second}) imprint failed: {error}");
2132                    continue;
2133                }
2134            };
2135            split_lap(1, &mut split_clock);
2136            let pieces_before = imprint.pieces.len();
2137            merge_pair_imprint(
2138                &mut imprint,
2139                pair,
2140                first as u8,
2141                second as u8,
2142                &mut next_piece_id,
2143                &mut next_vertex_id,
2144                tolerance,
2145                scale,
2146            );
2147            split_lap(2, &mut split_clock);
2148            os_debug!(
2149                "pair ({first},{second}) src=({},{}) pieces+={}",
2150                carriers[first].source_face_id,
2151                carriers[second].source_face_id,
2152                imprint.pieces.len() - pieces_before,
2153            );
2154        }
2155    }
2156    if body == Body::Shell && (distance < 0.0 || !inward_extended_walls.is_empty()) {
2157        // An extended opening-wall carrier (outward, or inward at a reflex
2158        // rim) no longer carries the source outline. OUTWARD it has the GROWN
2159        // outline. Its inner boundary — where the wall ring stops at the
2160        // source solid — is the source outline, and the retained SOURCE faces
2161        // are not carriers, so no carrier×carrier pair ever imprints it.
2162        // Un-cut, the wall stays one whole-plane fragment covering the
2163        // opening void, and the source faces' rim edges dangle one-use.
2164        // Imprint each wall carrier against the retained source faces that
2165        // share an edge with its opening: the wall then fragments into the
2166        // ring (kept) and the opening hole (dropped by the void guard).
2167        for index in 0..carriers.len() {
2168            if one_call_done {
2169                break;
2170            }
2171            if !matches!(carriers[index].kind, OffsetFaceRole::Wall) {
2172                continue;
2173            }
2174            if distance > 0.0 && !inward_extended_walls.contains(&index) {
2175                continue;
2176            }
2177            let opening = source_by_id[&carriers[index].source_face_id];
2178            for retained_id in &retained {
2179                let retained_face = source_by_id[retained_id];
2180                if !source_faces_adjacent(opening, retained_face) {
2181                    continue;
2182                }
2183                split_lap(0, &mut split_clock);
2184                let neighbor = standalone_face(source, *retained_id)?;
2185                split_lap(3, &mut split_clock);
2186                let pair = match build_imprints(
2187                    &carriers[index].solid,
2188                    &neighbor,
2189                    &ImprintOptions {
2190                        tolerance,
2191                        maximum_fit_points: 96,
2192                        // The global lane, as above.
2193                        local_fit: false,
2194                        fit_chunk_points: None,
2195                        maximum_ssi_step: Some((scale * 0.0005).max(tolerance * 100.0)),
2196                        span_budget: None,
2197                        hermite_sections: false,
2198                        tangent_curve_lane: false,
2199                        exact_iso_pcurves: offset_exact_iso_pcurves_on(),
2200                        march_starts: false,
2201                        two_radius_junctions: false,
2202                        tangent_curve_imprint: false,
2203                    },
2204                ) {
2205                    Ok(pair) => pair,
2206                    Err(error) => {
2207                        os_debug!(
2208                            "wall×source pair ({index},{retained_id}) imprint failed: {error}"
2209                        );
2210                        continue;
2211                    }
2212                };
2213                split_lap(4, &mut split_clock);
2214                let pieces_before = imprint.pieces.len();
2215                merge_pair_imprint(
2216                    &mut imprint,
2217                    pair,
2218                    index as u8,
2219                    SOURCE_OPERAND,
2220                    &mut next_piece_id,
2221                    &mut next_vertex_id,
2222                    tolerance,
2223                    scale,
2224                );
2225                split_lap(5, &mut split_clock);
2226                os_debug!(
2227                    "wall×source pair ({index},{retained_id}) pieces+={}",
2228                    imprint.pieces.len() - pieces_before,
2229                );
2230            }
2231        }
2232    }
2233    // APEX-CAP ring splits: the cap × cone section lies ON the cone
2234    // carrier's promoted ring edge (an overlap, not a crossing), so
2235    // `build_imprints` mints no edge splits for the cone side. Without them
2236    // the cone keeps ONE closed ring edge while the cap carries the section
2237    // as arcs — mismatched segmentation, both sides one-use. Record the arc
2238    // junctions as splits on the cone's coincident edge.
2239    for (cone_index, cap_index) in &apex_cap_pairs {
2240        let cap_face_id = carriers[*cap_index].solid.shells[0].faces[0].id;
2241        let piece_ids = imprint
2242            .by_face
2243            .iter()
2244            .find(|entry| entry.operand == *cap_index as u8 && entry.face_id == cap_face_id)
2245            .map(|entry| entry.piece_ids.clone())
2246            .unwrap_or_default();
2247        let coincidence_band = 2e-5f64.max(scale * 1e-7);
2248        for piece_id in piece_ids {
2249            let Some((curve, t0, t1)) = imprint
2250                .pieces
2251                .iter()
2252                .find(|piece| piece.id == piece_id)
2253                .map(|piece| (piece.curve.clone(), piece.t0, piece.t1))
2254            else {
2255                continue;
2256            };
2257            for endpoint in [curve.evaluate(t0).or_refuse(KernelStage::Sew, "evaluate")?, curve.evaluate(t1).or_refuse(KernelStage::Sew, "evaluate")?] {
2258                for edge in &carriers[*cone_index].solid.edges {
2259                    if edge.degenerate {
2260                        continue;
2261                    }
2262                    let projection = crate::project_point_to_curve(&edge.curve, endpoint).or_refuse(KernelStage::Sew, "project_point_to_curve")?;
2263                    if projection.distance > coincidence_band
2264                        || projection.u < edge.t0 + 1e-9
2265                        || projection.u > edge.t1 - 1e-9
2266                    {
2267                        continue;
2268                    }
2269                    let parameter = projection.u;
2270                    if let Some(existing) = imprint.edge_splits.iter_mut().find(|split| {
2271                        split.operand == *cone_index as u8 && split.edge_id == edge.id
2272                    }) {
2273                        if !existing
2274                            .parameters
2275                            .iter()
2276                            .any(|value| (*value - parameter).abs() <= 1e-8)
2277                        {
2278                            existing.parameters.push(parameter);
2279                        }
2280                    } else {
2281                        imprint.edge_splits.push(EdgeSplitRecord {
2282                            operand: *cone_index as u8,
2283                            edge_id: edge.id,
2284                            parameters: vec![parameter],
2285                        });
2286                    }
2287                    os_debug!(
2288                        "apex-cap ring split: cone carrier {cone_index} edge {} at t={parameter:.6}",
2289                        edge.id,
2290                    );
2291                }
2292            }
2293        }
2294    }
2295    if debug_enabled() {
2296        for piece in &imprint.pieces {
2297            let start = piece.curve.evaluate(piece.t0);
2298            let mid = piece.curve.evaluate((piece.t0 + piece.t1) * 0.5);
2299            let end = piece.curve.evaluate(piece.t1);
2300            if let (Ok(start), Ok(mid), Ok(end)) = (start, mid, end) {
2301                os_debug!(
2302                    "piece[{}] ({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4}) on {:?}",
2303                    piece.id,
2304                    start.x,
2305                    start.y,
2306                    start.z,
2307                    mid.x,
2308                    mid.y,
2309                    mid.z,
2310                    end.x,
2311                    end.y,
2312                    end.z,
2313                    piece.support_faces,
2314                );
2315                for pcurve in &piece.pcurves {
2316                    let uv = |t: f64| pcurve.pcurve.evaluate(t).map(|p| (p.x, p.y)).unwrap_or((f64::NAN, f64::NAN));
2317                    let [a, b] = pcurve.pcurve.domain().unwrap_or([0.0, 1.0]);
2318                    os_debug!(
2319                        "  pcurve operand={} face={} uv {:?}..{:?}..{:?}",
2320                        pcurve.operand, pcurve.face_id, uv(a), uv(0.5 * (a + b)), uv(b),
2321                    );
2322                }
2323            }
2324        }
2325    }
2326    os_debug!("tangent rim cuts imprinted: {}", tangent_rim_cuts.len());
2327    super::tangent_rim_cuts::drop_marched_rim_noise(&mut imprint, &tangent_rim_cuts, distance)?;
2328    let rim_cut_pieces = super::tangent_rim_cuts::imprint_tangent_rim_cuts(
2329        &mut imprint,
2330        &carriers,
2331        tangent_rim_cuts,
2332        &mut next_piece_id,
2333        &mut next_vertex_id,
2334        distance,
2335        tolerance,
2336        scale,
2337    )?;
2338    split_lap(6, &mut split_clock);
2339    synchronize_smooth_edge_splits(&mut imprint, &smooth.edge_pairs);
2340    split_lap(7, &mut split_clock);
2341    // This decides whether an imprint is genuinely the carrier's existing
2342    // trim, not whether independently fitted curves can later be sewn. The
2343    // looser assembly tolerance can erase a short separating branch while it
2344    // is still departing a boundary.
2345    let boundary_coincidence_tolerance = 2e-5f64.max(scale * 1e-7);
2346    let piece_geometry = imprint
2347        .pieces
2348        .iter()
2349        .map(|piece| {
2350            (
2351                piece.id,
2352                FragmentEdgeGeometry {
2353                    curve: piece.curve.clone(),
2354                    t0: piece.t0,
2355                    t1: piece.t1,
2356                },
2357            )
2358        })
2359        .collect::<HashMap<_, _>>();
2360    // A rim tube ends ON its opening's plane: its mouth reaches that
2361    // opening's wall as an orphan rim, welded into the cap like any skin's.
2362    // That wall's own copy of the section would cut the mouth a second time;
2363    // a section with any OTHER wall (a second opening the tube crosses) is a
2364    // true trim and stays.
2365    if !rim_tubes.is_empty() {
2366        for entry in imprint.by_face.iter_mut() {
2367            let Some(wall) = carriers.get(entry.operand as usize) else { continue };
2368            if !matches!(wall.kind, OffsetFaceRole::Wall) {
2369                continue;
2370            }
2371            let wall_opening = wall.source_face_id;
2372            entry.piece_ids.retain(|piece_id| {
2373                !imprint.pieces.iter().any(|piece| {
2374                    piece.id == *piece_id
2375                        && piece
2376                            .support_faces
2377                            .iter()
2378                            .any(|face| rim_tubes.get(&(face.operand as usize)) == Some(&wall_opening))
2379                })
2380            });
2381        }
2382    }
2383    for (index, carrier) in carriers.iter().enumerate() {
2384        if !matches!(carrier.kind, OffsetFaceRole::Offset) {
2385            continue;
2386        }
2387        // A rebuilt carrier keeps the edge records of the trim it replaced
2388        // (`full_rectangle_face` appends its rectangle to a copy). A tangent
2389        // rim cut restores exactly such a rim, so it is read against the
2390        // edges the trim USES; every other piece keeps the reading it had.
2391        let used_edges = carrier.solid.shells[0].faces[0]
2392            .loops
2393            .iter()
2394            .flat_map(|loop_record| &loop_record.coedges)
2395            .map(|coedge| coedge.edge_id)
2396            .collect::<HashSet<_>>();
2397        let boundaries = carrier
2398            .solid
2399            .edges
2400            .iter()
2401            .map(|edge| (used_edges.contains(&edge.id), FragmentEdgeGeometry {
2402                curve: edge.curve.clone(),
2403                t0: edge.t0,
2404                t1: edge.t1,
2405            }))
2406            .collect::<Vec<_>>();
2407        if let Some(by_face) = imprint
2408            .by_face
2409            .iter_mut()
2410            .find(|entry| entry.operand == index as u8)
2411        {
2412            let before = by_face.piece_ids.clone();
2413            by_face.piece_ids.retain(|piece_id| {
2414                let piece = &piece_geometry[piece_id];
2415                let rim_cut = rim_cut_pieces.contains(piece_id);
2416                !boundaries.iter().any(|(used, boundary)| {
2417                    (*used || !rim_cut)
2418                        && fragment_edge_lies_on(piece, boundary, boundary_coincidence_tolerance)
2419                            .unwrap_or(false)
2420                })
2421            });
2422            // Separate retained planes can imprint overlapping portions of the
2423            // same line on this carrier. Arrange that cut once: duplicate
2424            // segments otherwise erase the region between a blend section
2425            // and the line. Preserve each piece on its other carrier.
2426            let candidates = by_face.piece_ids.clone();
2427            by_face.piece_ids.retain(|id| {
2428                let edge = &piece_geometry[id];
2429                if edge.curve.degree != 1 || edge.curve.control_points.len() != 2 {
2430                    return true;
2431                }
2432                !candidates.iter().any(|other_id| {
2433                    if id == other_id { return false; }
2434                    let other = &piece_geometry[other_id];
2435                    if other.curve.degree != 1 || other.curve.control_points.len() != 2 {
2436                        return false;
2437                    }
2438                    fragment_edge_lies_on(edge, other, tolerance).unwrap_or(false)
2439                        && (other_id < id
2440                            || !fragment_edge_lies_on(other, edge, tolerance).unwrap_or(false))
2441                })
2442            });
2443            if debug_enabled() && before.len() != by_face.piece_ids.len() {
2444                os_debug!(
2445                    "carrier[{index}] dropped boundary-coincident pieces: {:?} -> {:?}",
2446                    before,
2447                    by_face.piece_ids,
2448                );
2449            }
2450        }
2451    }
2452
2453    if debug_enabled() {
2454        for entry in &imprint.by_face {
2455            os_debug!(
2456                "by_face operand={} face={} pieces={:?}",
2457                entry.operand,
2458                entry.face_id,
2459                entry.piece_ids,
2460            );
2461        }
2462    }
2463    split_lap(8, &mut split_clock);
2464    if split_profile {
2465        profile_line!(
2466            "offset_shell.imprint_split skips={:.3} pair_build={:.3} pair_merge={:.3} standalone={:.3} wall_build={:.3} wall_merge={:.3} ring={:.3} smooth={:.3} filter={:.3}",
2467            split_ms[0], split_ms[1], split_ms[2], split_ms[3], split_ms[4], split_ms[5], split_ms[6], split_ms[7], split_ms[8],
2468        );
2469    }
2470    profile::lap(&mut clock, profile::IMPRINT);
2471    let mut split_carriers = Vec::new();
2472    let mut fragments_by_carrier = Vec::new();
2473    for (index, carrier) in carriers.iter().enumerate() {
2474        // Offset carriers keep their boundary un-split (their trims never
2475        // coincide with imprints — the boundary-coincidence filter drops such
2476        // pieces instead). An apex-cap ring breaks that assumption: the
2477        // frustum's ring is its TRIM boundary while the cap crosses it as TWO
2478        // imprint arcs — without splitting, the two sides segment differently
2479        // and both stay one-use. Split exactly the cap-affected carriers.
2480        let split = if matches!(carrier.kind, OffsetFaceRole::Offset)
2481            && !apex_cap_sources.contains(&index)
2482        {
2483            carrier.solid.clone()
2484        } else {
2485            apply_edge_splits(&carrier.solid, index as u8, &imprint)?
2486        };
2487        let fragment_clock = web_time::Instant::now();
2488        let fragments = fragment_solid(&split, index as u8, &imprint)?;
2489        os_debug!(
2490            "carrier[{index}] kind={:?} src={} fragments={} ({:.3} ms)",
2491            carrier.kind,
2492            carrier.source_face_id,
2493            fragments.len(),
2494            fragment_clock.elapsed().as_secs_f64() * 1e3,
2495        );
2496        if debug_enabled() {
2497            for (fragment_index, fragment) in fragments.iter().enumerate() {
2498                let mut boundary_count = 0usize;
2499                let mut imprint_pieces = Vec::new();
2500                let mut derived_count = 0usize;
2501                for coedge in fragment
2502                    .loops
2503                    .iter()
2504                    .flat_map(|loop_record| &loop_record.coedges)
2505                {
2506                    match &coedge.source {
2507                        FragmentEdgeSource::Boundary { .. }
2508                        | FragmentEdgeSource::SharedBoundary { .. } => boundary_count += 1,
2509                        FragmentEdgeSource::Imprint { piece_id } => imprint_pieces.push(*piece_id),
2510                        FragmentEdgeSource::Derived { .. } => derived_count += 1,
2511                    }
2512                }
2513                os_debug!(
2514                    "  frag[{index}.{fragment_index}] test=({:.3},{:.3},{:.3}) uv=({:.3},{:.3}) boundary={boundary_count} derived={derived_count} pieces={imprint_pieces:?}",
2515                    fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
2516                    fragment.test_uv.x, fragment.test_uv.y,
2517                );
2518            }
2519        }
2520        split_carriers.push(split);
2521        fragments_by_carrier.push(fragments);
2522    }
2523    profile::lap(&mut clock, profile::FRAGMENT);
2524    let mut assembly_sources = [(SOURCE_OPERAND, source)]
2525        .into_iter()
2526        .collect::<HashMap<_, _>>();
2527    for (index, carrier) in split_carriers.iter().enumerate() {
2528        assembly_sources.insert(index as u8, carrier);
2529    }
2530
2531    let source_edge_by_id = source
2532        .edges
2533        .iter()
2534        .map(|edge| (edge.id, edge))
2535        .collect::<HashMap<_, _>>();
2536    let retained_faces_with_edges = retained
2537        .iter()
2538        .map(|face_id| {
2539            let face = source_by_id[face_id];
2540            let edges = face
2541                .loops
2542                .iter()
2543                .flat_map(|loop_record| &loop_record.coedges)
2544                .filter_map(|coedge| source_edge_by_id.get(&coedge.edge_id).copied())
2545                .collect::<Vec<_>>();
2546            (face, edges)
2547        })
2548        .collect::<Vec<_>>();
2549    let mut offset_skin_tolerance = offset_skin_band(scale, distance);
2550    // `BREP_OFFSET_THIN_SKIN_PAD`: the band's 2e-3 floor is a fixed length;
2551    // on a shell thinner than it (box-paper-thin, d = 1e-3) no point was ever
2552    // shadowed (`separation < d - 2e-3` cannot hold), so the opening's 1e-3
2553    // corner squares, holding no wall seed, read as the void and were left
2554    // out of the rim. A thin shell's band is held to a quarter of it.
2555    if thin_skin_pad_enabled() && distance > 0.0 {
2556        offset_skin_tolerance = offset_skin_tolerance.min(0.25 * distance.abs());
2557    }
2558    // OUTWARD shells: a wall fragment lying IN FRONT of another opening —
2559    // past that opening's plane on its void side, within the extent of its
2560    // (extended) wall carrier — is not material: an opening removes
2561    // everything in front of it. Such a fragment is the sheet of this wall
2562    // between the source outline and the grown outline on the far side of an
2563    // ADJACENT opening's shared edge (the x∈[−1,0] strip of an opened −Z
2564    // face's wall, in front of the opened −X face). It sits within |distance|
2565    // of a retained face's corner edge, so the void-cross-section guard reads
2566    // it as wall thickness; only the other opening's plane tells it apart.
2567    //
2568    // A RULED opening's wall is curved, so it has no one plane: its front is
2569    // read at the point's foot on the wall carrier, along the carrier's normal
2570    // turned to the opening face's outward side. On the torus wedge that is
2571    // what drops the start and end caps' strips beyond the extended chord,
2572    // which lie within |distance| of the torus and in front of the cone.
2573    let mut opening_planes: Vec<(usize, Vec3, Vec3)> = Vec::new();
2574    let mut opening_ruled: Vec<(usize, f64)> = Vec::new();
2575    if distance < 0.0 {
2576        for (index, carrier) in carriers.iter().enumerate() {
2577            if !matches!(carrier.kind, OffsetFaceRole::Wall) {
2578                continue;
2579            }
2580            let opening = source_by_id[&carrier.source_face_id];
2581            let [u0, u1] = opening.surface.domain_u().or_refuse(KernelStage::Sew, "domain_u")?;
2582            let [v0, v1] = opening.surface.domain_v().or_refuse(KernelStage::Sew, "domain_v")?;
2583            let (u, v) = ((u0 + u1) * 0.5, (v0 + v1) * 0.5);
2584            if ruled_walls.contains(&index) {
2585                let wall = &split_carriers[index].shells[0].faces[0];
2586                let probe = project_point_to_surface(&wall.surface, opening.surface.evaluate(u, v).or_refuse(KernelStage::Sew, "evaluate")?).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2587                let side = face_normal(wall, probe.u, probe.v)?.dot(face_normal(opening, u, v)?);
2588                opening_ruled.push((index, if side < 0.0 { -1.0 } else { 1.0 }));
2589                continue;
2590            }
2591            if !opening.surface.is_affine().or_refuse(KernelStage::Sew, "is_affine")? {
2592                continue;
2593            }
2594            opening_planes.push((
2595                index,
2596                opening.surface.evaluate(u, v).or_refuse(KernelStage::Sew, "evaluate")?,
2597                face_normal(opening, u, v)?,
2598            ));
2599        }
2600    }
2601    let in_front_of_other_opening = |wall_index: usize, point: Vec3| -> Result<bool, KernelRefusal> {
2602        let band = 2e-3f64.max(scale * 5e-5);
2603        for (index, plane_point, outward) in &opening_planes {
2604            if *index == wall_index || point.sub(*plane_point).dot(*outward) <= band {
2605                continue;
2606            }
2607            let face = &split_carriers[*index].shells[0].faces[0];
2608            let projection = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2609            let uv = Vec2 {
2610                x: projection.u,
2611                y: projection.v,
2612            };
2613            if parameter_point_in_face(face, uv, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside {
2614                return Ok(true);
2615            }
2616        }
2617        for (index, side) in &opening_ruled {
2618            if *index == wall_index {
2619                continue;
2620            }
2621            let face = &split_carriers[*index].shells[0].faces[0];
2622            let projection = project_point_to_surface(&face.surface, point).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
2623            let outward = face_normal(face, projection.u, projection.v)?.scale(*side);
2624            if point.sub(projection.point).dot(outward) <= band {
2625                continue;
2626            }
2627            let uv = Vec2 {
2628                x: projection.u,
2629                y: projection.v,
2630            };
2631            if parameter_point_in_face(face, uv, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside {
2632                return Ok(true);
2633            }
2634        }
2635        Ok(false)
2636    };
2637
2638    let mut chosen_offsets = Vec::new();
2639    let mut chosen_walls = Vec::new();
2640    let mut newly_shadowed = HashSet::<u64>::default();
2641    for (index, carrier) in carriers.iter().enumerate() {
2642        let raw_seeds = source_seeds(source, carrier.source_face_id)?;
2643        let mut seeds = Vec::with_capacity(raw_seeds.len());
2644        for raw_seed in raw_seeds {
2645            let seed = if matches!(carrier.kind, OffsetFaceRole::Offset) {
2646                offset_seed(
2647                    source_by_id[&carrier.source_face_id],
2648                    raw_seed,
2649                    &split_carriers[index].shells[0].faces[0].surface,
2650                    distance,
2651                    2e-3f64.max(scale * 5e-5),
2652                )?
2653                .unwrap_or(raw_seed)
2654            } else if inward_extended_walls.contains(&index) {
2655                offset_seed(
2656                    source_by_id[&carrier.source_face_id],
2657                    raw_seed,
2658                    &split_carriers[index].shells[0].faces[0].surface,
2659                    0.0,
2660                    2e-3f64.max(scale * 5e-5),
2661                )?
2662                .unwrap_or(raw_seed)
2663            } else {
2664                raw_seed
2665            };
2666            if seed.sub(raw_seed).length() > 1e-9 {
2667                os_debug!(
2668                    "  seed[{index}] moved from ({:.4},{:.4}) to the offset image ({:.4},{:.4})",
2669                    raw_seed.x,
2670                    raw_seed.y,
2671                    seed.x,
2672                    seed.y
2673                );
2674            }
2675            seeds.push(seed);
2676        }
2677        let seed = seeds[0];
2678        if matches!(carrier.kind, OffsetFaceRole::Offset) {
2679            // Fragments whose test point sits at the full offset distance
2680            // from every retained source face are the true offset-skin
2681            // regions. Fragments closer to some other face are shadowed
2682            // pockets/strips that another carrier owns.
2683            // A fragment whose offset lies ON another retained face's offset
2684            // (material exactly twice the shell distance thick: a slot, fin or
2685            // floor at t = 2d) reads as SHADOWED by that face. One hair
2686            // thinner, the same fragment reads shadowed on its own and is
2687            // dropped by the on-skin filter, or omits its carrier by the
2688            // skinless rule below, so the answer is the limit of that
2689            // construction: the census's L∞ forms are continuous across the
2690            // onset. Without this the fragment read On, was selected, and the
2691            // shell refused as "a cavity pinched to zero thickness". The
2692            // coincidence test is `coincident_offset_face`'s (the other face's
2693            // distance within `offset_skin_tolerance` of |d|, its foot on the
2694            // opposite side of the point from this face's own), taken only on
2695            // the THIN side of the onset.
2696            let mut readings = Vec::with_capacity(fragments_by_carrier[index].len());
2697            // The construction band allows a carrier's own fit residual. It
2698            // must not also preserve pockets buried by neighboring offsets:
2699            // that coverage is what justified admitting a finite cusp. Keep
2700            // the own-face reading unchanged, and measure other faces at the
2701            // fit tolerance for this construction.
2702            let cusp_neighbors = if shielded_cusps.is_empty() {
2703                Vec::new()
2704            } else {
2705                retained_faces_with_edges.iter()
2706                    .filter(|(face, _)| face.id != carrier.source_face_id)
2707                    .cloned().collect::<Vec<_>>()
2708            };
2709            for fragment in &fragments_by_carrier[index] {
2710                let reading = offset_skin_reading(
2711                    fragment.test_point,
2712                    &retained_faces_with_edges,
2713                    distance,
2714                    offset_skin_tolerance,
2715                );
2716                let reading = if matches!(&reading, SkinReading::On) && !cusp_neighbors.is_empty() {
2717                    offset_skin_reading(
2718                        fragment.test_point,
2719                        &cusp_neighbors,
2720                        distance,
2721                        4.0 * KernelTolerances::for_solid(source, 1e-7).intersection_fit,
2722                    )
2723                } else {
2724                    reading
2725                };
2726                let reading = match reading {
2727                    SkinReading::On => match coincident_offset_face(
2728                        fragment.test_point,
2729                        carrier.source_face_id,
2730                        &retained_faces_with_edges,
2731                        distance,
2732                        offset_skin_tolerance,
2733                    )? {
2734                        // ONE-SIDED and tight: only material no thicker than
2735                        // 2|d| (to 10× the model tolerance) takes the thin
2736                        // construction, which is exact there. A wall inside
2737                        // the skin band but genuinely thicker than 2|d| keeps
2738                        // its sliver cavity's named refusal below; taking the
2739                        // thin construction there would fill a real cavity.
2740                        Some((face, separation)) if separation <= distance.abs() + tolerance * 10.0 => {
2741                            // A coincidence the fragment's other interior
2742                            // points do not share is a tangent TOUCH: the
2743                            // cavity pinches to a line there, and dropping the
2744                            // fragment as a sheet would discard real skin.
2745                            if tangent_touch_on() {
2746                                if let Some((farther, far)) = tangent_touch(
2747                                    fragment,
2748                                    face,
2749                                    &retained_faces_with_edges,
2750                                    distance,
2751                                    offset_skin_tolerance,
2752                                )? {
2753                                    return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::TANGENT_OFFSETS, format!(
2754                                        "offset_shell: the offsets of source faces {} and {face} touch tangentially near \
2755                                         ({:.4}, {:.4}, {:.4}) — the material between those faces is exactly twice the \
2756                                         shell distance thick along that touch (separation {separation:.6} against {:.6}) \
2757                                         and thicker beside it (the offset reads {far:.4} from face {face} at ({:.4}, {:.4}, {:.4})), so the cavity would \
2758                                         pinch to a line there; a cavity pinched to a line is not supported — use a \
2759                                         shell distance a little below {:.4}",
2760                                        carrier.source_face_id,
2761                                        fragment.test_point.x,
2762                                        fragment.test_point.y,
2763                                        fragment.test_point.z,
2764                                        distance.abs(),
2765                                        farther.x,
2766                                        farther.y,
2767                                        farther.z,
2768                                        distance.abs(),
2769                                    )));
2770                                }
2771                            }
2772                            SkinReading::Shadowed { face, separation }
2773                        }
2774                        _ => SkinReading::On,
2775                    },
2776                    other => other,
2777                };
2778                // One test point cannot speak for a skin that bounds a cavity
2779                // the solid demonstrably has: see `cavity_witness`.
2780                let reading = match reading {
2781                    SkinReading::Shadowed { .. } if cavity_bounds.contains(&carrier.source_face_id) => SkinReading::On,
2782                    other => other,
2783                };
2784                readings.push(reading);
2785            }
2786            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
2787                if let SkinReading::Unmeasured { face, reason } = reading {
2788                    return Err(unmeasured_skin_refusal(fragment.test_point, *face, reason));
2789                }
2790            }
2791            // EVERY fragment measured nearer than the distance to some other
2792            // retained face: this support's offset is SHADOWED over its whole
2793            // extended carrier — the side walls of a slot narrower than 2|d|
2794            // grown outward, a pocket floor within 2d of the face under it.
2795            // It owns no skin. It used to switch the filter off and keep its
2796            // seeded fragment anyway, which built a closed, validating shell
2797            // with an inverted box inside it (+90 on a width-2 slot grown by
2798            // 1.5, with the 90 of material at its centre missing). Dropping
2799            // only its fragments is not enough: its carrier has already cut
2800            // its neighbours, and the top skin over that slot keeps a hole
2801            // nothing fills. So the pass is re-run with the support omitted
2802            // before the imprint, like a collapsed one. An apex-cap sphere
2803            // shares its cone's source id and is not judged here.
2804            //
2805            // Only the FIRST pass omits. A test point speaks for its fragment
2806            // because every other carrier's imprint bounds it; omitting a
2807            // carrier removes cuts, merges fragments and moves test points,
2808            // but changes no distance, so a support that reads shadowed only
2809            // AFTER an omission is reading a test point that no longer stands
2810            // for its fragment. Measured on two bosses 1 apart grown outward
2811            // by 1.5: once the facing boss walls were omitted, the plate's
2812            // grown top — one uncut fragment, mostly skin — read shadowed at
2813            // its single test point.
2814            //
2815            // "Every fragment" counts a fragment the selection would drop by
2816            // CLASS as not skin, as the selection does: the extended carrier's
2817            // surplus past a slot's end reads at least the distance from every
2818            // face, lies inside the source, and on a slot 1 wide grown outward
2819            // left the slot floor unjudged until the side walls were gone.
2820            // ADRIFT: a fragment whose test point is farther from its OWN face
2821            // than the distance, in the mitered metric, is not that face's skin
2822            // — it is inside the cavity, past where its neighbours' offsets cut
2823            // it. A rib, a pin or a divider thinner than 2d shelled inward
2824            // keeps such fragments, and the assembly then fails on them.
2825            let adrift = fragments_by_carrier[index]
2826                .iter()
2827                .map(|fragment| {
2828                    point_adrift_of_its_own_offset(
2829                        fragment.test_point,
2830                        carrier.source_face_id,
2831                        &retained_faces_with_edges,
2832                        distance,
2833                        offset_skin_tolerance,
2834                    )
2835                })
2836                .collect::<Vec<_>>();
2837            let mut skinless = readings
2838                .iter()
2839                .any(|reading| matches!(reading, SkinReading::Shadowed { .. }))
2840                || adrift.iter().any(|flag| *flag);
2841            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
2842                if !skinless {
2843                    break;
2844                }
2845                if matches!(reading, SkinReading::On)
2846                    && !adrift[fragments_by_carrier[index]
2847                        .iter()
2848                        .position(|other| std::ptr::eq(other, fragment))
2849                        .unwrap_or(0)]
2850                {
2851                    let class = classify_point(fragment.test_point, source, tolerance * 10.0).or_refuse(KernelStage::Sew, "classify_point")?.class;
2852                    skinless = (distance > 0.0 && class == PointClass::Out)
2853                        || (distance < 0.0 && class == PointClass::In);
2854                }
2855            }
2856            #[cfg(not(test))]
2857            let forced_shadow = false;
2858            let skinless = skinless || forced_shadow;
2859            if skinless && !apex_cap_sources.contains(&index) {
2860                if body == Body::Shell && distance > 0.0 && cascade_omission_enabled() && !forced_shadow {
2861                    let held = fragments_holding_true_skin(
2862                        source_by_id[&carrier.source_face_id],
2863                        source,
2864                        &fragments_by_carrier[index],
2865                        &retained_faces_with_edges,
2866                        distance,
2867                        offset_skin_tolerance,
2868                    )?;
2869                    if !held.is_empty() {
2870                        os_debug!("  select[{index}] src={}: {} fragment(s) hold true skin", carrier.source_face_id, held.len());
2871                        chosen_offsets.extend(held);
2872                        continue;
2873                    }
2874                }
2875                if !shadowed_supports.is_empty() && !(body == Body::Shell && distance > 0.0 && cascade_omission_enabled()) {
2876                    let mut omitted = shadowed_supports.iter().copied().collect::<Vec<_>>();
2877                    omitted.sort_unstable();
2878                    return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_shadow_cascade", format!(
2879                        "offset_shell: omitting the shadowed offsets of source faces {omitted:?} \
2880                         leaves the offset of source face {} shadowed at every one of its {} \
2881                         fragment test points, which no longer stand for their fragments once \
2882                         those carriers stop cutting it",
2883                        carrier.source_face_id,
2884                        readings.len()
2885                    )));
2886                }
2887                if surviving_tubes.contains(&index) {
2888                    os_debug!("  select[{index}] src={}: a surviving round's rim tube reads shadowed; only the tube is dropped", carrier.source_face_id);
2889                    continue;
2890                }
2891                os_debug!(
2892                    "  select[{index}] src={} SHADOWED over all {} fragment(s): {:?}",
2893                    carrier.source_face_id,
2894                    readings.len(),
2895                    readings
2896                );
2897                newly_shadowed.insert(carrier.source_face_id);
2898                continue;
2899            }
2900            // Partly shadowed: keep a bounded sample of the shadowed test
2901            // points, so a refusal can say where two offsets cross.
2902            for (fragment, reading) in fragments_by_carrier[index].iter().zip(&readings) {
2903                if shadowed_points.len() >= MAXIMUM_CROSSING_READS {
2904                    break;
2905                }
2906                if matches!(reading, SkinReading::Shadowed { .. }) {
2907                    shadowed_points.push((fragment.test_point, carrier.source_face_id));
2908                }
2909            }
2910            let mut on_skin = readings
2911                .iter()
2912                .zip(&adrift)
2913                .map(|(reading, adrift)| matches!(reading, SkinReading::On) && !adrift)
2914                .collect::<Vec<_>>();
2915            if open_section_reach {
2916                if let Some(ends) = open_profile_end_neighbours(index, &carriers, &source_faces)? {
2917                    // A continued variable profile can approach its original
2918                    // end cap inside the distance band. Its sharp boundary is
2919                    // the section with the OFFSET end plane, not that old cap.
2920                    for (keep, fragment) in on_skin.iter_mut().zip(&fragments_by_carrier[index]) {
2921                        *keep = !outside_continued_neighbours(fragment.test_point, &ends, &carriers, tolerance)?;
2922                    }
2923                    os_debug!("  select[{index}] open profile kept {} central regions", on_skin.iter().filter(|keep| **keep).count());
2924                }
2925            }
2926            // A synthetic apex sphere has no source-face seed of its own to
2927            // fall back to. When its whole cap is hidden by retained offsets,
2928            // keep its cuts but contribute no skin. Otherwise the fallback
2929            // selects the uncut sphere as a stray patch inside the material.
2930            // The parent cone remains subject to the ordinary selection.
2931            let skin_filter_active = on_skin.iter().any(|flag| *flag)
2932                || apex_cap_pairs.iter().any(|(_, cap)| *cap == index);
2933            let opening_limits = if inward_extended_walls.is_empty() {
2934                Vec::new()
2935            } else {
2936                let openings = inward_extended_walls
2937                    .iter()
2938                    .map(|index| source_by_id[&carriers[*index].source_face_id])
2939                    .collect::<Vec<_>>();
2940                opening_trim_halfspaces(source_by_id[&carrier.source_face_id], &openings, tolerance)?
2941            };
2942            let mut classified = Vec::new();
2943            let mut viable = Vec::new();
2944            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
2945                let class = classify_point(fragment.test_point, source, tolerance * 10.0).or_refuse(KernelStage::Sew, "classify_point")?.class;
2946                let excluded_by_class = (distance > 0.0 && class == PointClass::Out)
2947                    || (distance < 0.0 && class == PointClass::In);
2948                let contact = if excluded_by_class {
2949                    false
2950                } else {
2951                    distance > 0.0
2952                        && fragment_has_sustained_source_contact(
2953                            fragment,
2954                            &source_faces,
2955                            &assembly_sources,
2956                            &imprint,
2957                            2e-3f64.max(scale * 5e-5),
2958                        )?
2959                };
2960                os_debug!(
2961                    "  select[{index}.{fragment_index}] class={class:?} contact={contact} on_skin={} reading={:?} adrift={} seed_in={:?} uv=({:.3},{:.3})",
2962                    on_skin[fragment_index],
2963                    readings[fragment_index],
2964                    adrift[fragment_index],
2965                    parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8),
2966                    fragment.test_uv.x, fragment.test_uv.y,
2967                );
2968                let past_opening = opening_limits.iter().any(|(origin, normal)| {
2969                    fragment.test_point.sub(*origin).dot(*normal) < -tolerance * 10.0
2970                });
2971                if excluded_by_class
2972                    || past_opening
2973                    || (skin_filter_active && !on_skin[fragment_index])
2974                {
2975                    continue;
2976                }
2977                classified.push(fragment.clone());
2978                if contact {
2979                    continue;
2980                }
2981                viable.push(fragment.clone());
2982            }
2983            // One skin per REGION of the source face (see `source_seeds`):
2984            // every region of a pinched face is offset like a face of its
2985            // own, and the selection below answers each region's seed. An
2986            // ordinary face has the one seed and the one answer it always had.
2987            let mut region_skins = Vec::new();
2988            let continued_neighbours = if distance > 0.0 {
2989                continued_sphere_neighbours(index, &carriers, &source_faces, scale)?
2990            } else { None };
2991            if let Some(neighbours) = &continued_neighbours {
2992                for fragment in &classified {
2993                    if outside_continued_neighbours(fragment.test_point, neighbours, &carriers, tolerance)? {
2994                        region_skins.push(fragment.clone());
2995                    }
2996                }
2997                os_debug!("  select[{index}] continued sphere kept {} regions", region_skins.len());
2998            }
2999            for &seed in seeds.iter().filter(|_| continued_neighbours.is_none()) {
3000                os_debug!("  select[{index}] seed=({:.4},{:.4})", seed.x, seed.y);
3001                let seeded = viable
3002                    .iter()
3003                    .filter(|fragment| {
3004                        parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8)
3005                            .is_ok_and(|class| class != PolygonClass::Outside)
3006                    })
3007                    .cloned()
3008                    .collect::<Vec<_>>();
3009                let seeded_classified = classified
3010                    .iter()
3011                    .filter(|fragment| {
3012                        parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8)
3013                            .is_ok_and(|class| class != PolygonClass::Outside)
3014                    })
3015                    .cloned()
3016                    .collect::<Vec<_>>();
3017                let selected = if viable.is_empty() {
3018                    if !skin_filter_active {
3019                        // NOTHING on this carrier reads on-skin: every classified
3020                        // fragment's test point is measurably CLOSER than the
3021                        // offset distance to some retained face — a buried strip
3022                        // another carrier owns. Forcing the largest one in anyway
3023                        // plants a wrong skin patch that collides with the
3024                        // completion phase's reconstruction (3-use edges).
3025                        // Contribute nothing: `complete_opening_boundary_cycles`
3026                        // rebuilds the true skin from the carrier surface, and the
3027                        // watertight gate still refuses if it cannot.
3028                        None
3029                    } else {
3030                        let mut by_area = classified
3031                            .iter()
3032                            .cloned()
3033                            .map(|fragment| {
3034                                let area = parameter_space_area(&fragment_as_trim(&fragment)).or_refuse(KernelStage::Sew, "parameter_space_area")?.abs();
3035                                Ok((fragment, area))
3036                            })
3037                            .collect::<Result<Vec<_>, KernelRefusal>>()?;
3038                        by_area.sort_by(|a, b| b.1.total_cmp(&a.1));
3039                        by_area.into_iter().next().map(|entry| entry.0)
3040                    }
3041                } else if !seeded_classified.is_empty() {
3042                    let mut candidates = seeded_classified;
3043                    candidates.sort_by(|a, b| {
3044                        a.test_uv
3045                            .sub(seed)
3046                            .length()
3047                            .total_cmp(&b.test_uv.sub(seed).length())
3048                    });
3049                    candidates.into_iter().next()
3050                } else if viable.len() > 2 {
3051                    let mut by_area = viable
3052                        .iter()
3053                        .cloned()
3054                        .map(|fragment| {
3055                            let area = parameter_space_area(&fragment_as_trim(&fragment)).or_refuse(KernelStage::Sew, "parameter_space_area")?.abs();
3056                            Ok((fragment, area))
3057                        })
3058                        .collect::<Result<Vec<_>, KernelRefusal>>()?;
3059                    by_area.sort_by(|a, b| b.1.total_cmp(&a.1));
3060                    by_area.into_iter().next().map(|entry| entry.0)
3061                } else {
3062                    let mut candidates = if seeded.is_empty() { viable.clone() } else { seeded };
3063                    candidates.sort_by(|a, b| {
3064                        a.test_uv
3065                            .sub(seed)
3066                            .length()
3067                            .total_cmp(&b.test_uv.sub(seed).length())
3068                    });
3069                    candidates.into_iter().next()
3070                };
3071                let mut drop_debris = false;
3072                if let Some(fragment) = &selected {
3073                    os_debug!(
3074                        "  select[{index}] src={} chosen test point departs its own face's offset \
3075                         distance by {:?}",
3076                        carrier.source_face_id,
3077                        own_offset_departure(
3078                            fragment.test_point,
3079                            carrier.source_face_id,
3080                            &retained_faces_with_edges,
3081                            distance
3082                        )
3083                    );
3084                    os_debug!(
3085                        "  select[{index}] src={} chosen test point departs in the MITER metric by {:?}",
3086                        carrier.source_face_id,
3087                        own_miter_departure(
3088                            fragment.test_point,
3089                            carrier.source_face_id,
3090                            &retained_faces_with_edges,
3091                            distance
3092                        )
3093                    );
3094                    let coincidence = coincident_offset_face(
3095                        fragment.test_point,
3096                        carrier.source_face_id,
3097                        &retained_faces_with_edges,
3098                        distance,
3099                        offset_skin_tolerance,
3100                    )?;
3101                    let coincidence = match coincidence {
3102                        Some((other, separation))
3103                            if coincide_debris_on()
3104                                && fragment_is_band_debris(fragment, offset_skin_tolerance)? =>
3105                        {
3106                            os_debug!(
3107                                "  select[{index}] src={} drops corner debris coincident with {other} \
3108                                 (separation {separation}) at {:?}",
3109                                carrier.source_face_id,
3110                                fragment.test_point
3111                            );
3112                            drop_debris = true;
3113                            None
3114                        }
3115                        reading => reading,
3116                    };
3117                    if let Some((other, separation)) = coincidence {
3118                        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_coincident_offsets", format!(
3119                            "offset_shell: the offsets of source faces {} and {other} coincide near \
3120                             ({:.4}, {:.4}, {:.4}) — the material between those faces is twice the \
3121                             shell distance thick (separation {separation:.6} against {:.6}, band \
3122                             {offset_skin_tolerance:.1e}), so the cavity between them has no \
3123                             thickness there; a cavity pinched to zero thickness is not supported",
3124                            carrier.source_face_id,
3125                            fragment.test_point.x,
3126                            fragment.test_point.y,
3127                            fragment.test_point.z,
3128                            distance.abs(),
3129                        )));
3130                    }
3131                }
3132                let selected = if drop_debris { None } else { selected };
3133                if let Some(fragment) = selected {
3134                    // A pinched face's seeds each find their own region; a
3135                    // fallback that ignores the seed can answer the same
3136                    // fragment twice, and one skin must enter once.
3137                    if !region_skins
3138                        .iter()
3139                        .any(|other: &FaceFragmentRecord| {
3140                            other.test_point.sub(fragment.test_point).length() <= 1e-12
3141                        })
3142                    {
3143                        region_skins.push(fragment);
3144                    }
3145                }
3146            }
3147            // EVERY SKIN PIECE (`BREP_OFFSET_EVERY_SKIN_PIECE`, default on):
3148            // one source region's offset skin can come out in several pieces
3149            // when another offset cuts it (the drilled block's bore skin,
3150            // radius 4, runs into the wall skin x = 19 and parts it at
3151            // y = 10 ± √15/2) or the carrier's seam parts it (the bore skin
3152            // itself, at its seam). The seed answers one piece; every
3153            // classified fragment already reads on the skin, inside the source
3154            // and short of the openings, so all of them are the skin, as for
3155            // the extended walls below. Left out, the pieces the seed missed
3156            // left their outlines one-use (shell/hole-skin-merging-wall).
3157            // Only where the seed could not choose: an inward shell whose every
3158            // on-skin fragment touches the source (`viable` empty), so the
3159            // largest stood in for the region; an outward shell's fragments and
3160            // a seeded choice keep the seed's answer. And only a piece whose
3161            // test point lies the distance from its OWN trimmed face: "on the
3162            // skin" says no retained face is nearer, which a point inside the
3163            // offset body also reads (the cylinder's offset past a reflex
3164            // junction, inside the box's offset wall: 0.139 from the trimmed
3165            // cylinder against 0.1, reflex_junction_under_a_filleted_top).
3166            if every_skin_piece_enabled()
3167                && distance > 0.0
3168                && (viable.is_empty() || every_seeded_piece)
3169                && skin_filter_active
3170                && inward_extended_walls.is_empty()
3171                && classified.len() > region_skins.len()
3172            {
3173                for fragment in &classified {
3174                    if region_skins.iter().any(|other: &FaceFragmentRecord| other.test_point.sub(fragment.test_point).length() <= 1e-12) {
3175                        continue;
3176                    }
3177                    let departure = own_offset_departure(fragment.test_point, carrier.source_face_id, &retained_faces_with_edges, distance);
3178                    os_debug!("  select[{index}] every skin piece: test point ({:.4},{:.4},{:.4}) departs its own face's offset by {departure:?}", fragment.test_point.x, fragment.test_point.y, fragment.test_point.z);
3179                    if departure.is_some_and(|departure| departure.abs() <= offset_skin_tolerance) {
3180                        region_skins.push(fragment.clone());
3181                    }
3182                }
3183            }
3184            if !inward_extended_walls.is_empty() && skin_filter_active {
3185                // The extended opening cuts beyond the source footprint.
3186                // Other finite carriers can subdivide a connected offset
3187                // region there (the box/revolve report splits both box caps
3188                // at x=1). A single source seed keeps only one of those cells.
3189                // Keep every cell already proved inside the source and on
3190                // the offset skin, then merge their shared boundaries.
3191                region_skins = classified;
3192            }
3193            chosen_offsets.extend(region_skins);
3194        } else if body == Body::Whole {
3195            // A HELD face of the offset body: its carrier is the face at
3196            // distance zero, cut by the neighbouring offset skins; the body
3197            // keeps the region the face's own seed lies in, whole. There is
3198            // no source rim to stop at and no void in front of it.
3199            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
3200                if seeds.iter().any(|seed| {
3201                    parameter_point_in_face(&fragment_as_trim(fragment), *seed, 1e-8)
3202                        .is_ok_and(|class| class != PolygonClass::Outside)
3203                }) {
3204                    os_debug!("  held[{index}.{fragment_index}] kept: contains the face's seed");
3205                    chosen_walls.push(fragment.clone());
3206                }
3207            }
3208        } else {
3209            // Keep arrangement order stable. Besides making the result
3210            // reproducible, this matches the reference kernel's Set insertion
3211            // order when the final manifold-wall guard admits fragments.
3212            let opening = source_by_id[&carrier.source_face_id];
3213            let wall_seeds = opening_wall_seeds(
3214                opening,
3215                &split_carriers[index].shells[0].faces[0],
3216                source,
3217                &opening_set,
3218                distance,
3219            )?;
3220            // The wall-seed exemptions below rest on "the coplanar-rim weld
3221            // cuts the void hole later" — which only ever happens on PLANAR
3222            // opening carriers. A curved carrier (e.g. the sphere face used
3223            // directly as the opening) keeps its un-split fragment forever:
3224            // exempting it would seal the opening with the source face itself
3225            // and fabricate a closed hollow solid. Curved carriers therefore
3226            // get the strict void guard.
3227            let carrier_planar =
3228                surface_is_planar(&split_carriers[index].shells[0].faces[0].surface, tolerance)
3229                    .unwrap_or(false);
3230            let extended_inward = inward_extended_walls.contains(&index);
3231            let outside_source = |point| -> Result<bool, KernelRefusal> {
3232                Ok(extended_inward
3233                    && classify_point(point, source, tolerance * 10.0)
3234                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::Out)
3235            };
3236            let wall_on_skin = |point| {
3237                if extended_inward {
3238                    let inside_source = classify_point(point, source, tolerance * 10.0)
3239                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In;
3240                    point_on_inward_opening_skin(
3241                        point,
3242                        &retained_faces_with_edges,
3243                        &reflex_wall_neighbors[&index],
3244                        inside_source,
3245                        distance,
3246                        offset_skin_tolerance,
3247                    )
3248                } else {
3249                    point_on_offset_skin(
3250                        point,
3251                        &retained_faces_with_edges,
3252                        distance,
3253                        offset_skin_tolerance,
3254                    )
3255                }
3256            };
3257            let mut selected_indices = Vec::new();
3258            for (fragment_index, fragment) in fragments_by_carrier[index].iter().enumerate() {
3259                if outside_source(fragment.test_point)? {
3260                    continue;
3261                }
3262                if parameter_point_in_face(&fragment_as_trim(fragment), seed, 1e-8).or_refuse(KernelStage::Sew, "parameter_point_in_face")?
3263                    == PolygonClass::Outside
3264                {
3265                    if in_front_of_other_opening(index, fragment.test_point)? {
3266                        os_debug!(
3267                            "  wall[{index}.{fragment_index}] skipped: in front of another \
3268                             opening at ({:.3},{:.3},{:.3})",
3269                            fragment.test_point.x,
3270                            fragment.test_point.y,
3271                            fragment.test_point.z,
3272                        );
3273                        continue;
3274                    }
3275                    // Wall = the material cross-section exposed at the
3276                    // opening: every point of a genuine wall fragment lies
3277                    // WITHIN the offset distance of some retained face (it is
3278                    // the thickness between that face and its offset skin). A
3279                    // fragment at ≥ distance from EVERY retained face — and
3280                    // containing no expected wall seed (an un-split cap
3281                    // fragment can span both the void AND the wall annulus;
3282                    // the coplanar-rim weld cuts its hole later) — is the
3283                    // core's own cross-section: a HOLE in the opening (e.g.
3284                    // the corner void where a carve's offset circle passes
3285                    // just inside the opening's corner). Welding it shut
3286                    // would fabricate a wall over the void.
3287                    if wall_on_skin(fragment.test_point)? && !(carrier_planar
3288                        && !extended_inward
3289                        && wall_seeds.iter().any(|wall_seed| {
3290                            parameter_point_in_face(&fragment_as_trim(fragment), *wall_seed, 1e-8)
3291                                .is_ok_and(|class| class != PolygonClass::Outside)
3292                        }))
3293                    {
3294                        os_debug!(
3295                            "  wall[{index}.{fragment_index}] skipped: void cross-section at \
3296                             ({:.3},{:.3},{:.3})",
3297                            fragment.test_point.x,
3298                            fragment.test_point.y,
3299                            fragment.test_point.z,
3300                        );
3301                        continue;
3302                    }
3303                    // A SURPLUS fragment beyond a sharp convex corner: it
3304                    // touches the wall's own outline, no edge of it was cut by
3305                    // the SOURCE (the rim every genuine wall region borders),
3306                    // and it holds no wall seed. The void test above reads it
3307                    // as material, because it measures a planar neighbour in the
3308                    // MITER metric (its extended plane, 0.277 from this region
3309                    // on the free-form D turning 83.7° at d = 0.3). The
3310                    // opening wall's clearance cuts such a region off between
3311                    // the carriers' tails past the mitre, and kept, it
3312                    // assembled as "non-integral genus" (8 of the D band's 42
3313                    // cells, 2026-09-26).
3314                    if distance < 0.0
3315                        && wall_surplus_beyond_the_sections(fragment, index as u8, |piece_id| {
3316                            imprint.pieces.iter().find(|piece| piece.id == piece_id).is_some_and(|piece| {
3317                                piece.support_faces.iter().any(|key| key.operand == SOURCE_OPERAND)
3318                            })
3319                        })
3320                        && !wall_seeds.iter().any(|wall_seed| {
3321                            parameter_point_in_face(&fragment_as_trim(fragment), *wall_seed, 1e-8)
3322                                .is_ok_and(|class| class != PolygonClass::Outside)
3323                        })
3324                    {
3325                        os_debug!(
3326                            "  wall[{index}.{fragment_index}] skipped: surplus beyond the sections at \
3327                             ({:.3},{:.3},{:.3}), touching the wall outline and no source rim",
3328                            fragment.test_point.x,
3329                            fragment.test_point.y,
3330                            fragment.test_point.z,
3331                        );
3332                        continue;
3333                    }
3334                    selected_indices.push(fragment_index);
3335                }
3336            }
3337            for wall_seed in wall_seeds {
3338                let fragments = &fragments_by_carrier[index];
3339                let nearest_containing = fragments
3340                    .iter()
3341                    .enumerate()
3342                    .filter(|(_, fragment)| {
3343                        parameter_point_in_face(&fragment_as_trim(fragment), wall_seed, 1e-8)
3344                            .is_ok_and(|class| class != PolygonClass::Outside)
3345                    })
3346                    .min_by(|(_, first), (_, second)| {
3347                        first
3348                            .test_uv
3349                            .sub(wall_seed)
3350                            .length()
3351                            .total_cmp(&second.test_uv.sub(wall_seed).length())
3352                    })
3353                    .map(|(fragment_index, _)| fragment_index);
3354                // Arrangement fitting can leave the seed just outside every
3355                // fragment by a small amount. Match the reference kernel's
3356                // geometric fallback instead of silently omitting the wall
3357                // fragment and leaving the assembled shell open.
3358                let nearest = if nearest_containing.is_some() {
3359                    nearest_containing
3360                } else {
3361                    let seed_point = split_carriers[index].shells[0].faces[0]
3362                        .surface
3363                        .evaluate(wall_seed.x, wall_seed.y).or_refuse(KernelStage::Sew, "evaluate")?;
3364                    fragments
3365                        .iter()
3366                        .enumerate()
3367                        .min_by(|(_, first), (_, second)| {
3368                            first
3369                                .test_point
3370                                .sub(seed_point)
3371                                .length()
3372                                .total_cmp(&second.test_point.sub(seed_point).length())
3373                        })
3374                        .map(|(fragment_index, _)| fragment_index)
3375                };
3376                if let Some(fragment_index) = nearest {
3377                    let candidate = &fragments_by_carrier[index][fragment_index];
3378                    if outside_source(candidate.test_point)?
3379                        || in_front_of_other_opening(index, candidate.test_point)?
3380                    {
3381                        continue;
3382                    }
3383                    // Void-cross-section guard. On a PLANAR carrier it applies
3384                    // to the GEOMETRIC FALLBACK only: a fragment that
3385                    // genuinely contains this wall seed is wall content by
3386                    // construction (even when un-split it also spans void —
3387                    // the rim weld cuts the hole later), but a merely-nearest
3388                    // fragment must not resurrect a hole in the opening. On a
3389                    // CURVED carrier no later weld cuts the hole, so even a
3390                    // seed-containing fragment gets the strict guard.
3391                    // Extended inward walls are cut by the source as well:
3392                    // a seed must not resurrect the opposite side of a
3393                    // reflex rim merely because its unsigned distance is small.
3394                    if (nearest_containing.is_none() || !carrier_planar || extended_inward)
3395                        && wall_on_skin(candidate.test_point)?
3396                    {
3397                        os_debug!(
3398                            "  wall[{index}.{fragment_index}] seed-hit skipped: void \
3399                             cross-section (planar={carrier_planar}) at ({:.3},{:.3},{:.3})",
3400                            candidate.test_point.x,
3401                            candidate.test_point.y,
3402                            candidate.test_point.z,
3403                        );
3404                        continue;
3405                    }
3406                    let existing = chosen_offsets.iter().cloned().chain(
3407                        selected_indices
3408                            .iter()
3409                            .map(|selected| fragments_by_carrier[index][*selected].clone()),
3410                    );
3411                    if !selected_indices.contains(&fragment_index)
3412                        && !would_overuse_existing_boundary(
3413                            candidate,
3414                            existing,
3415                            &assembly_sources,
3416                            &imprint,
3417                            2e-3,
3418                        )?
3419                    {
3420                        selected_indices.push(fragment_index);
3421                    }
3422                }
3423            }
3424            for fragment_index in selected_indices.iter().copied() {
3425                let mut fragment = fragments_by_carrier[index][fragment_index].clone();
3426                // An OUTWARD wall is the grown body's section less the source:
3427                // none of it lies inside the source. A kept fragment that does
3428                // is the opening's plane carried past a reflex outline edge
3429                // (an L-block opened at its step: the plane beyond the step
3430                // runs inside the block's leg), and the fragments around it
3431                // were cut only where the source meets the plane, so the
3432                // selection cannot tell wall from material there. The boolean
3433                // lane builds that shell exactly; refuse by name to reach it.
3434                if distance < 0.0
3435                    && !extended_inward
3436                    && wall_inside_source_lane_on()
3437                    && classify_point(fragment.test_point, source, tolerance * 10.0)
3438                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In
3439                {
3440                    return Err(KernelRefusal::unsupported(
3441                        KernelStage::Select,
3442                        "offset_shell_wall_inside_source",
3443                        format!(
3444                            "offset_shell: opening face {}'s outward wall keeps a fragment inside the \
3445                             source at ({:.3},{:.3},{:.3})",
3446                            carrier.source_face_id, fragment.test_point.x, fragment.test_point.y, fragment.test_point.z,
3447                        ),
3448                    ));
3449                }
3450                // Past a reflex rim the wall closes the cavity on the other
3451                // side of the opening plane, so its normal reverses too.
3452                if extended_inward
3453                    && classify_point(fragment.test_point, source, tolerance * 10.0)
3454                        .or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In
3455                {
3456                    flip_fragment(&mut fragment)?;
3457                }
3458                chosen_walls.push(fragment);
3459            }
3460        }
3461    }
3462    if debug_enabled() {
3463        for fragment in &chosen_offsets {
3464            os_debug!(
3465                "chosen offset: operand={} src={} test=({:.3},{:.3},{:.3})",
3466                fragment.operand,
3467                carriers[fragment.operand as usize].source_face_id,
3468                fragment.test_point.x,
3469                fragment.test_point.y,
3470                fragment.test_point.z,
3471            );
3472            for (loop_index, loop_record) in fragment.loops.iter().enumerate() {
3473                for coedge in &loop_record.coedges {
3474                    let surface = &fragment.surface;
3475                    let [c0, c1] = coedge.pcurve.domain().unwrap_or([0.0, 0.0]);
3476                    let uv0 = coedge.pcurve.evaluate(c0);
3477                    let uv1 = coedge.pcurve.evaluate(c1);
3478                    if let (Ok(uv0), Ok(uv1)) = (uv0, uv1) {
3479                        let p0 = surface.evaluate(uv0.x, uv0.y);
3480                        let p1 = surface.evaluate(uv1.x, uv1.y);
3481                        if let (Ok(p0), Ok(p1)) = (p0, p1) {
3482                            let kind = match &coedge.source {
3483                                FragmentEdgeSource::Boundary { edge_id, .. } => {
3484                                    format!("bnd:{edge_id}")
3485                                }
3486                                FragmentEdgeSource::SharedBoundary { edge_id, .. } => {
3487                                    format!("sbnd:{edge_id}")
3488                                }
3489                                FragmentEdgeSource::Imprint { piece_id } => {
3490                                    format!("imp:{piece_id}")
3491                                }
3492                                FragmentEdgeSource::Derived { .. } => "derived".to_string(),
3493                            };
3494                            os_debug!(
3495                                "    loop{loop_index} {kind} ({:.4},{:.4},{:.4})..({:.4},{:.4},{:.4})",
3496                                p0.x, p0.y, p0.z, p1.x, p1.y, p1.z,
3497                            );
3498                        }
3499                    }
3500                }
3501            }
3502        }
3503        for fragment in &chosen_walls {
3504            os_debug!(
3505                "chosen wall: operand={} src={} test=({:.3},{:.3},{:.3})",
3506                fragment.operand,
3507                carriers[fragment.operand as usize].source_face_id,
3508                fragment.test_point.x,
3509                fragment.test_point.y,
3510                fragment.test_point.z,
3511            );
3512        }
3513    }
3514    // A re-run must omit something this pass did not, or it replays this pass
3515    // exactly and recurses until the stack overflows: only supports not
3516    // already omitted count. A carrier riding an omitted support's id (a
3517    // synthetic carrier the omission did not remove) reading shadowed is
3518    // refused by name instead.
3519    let already_omitted = newly_shadowed.iter().filter(|id| shadowed_supports.contains(id)).copied().collect::<Vec<_>>();
3520    newly_shadowed.retain(|id| !shadowed_supports.contains(id));
3521    if newly_shadowed.is_empty() && !already_omitted.is_empty() {
3522        let mut faces = already_omitted;
3523        faces.sort_unstable();
3524        return Err(KernelRefusal::unsupported(KernelStage::Select, refusals::SHADOW_RETRY_STALLED, format!(
3525            "offset_shell: a carrier built for the already omitted source face(s) {faces:?} reads shadowed \
3526             over its whole extent, so omitting it again cannot change the construction"
3527        )));
3528    }
3529    if !newly_shadowed.is_empty() {
3530        let mut omitted = shadowed_supports.clone();
3531        omitted.extend(newly_shadowed.iter().copied());
3532        os_debug!(
3533            "re-running without shadowed offset supports {:?} (omitted before: {:?})",
3534            newly_shadowed,
3535            shadowed_supports
3536        );
3537        // What this pass sampled belongs to carriers the next pass may not
3538        // build.
3539        shadowed_points.clear();
3540        profile::lap(&mut clock, profile::SELECT);
3541        let cascaded = !shadowed_supports.is_empty();
3542        let rebuilt = offset_shell_impl(
3543            source,
3544            opening_face_ids,
3545            distance,
3546            body,
3547            extend_oblique_carriers,
3548            extension_fired,
3549            reflex_rebuilds,
3550            &omitted,
3551            cavity_bounds,
3552            every_seeded_piece,
3553            shadowed_points,
3554            omitted_supports,
3555            vacated_notes,
3556        );
3557        let rebuilt = rebuilt?;
3558        if cascaded {
3559            refuse_a_cascade_that_kept_the_cavity(source, opening_face_ids, distance, &rebuilt.solid)?;
3560        }
3561        return Ok(rebuilt);
3562    }
3563    if chosen_offsets.is_empty() && !shadowed_supports.is_empty() {
3564        if matches!(body, Body::Shell) {
3565            if let Some(witness) = cavity_witness(source, opening_face_ids, distance)? {
3566                if !witness.bounds.is_subset(cavity_bounds) {
3567                    let mut bounds = cavity_bounds.clone();
3568                    bounds.extend(witness.bounds.iter().copied());
3569                    os_debug!(
3570                        "every skin read shadowed, but ({:.4}, {:.4}, {:.4}) lies {:.6} from every retained face: re-running with faces {:?} kept",
3571                        witness.point.x, witness.point.y, witness.point.z, witness.clearance, bounds
3572                    );
3573                    shadowed_points.clear();
3574                    profile::lap(&mut clock, profile::SELECT);
3575                    return offset_shell_impl(
3576                        source,
3577                        opening_face_ids,
3578                        distance,
3579                        body,
3580                        extend_oblique_carriers,
3581                        extension_fired,
3582                        reflex_rebuilds,
3583                        &HashSet::default(),
3584                        &bounds,
3585                        every_seeded_piece,
3586                        shadowed_points,
3587                        omitted_supports,
3588                        vacated_notes,
3589                    );
3590                }
3591                return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_cavity_unbuilt", format!(
3592                    "offset_shell: a cavity remains at this distance (the point ({:.4}, {:.4}, {:.4}) is {:.4} from \
3593                     every retained face, past the shell distance {distance}), but every offset skin around it \
3594                     reads as covered by another face, so it could not be built; returning the solid unchanged \
3595                     would be wrong — use a smaller shell distance",
3596                    witness.point.x, witness.point.y, witness.point.z, witness.clearance
3597                )));
3598            }
3599            if let Some(unchanged) = empty_cavity_shell(source, opening_face_ids, distance)? {
3600                return Ok(unchanged);
3601            }
3602        }
3603        let mut omitted = shadowed_supports.iter().copied().collect::<Vec<_>>();
3604        omitted.sort_unstable();
3605        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_all_shadowed", format!(
3606            "offset_shell: no retained face keeps any offset skin once the shadowed offsets of \
3607             source faces {omitted:?} are omitted — the solid is nowhere thicker than twice the \
3608             shell distance, so there is no cavity to shell"
3609        )));
3610    }
3611    if chosen_offsets.is_empty() {
3612        // NO SKIN, NONE SHADOWED (`BREP_OFFSET_SHELL_EMPTY_CAVITY`, default on; `=0` restores): every offset
3613        // skin lies wholly outside the solid, so none was selected, though no support read
3614        // shadowed (a cone r 3 h 4 open at its base at wall 2.5: its offset cone's own apex falls
3615        // below the opening plane). That is the empty cavity the shadowed branch above answers
3616        // with the solid unchanged; it is answered the same way, on the same two readings: no
3617        // witness of a cavity, and no point of the solid farther than the wall from every
3618        // retained face.
3619        if matches!(body, Body::Shell) && empty_cavity_any_enabled() && cavity_witness(source, opening_face_ids, distance)?.is_none() {
3620            if let Some(unchanged) = empty_cavity_shell(source, opening_face_ids, distance)? {
3621                os_debug!("no offset skin was selected and no cavity remains: the solid is its own shell");
3622                return Ok(unchanged);
3623            }
3624        }
3625        return Err(KernelRefusal::internal(KernelStage::Select, "offset_shell_no_boundary", "offset_shell: carrier intersections produced no offset boundary"));
3626    }
3627    // Opening-wall fragments can overlap at dense carrier junctions. The
3628    // seed-time guard above handles geometric containment; this final pass
3629    // mirrors the topology-level rule and counts exact fragment edge sources.
3630    let mut boundary_use_count = HashMap::<[i64; 9], usize>::default();
3631    for fragment in &chosen_offsets {
3632        for coedge in fragment
3633            .loops
3634            .iter()
3635            .flat_map(|loop_record| &loop_record.coedges)
3636        {
3637            let key = fragment_edge_segment_key(&coedge.source, &assembly_sources, &imprint)?;
3638            *boundary_use_count.entry(key).or_default() += 1;
3639        }
3640    }
3641    let mut manifold_walls = Vec::new();
3642    for fragment in chosen_walls {
3643        let keys = fragment
3644            .loops
3645            .iter()
3646            .flat_map(|loop_record| &loop_record.coedges)
3647            .map(|coedge| fragment_edge_segment_key(&coedge.source, &assembly_sources, &imprint))
3648            .collect::<Result<Vec<_>, _>>()?;
3649        if !keys
3650            .iter()
3651            .any(|key| boundary_use_count.get(key).copied().unwrap_or(0) >= 2)
3652        {
3653            for key in keys {
3654                *boundary_use_count.entry(key).or_default() += 1;
3655            }
3656            manifold_walls.push(fragment);
3657        }
3658    }
3659    os_debug!(
3660        "manifold walls kept: {} operands={:?}",
3661        manifold_walls.len(),
3662        manifold_walls
3663            .iter()
3664            .map(|fragment| fragment.operand)
3665            .collect::<Vec<_>>(),
3666    );
3667    let mut chosen_walls = manifold_walls;
3668    // A part of the selected cavity skin with no path to an opening wall is a
3669    // SEALED hollow; named only if the assembly then refuses.
3670    let sealed = if sealed_hollow_on() && body == Body::Shell {
3671        sealed_skins(&chosen_offsets, &chosen_walls, &assembly_sources, &imprint, |fragment| {
3672            carriers[fragment.operand as usize].source_face_id
3673        })?
3674    } else {
3675        Vec::new()
3676    };
3677    // EVERY SKIN SEALED (`BREP_OFFSET_SHELL_SEALED_OPENINGS_WHOLE`, default on; `=0` restores): no selected
3678    // skin reaches an opening, so the cavity is a closed void below them and each opening face
3679    // stays as it is. Its wall fragments were cut by the skins' carriers PAST the cavity's own
3680    // end (the 8 x 8 pyramid cut at 4, shelled open at its top at 1.9: the sides' offsets cross
3681    // at z 3.75 and their mirrored continuations cut the opening in a square 0.25 across, which
3682    // the wall selection dropped as the cavity's mouth and nothing filled). The opening faces
3683    // are kept whole from the source instead of as wall fragments.
3684    // A skin with an edge cut by an opening's wall carrier reaches that opening, whatever the
3685    // fragment connectivity reads (a pinched lemon shelled through both caps reads sealed by it).
3686    let reaches_an_opening = || {
3687        chosen_offsets.iter().flat_map(|fragment| fragment.loops.iter().flat_map(|loop_record| &loop_record.coedges)).any(|coedge| {
3688            let FragmentEdgeSource::Imprint { piece_id } = &coedge.source else { return false };
3689            imprint.pieces.iter().find(|piece| piece.id == *piece_id).is_some_and(|piece| {
3690                piece.support_faces.iter().any(|key| carriers.get(key.operand as usize).is_some_and(|carrier| carrier.kind == OffsetFaceRole::Wall))
3691            })
3692        })
3693    };
3694    // ... or whose edge lies on an opening face (a carrier reaching its opening plane meets it
3695    // along its own boundary, not an imprint).
3696    let touches_an_opening = || -> Result<bool, KernelRefusal> {
3697        let openings = source.shells.iter().flat_map(|shell| &shell.faces).filter(|face| opening_face_ids.contains(&face.id)).collect::<Vec<_>>();
3698        let band = 1e-7 * crate::solid_scale(source).max(1.0);
3699        for (_, middle) in sealed.iter().flat_map(|skin| &skin.edge_middles) {
3700            for face in &openings {
3701                let Ok(foot) = crate::project_point_to_surface(&face.surface, *middle) else { continue };
3702                if foot.distance <= band
3703                    && parameter_point_in_face(face, Vec2 { x: foot.u, y: foot.v }, 1e-9).or_refuse(KernelStage::Select, "parameter_point_in_face")? != PolygonClass::Outside
3704                {
3705                    return Ok(true);
3706                }
3707            }
3708        }
3709        Ok(false)
3710    };
3711    let all_sealed = sealed_openings_whole_on()
3712        && !chosen_offsets.is_empty()
3713        && sealed.iter().map(|skin| skin.fragments).sum::<usize>() == chosen_offsets.len()
3714        && !reaches_an_opening()
3715        && !touches_an_opening()?;
3716    if all_sealed {
3717        os_debug!("every selected skin is sealed: the openings stay whole");
3718        chosen_walls.clear();
3719    }
3720    if !sealed.is_empty() {
3721        os_debug!(
3722            "sealed skins: {:?}",
3723            sealed.iter().map(|skin| (&skin.sources, skin.centre, skin.edge_middles.len())).collect::<Vec<_>>()
3724        );
3725    }
3726
3727    profile::lap(&mut clock, profile::SELECT);
3728    let stage_clock = web_time::Instant::now();
3729    // The offset BODY has no source face in it: it is the skins (and the held
3730    // faces) alone, oriented as the source is, so nothing is flipped either.
3731    let source_fragments = if body == Body::Whole {
3732        Vec::new()
3733    } else {
3734        fragment_solid(source, SOURCE_OPERAND, &empty_imprint())?
3735    };
3736    os_debug!("stage: source fragments {:.3}s", stage_clock.elapsed().as_secs_f64());
3737    let mut selected = source_fragments
3738        .into_iter()
3739        .filter(|fragment| retained.contains(&fragment.source_face_id) || (all_sealed && opening_face_ids.contains(&fragment.source_face_id)))
3740        .collect::<Vec<_>>();
3741    let mut face_images = selected
3742        .iter()
3743        .map(|fragment| OffsetShellFaceImageRecord {
3744            role: OffsetFaceRole::Source,
3745            source_face_id: fragment.source_face_id,
3746        })
3747        .collect::<Vec<_>>();
3748    if distance < 0.0 {
3749        for fragment in &mut selected {
3750            flip_fragment(fragment)?;
3751        }
3752    }
3753    if distance > 0.0 && body == Body::Shell {
3754        for fragment in &mut chosen_offsets {
3755            flip_fragment(fragment)?;
3756        }
3757    }
3758    face_images.extend(
3759        chosen_offsets
3760            .iter()
3761            .map(|fragment| OffsetShellFaceImageRecord {
3762                role: OffsetFaceRole::Offset,
3763                source_face_id: carriers[fragment.operand as usize].source_face_id,
3764            }),
3765    );
3766    face_images.extend(
3767        chosen_walls
3768            .iter()
3769            .map(|fragment| OffsetShellFaceImageRecord {
3770                role: OffsetFaceRole::Wall,
3771                source_face_id: carriers[fragment.operand as usize].source_face_id,
3772            }),
3773    );
3774    selected.extend(chosen_offsets);
3775    selected.extend(chosen_walls);
3776    // `BREP_OFFSET_THIN_SKIN_PAD`: the same fixed 2e-3 floor as the skin band
3777    // welded the 1e-3 rim of box-paper-thin into points (every rim edge
3778    // degenerate, the rim eight one-face shells, the volume short by the
3779    // rim's 0.072); a thin inward shell's weld is held to a quarter of it.
3780    let mut assembly_weld = 2e-3f64.max(scale * 5e-5);
3781    if thin_skin_pad_enabled() && distance > 0.0 {
3782        assembly_weld = assembly_weld.min(0.25 * distance.abs());
3783    }
3784    let mut solid = profile::detail("assemble_open_fragments", || assemble_open_fragments(
3785        selected,
3786        &assembly_sources,
3787        &imprint,
3788        assembly_weld,
3789    ))?;
3790    os_debug!("stage: assembled open fragments {:.3}s", stage_clock.elapsed().as_secs_f64());
3791    profile::detail("orient_open_solid_faces", || orient_open_solid_faces(&mut solid))?;
3792    os_debug!("stage: oriented {:.3}s", stage_clock.elapsed().as_secs_f64());
3793    let connector_images = profile::detail("complete_sharp_offset_connectors", || complete_sharp_offset_connectors(
3794        &mut solid,
3795        source,
3796        &face_images,
3797        distance,
3798        2e-3f64.max(scale * 5e-5),
3799    ))?;
3800    os_debug!(
3801        "sharp connector completion added {} faces ({:.3}s)",
3802        connector_images.len(),
3803        stage_clock.elapsed().as_secs_f64()
3804    );
3805    if !connector_images.is_empty() {
3806        // Wall fragments were arranged before the sharp seam was closed, so
3807        // their prospective inner boundary was an open chain. Rebuild the
3808        // wall from the now-closed source/offset cycles instead of retaining
3809        // that pre-connector fragment.
3810        for shell in &mut solid.shells {
3811            shell.faces.retain(|face| {
3812                !matches!(
3813                    face_images
3814                        .get(face.id.saturating_sub(1) as usize)
3815                        .map(|image| image.role),
3816                    Some(OffsetFaceRole::Wall)
3817                )
3818            });
3819        }
3820        solid.shells.retain(|shell| !shell.faces.is_empty());
3821    }
3822    face_images.extend(connector_images);
3823    profile::detail("orient_open_solid_faces", || orient_open_solid_faces(&mut solid))?;
3824    // Weld curved-face offset rims that the wall fragmentation left orphaned
3825    // into their coplanar opening cap (cylinder / straight-hole shells). This
3826    // is the seam-rim consistency step the offset pipeline previously lacked.
3827    let welded_rims = profile::detail("weld_coplanar_orphan_rims", || weld_coplanar_orphan_rims(&mut solid, 2e-3f64.max(scale * 5e-5)))?;
3828    os_debug!("welded {welded_rims} coplanar orphan rims into opening caps");
3829    // A rim that is not a circle: a free-form or non-iso rim whose offset image
3830    // falls short of the opening. It runs after every earlier weld because it
3831    // only ever sees rims none of them closed.
3832    let rim_band = profile::detail("weld_free_form_rim_bands", || weld_free_form_rim_bands(
3833        &mut solid,
3834        &mut face_images,
3835        &carriers,
3836        source,
3837        2e-3f64.max(scale * 5e-5),
3838    ))?;
3839    let rim_bands = rim_band.welded;
3840    os_debug!("welded {rim_bands} free-form rim bands");
3841    // Weld leftover coaxial coplanar rim PAIRS (a through-hole's exposed wall
3842    // thickness at each opening) into new planar annulus faces.
3843    let pair_rims =
3844        profile::detail("weld_coplanar_rim_pair_annuli", || weld_coplanar_rim_pair_annuli(&mut solid, &mut face_images, 2e-3f64.max(scale * 5e-5)))?;
3845    os_debug!("welded {pair_rims} coplanar rim pairs into annulus walls");
3846    if debug_enabled() {
3847        for (shell_index, shell) in solid.shells.iter().enumerate() {
3848            for face in &shell.faces {
3849                os_debug!(
3850                    "POSTWELD shell {} face {} same_sense={} loops={}",
3851                    shell_index,
3852                    face.id,
3853                    face.same_sense,
3854                    face.loops.len()
3855                );
3856                for (loop_index, loop_record) in face.loops.iter().enumerate() {
3857                    let walk = loop_record
3858                        .coedges
3859                        .iter()
3860                        .map(|coedge| {
3861                            let spin = (|| -> Result<f64, KernelRefusal> {
3862                                let [d0, d1] = coedge.pcurve.domain().or_refuse(KernelStage::Sew, "domain")?;
3863                                let a = coedge.pcurve.evaluate(d0 + (d1 - d0) * 0.45).or_refuse(KernelStage::Sew, "evaluate")?;
3864                                let b = coedge.pcurve.evaluate(d0 + (d1 - d0) * 0.55).or_refuse(KernelStage::Sew, "evaluate")?;
3865                                let pa = face.surface.evaluate(a.x, a.y).or_refuse(KernelStage::Sew, "evaluate")?;
3866                                let pb = face.surface.evaluate(b.x, b.y).or_refuse(KernelStage::Sew, "evaluate")?;
3867                                Ok(pa.cross(pb).z)
3868                            })()
3869                            .unwrap_or(f64::NAN);
3870                            format!(
3871                                "{}{}(spin{:+.0})",
3872                                if coedge.forward { "+" } else { "-" },
3873                                coedge.edge_id,
3874                                spin.signum()
3875                            )
3876                        })
3877                        .collect::<Vec<_>>();
3878                    os_debug!("    loop {} {:?}", loop_index, walk);
3879                }
3880            }
3881        }
3882    }
3883    let completion_carriers = carriers.iter().collect::<Vec<_>>();
3884    let completion_tolerance = 2e-3f64.max(scale * 5e-5);
3885    // Unify geometric duplicate arc records BEFORE completion: a ring that is
3886    // already covered by both its faces (frustum + apex cap) must not read as
3887    // an open boundary, or completion papers over it with duplicate faces.
3888    let duplicate_welds = profile::detail("weld_duplicate_one_use_arcs", || weld_duplicate_one_use_arcs(&mut solid, completion_tolerance))?;
3889    os_debug!("welded {duplicate_welds} duplicate one-use boundary arcs");
3890    if debug_enabled() {
3891        let mut use_counts = HashMap::<u64, usize>::default();
3892        for coedge in solid
3893            .shells
3894            .iter()
3895            .flat_map(|shell| &shell.faces)
3896            .flat_map(|face| &face.loops)
3897            .flat_map(|loop_record| &loop_record.coedges)
3898        {
3899            *use_counts.entry(coedge.edge_id).or_default() += 1;
3900        }
3901        let open = use_counts.values().filter(|count| **count == 1).count();
3902        os_debug!(
3903            "assembled: faces={} open_edges={open}",
3904            solid
3905                .shells
3906                .iter()
3907                .map(|shell| shell.faces.len())
3908                .sum::<usize>()
3909        );
3910    }
3911    let completed_images = profile::detail("complete_opening_boundary_cycles", || complete_opening_boundary_cycles(
3912        &mut solid,
3913        &completion_carriers,
3914        &face_images,
3915        completion_tolerance,
3916    ))?;
3917    os_debug!("completion added {} faces", completed_images.len());
3918    face_images.extend(completed_images);
3919    let solid = profile::detail("merge_same_surface_faces_open", || merge_same_surface_faces_open(&solid, (1e-7f64).max(scale * 1e-9)))?;
3920    let assembly_tolerance = 2e-3f64.max(scale * 5e-5);
3921    // No faceted fallback here: an offset shell must be made of real analytic
3922    // surfaces. Failing loudly beats silently returning a tessellated BREP
3923    // with destroyed face provenance.
3924    // A shell the rim band lane recognized but could not close fails here as it
3925    // always did; the refusal now carries the lane's reason.
3926    let finalized = profile::detail("finalize_assembled_solid", || finalize_assembled_solid(solid, assembly_tolerance)).map_err(|error| {
3927        match &rim_band.decline {
3928            Some(reason) => error.with_message(|message| format!("{message}; offset_shell: {reason}")),
3929            None => error,
3930        }
3931    });
3932    let mut solid = match finalized {
3933        Ok(solid) => solid,
3934        Err(error) => {
3935            os_debug!("finalize_assembled_solid: {}", error.message);
3936            if !every_seeded_piece && body == Body::Shell && distance > 0.0 && every_seeded_skin_piece_enabled() {
3937                let retried = offset_shell_impl(
3938                    source,
3939                    opening_face_ids,
3940                    distance,
3941                    body,
3942                    extend_oblique_carriers,
3943                    extension_fired,
3944                    reflex_rebuilds,
3945                    shadowed_supports,
3946                    cavity_bounds,
3947                    true,
3948                    shadowed_points,
3949                    omitted_supports,
3950                    vacated_notes,
3951                );
3952                if retried.is_ok() {
3953                    return retried;
3954                }
3955            }
3956            if let Some((index, own, other, thickness)) = sealing_distance(
3957                &sealed,
3958                source,
3959                &retained_faces_with_edges,
3960                distance,
3961                offset_skin_tolerance,
3962            )? {
3963                let skin = &sealed[index];
3964                let bounding = skin.sources.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
3965                return Err(KernelRefusal::unsupported(KernelStage::Sew, refusals::SEALED_HOLLOW, format!(
3966                    "offset_shell: at this distance the cavity splits — a hollow bounded by the offsets of \
3967                     source faces {bounding} near ({:.4}, {:.4}, {:.4}) is sealed off from the opening, and a \
3968                     sealed hollow could not be assembled here. It is closed off where the offsets of source \
3969                     faces {own} and {other} cross, which they do from {:.4} up ({thickness:.4} of material \
3970                     between them); below {:.4} it opens into the rest of the cavity, so use a shell distance \
3971                     below that",
3972                    skin.centre.x,
3973                    skin.centre.y,
3974                    skin.centre.z,
3975                    0.5 * thickness,
3976                    0.5 * thickness,
3977                )));
3978            }
3979            return Err(error);
3980        }
3981    };
3982    profile::detail("reconstruct_analytic_shell", || crate::offset_retrim::reconstruct_analytic_shell(&mut solid))?;
3983    if rim_bands + pair_rims > 0 || !inward_extended_walls.is_empty() {
3984        // Rim welds and extended reflex walls join independently-oriented skins;
3985        // put the whole finalized manifold on one normal convention so the
3986        // shell reports its exact wall volume (coplanar-only shells keep
3987        // their assembled sense).
3988        profile::detail("coheres_face_normals", || coheres_face_normals(&mut solid))?;
3989    }
3990    let solid = solid;
3991    profile::lap(&mut clock, profile::ASSEMBLY);
3992    face_images = solid
3993        .shells
3994        .iter()
3995        .flat_map(|shell| &shell.faces)
3996        .map(|face| {
3997            face_images
3998                .get(face.id.saturating_sub(1) as usize)
3999                .cloned()
4000                .ok_or_else(|| "offset_shell: merged face lost provenance".to_string())
4001        })
4002        .collect::<Result<Vec<_>, _>>().or_refuse(KernelStage::Sew, "offset_shell_merged_face_lost_provenance")?;
4003    // A bore's end ring carries the bore wall's provenance whichever
4004    // construction built it (the opening's fragmentation or the rim-pair
4005    // weld), so its name does not depend on the path the rims took.
4006    let bore_rings = claim_bore_end_rings(&solid, &mut face_images)?;
4007    os_debug!("{bore_rings} bore end rings took the bore wall's provenance");
4008    // Honesty gate: a real rim left one-use is a hole in the shell that the
4009    // degenerate marking hides from `validate()` (degenerate edges are allowed
4010    // to be face-local). Refuse such a result instead of shipping a
4011    // non-watertight solid as valid. A rim is a CLOSED edge whose interior
4012    // sweeps measurably away from its seam vertex — a genuine circle, not a
4013    // legitimate pole point placeholder (which stays one-use by design).
4014    let mut rim_use_counts = HashMap::<u64, usize>::default();
4015    for coedge in solid
4016        .shells
4017        .iter()
4018        .flat_map(|shell| &shell.faces)
4019        .flat_map(|face| &face.loops)
4020        .flat_map(|loop_record| &loop_record.coedges)
4021    {
4022        *rim_use_counts.entry(coedge.edge_id).or_default() += 1;
4023    }
4024    if debug_enabled() {
4025        for (shell_index, shell) in solid.shells.iter().enumerate() {
4026            for face in &shell.faces {
4027                let role = face_images
4028                    .get(face.id.saturating_sub(1) as usize)
4029                    .map(|image| image.role);
4030                let c = face.surface.evaluate(0.5, 0.5).unwrap_or_default();
4031                os_debug!(
4032                    "DUMPFACE shell {} face {} affine={} role={:?} loops={} center=({:.3},{:.3},{:.3})",
4033                    shell_index, face.id, face.surface.is_affine().unwrap_or(false), role,
4034                    face.loops.len(), c.x, c.y, c.z
4035                );
4036                for (li, lp) in face.loops.iter().enumerate() {
4037                    let ids = lp.coedges.iter().map(|c| c.edge_id).collect::<Vec<_>>();
4038                    os_debug!("    loop {} edges {:?}", li, ids);
4039                }
4040            }
4041        }
4042        for edge in &solid.edges {
4043            let uses = rim_use_counts.get(&edge.id).copied().unwrap_or(0);
4044            let s = edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?;
4045            let m = edge.curve.evaluate((edge.t0 + edge.t1) * 0.5).or_refuse(KernelStage::Sew, "evaluate")?;
4046            let q = edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * 0.25).or_refuse(KernelStage::Sew, "evaluate")?;
4047            os_debug!(
4048                "DUMPEDGE edge {} uses={} closed={} deg={} cpts={} cdeg={} knots={:?} start=({:.3},{:.3},{:.3}) q=({:.3},{:.3},{:.3}) mid=({:.3},{:.3},{:.3})",
4049                edge.id, uses, edge.start_vertex_id == edge.end_vertex_id, edge.degenerate,
4050                edge.curve.control_points.len(), edge.curve.degree, edge.curve.knots,
4051                s.x, s.y, s.z, q.x, q.y, q.z, m.x, m.y, m.z
4052            );
4053        }
4054    }
4055    for edge in &solid.edges {
4056        if rim_use_counts.get(&edge.id).copied().unwrap_or(0) != 1
4057            || edge.start_vertex_id != edge.end_vertex_id
4058        {
4059            continue;
4060        }
4061        let anchor = edge.curve.evaluate(edge.t0).or_refuse(KernelStage::Sew, "evaluate")?;
4062        let sweep_threshold = 1e-4f64.max(scale * 1e-6);
4063        let sweeps = [0.25, 0.5, 0.75].into_iter().any(|fraction| {
4064            edge.curve
4065                .evaluate(edge.t0 + (edge.t1 - edge.t0) * fraction)
4066                .map(|point| point.sub(anchor).length() > sweep_threshold)
4067                .unwrap_or(false)
4068        });
4069        if sweeps {
4070            if debug_enabled() {
4071                let rim_mid = edge.curve.evaluate((edge.t0 + edge.t1) * 0.5).or_refuse(KernelStage::Sew, "evaluate")?;
4072                os_debug!(
4073                    "PROBE orphan rim edge {} anchor=({:.4},{:.4},{:.4}) mid=({:.4},{:.4},{:.4})",
4074                    edge.id,
4075                    anchor.x,
4076                    anchor.y,
4077                    anchor.z,
4078                    rim_mid.x,
4079                    rim_mid.y,
4080                    rim_mid.z
4081                );
4082                for (shell_index, shell) in solid.shells.iter().enumerate() {
4083                    for face in &shell.faces {
4084                        let uses_rim = face
4085                            .loops
4086                            .iter()
4087                            .flat_map(|l| &l.coedges)
4088                            .any(|c| c.edge_id == edge.id);
4089                        let affine = face.surface.is_affine().unwrap_or(false);
4090                        let on = edge_on_surface(edge, &face.surface, 2e-3f64.max(scale * 5e-5))
4091                            .unwrap_or(false);
4092                        let proj = project_point_to_surface(&face.surface, rim_mid).or_refuse(KernelStage::Sew, "project_point_to_surface")?;
4093                        let contains = if on {
4094                            parameter_point_in_face(
4095                                face,
4096                                Vec2 {
4097                                    x: proj.u,
4098                                    y: proj.v,
4099                                },
4100                                2e-3f64.max(scale * 5e-5),
4101                            ).or_refuse(KernelStage::Sew, "parameter_point_in_face")? != PolygonClass::Outside
4102                        } else {
4103                            false
4104                        };
4105                        if on || uses_rim {
4106                            os_debug!(
4107                                "  face {} shell {} affine={} uses_rim={} on_surf={} proj_dist={:.5} contains={}",
4108                                face.id, shell_index, affine, uses_rim, on, proj.distance, contains
4109                            );
4110                        }
4111                    }
4112                }
4113            }
4114            // The pieces a single seed missed leave their outlines one-use
4115            // here as at the assembly's own exit: the same retry answers it.
4116            if !every_seeded_piece && body == Body::Shell && distance > 0.0 && every_seeded_skin_piece_enabled() {
4117                let retried = offset_shell_impl(
4118                    source,
4119                    opening_face_ids,
4120                    distance,
4121                    body,
4122                    extend_oblique_carriers,
4123                    extension_fired,
4124                    reflex_rebuilds,
4125                    shadowed_supports,
4126                    cavity_bounds,
4127                    true,
4128                    shadowed_points,
4129                    omitted_supports,
4130                    vacated_notes,
4131                );
4132                if retried.is_ok() {
4133                    return retried;
4134                }
4135            }
4136            return Err(refusals::unwelded_curved_rim(edge.id, anchor).into());
4137        }
4138    }
4139    // The shell's single exit. An offset skin that crosses another wall, or
4140    // folds through itself where the source turned tighter than the distance,
4141    // leaves a body that validates and measures — so it is asked here, and
4142    // repaired or refused by name rather than returned.
4143    let mut solid = solid;
4144    // Face-local rim construction and planar merging can reuse wire IDs.
4145    // Reserve every existing ID, then replace only duplicates so the completed
4146    // body can cross the arena/buffer ingestion boundary. These IDs have no
4147    // external references; face/edge identities and provenance stay intact.
4148    let mut loop_ids = HashSet::default();
4149    let mut coedge_ids = HashSet::default();
4150    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
4151        for wire in &face.loops {
4152            loop_ids.insert(wire.id);
4153            coedge_ids.extend(wire.coedges.iter().map(|coedge| coedge.id));
4154        }
4155    }
4156    let mut seen_loops = HashSet::default();
4157    let mut seen_coedges = HashSet::default();
4158    let mut next_loop = 1;
4159    let mut next_coedge = 1;
4160    for face in solid.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
4161        for wire in &mut face.loops {
4162            if !seen_loops.insert(wire.id) {
4163                while !loop_ids.insert(next_loop) { next_loop += 1; }
4164                wire.id = next_loop;
4165            }
4166            for coedge in &mut wire.coedges {
4167                if !seen_coedges.insert(coedge.id) {
4168                    while !coedge_ids.insert(next_coedge) { next_coedge += 1; }
4169                    coedge.id = next_coedge;
4170                }
4171            }
4172        }
4173    }
4174    let solid = profile::detail("accept_offset_result", || super::acceptance::accept_offset_result(solid))?;
4175    profile::lap(&mut clock, profile::ACCEPTANCE);
4176    Ok(OffsetShellResultRecord { solid, face_images })
4177}
4178
4179/// Run offset shell with stable counters and validation diagnostics suitable
4180/// for automated regressions and UI presentation.
4181pub fn offset_shell_with_diagnostics(
4182    source: &BrepSolid,
4183    opening_face_ids: &[u64],
4184    distance: f64,
4185    tolerances: Option<KernelTolerances>,
4186) -> Result<KernelOutcome<OffsetShellResultRecord>, KernelRefusal> {
4187    if let Some(scaled) = crate::rescale::ScaledOffset::of(source, distance, "offset_shell")? {
4188        let mut outcome = offset_shell_with_diagnostics(&scaled.source, opening_face_ids, scaled.distance, tolerances)
4189            .map_err(|error| scaled.refusal(error))?;
4190        outcome.value.solid = scaled.back(&outcome.value.solid, "offset_shell")?;
4191        outcome.diagnostics.count_n("working_scale.fired", 1);
4192        outcome.diagnostics.measure_max("working_scale.factor", scaled.factor);
4193        return Ok(outcome);
4194    }
4195    let policy = tolerances.unwrap_or_else(|| KernelTolerances::for_solid(source, 1e-7));
4196    policy.check().or_refuse(KernelStage::Sew, "check")?;
4197    let mut diagnostics = KernelDiagnostics::default();
4198    diagnostics.count_n(
4199        "collect.source_faces",
4200        source
4201            .shells
4202            .iter()
4203            .map(|shell| shell.faces.len() as u64)
4204            .sum(),
4205    );
4206    diagnostics.count_n("collect.opening_faces", opening_face_ids.len() as u64);
4207    diagnostics.measure_max("offset.distance", distance.abs());
4208    diagnostics.measure_max("tolerance.model", policy.model);
4209    // Tally every pcurve fit the shell makes (its own re-trims and any boolean
4210    // it runs) so `pcurve.unmet_floor` reports a trim that stopped at the
4211    // sample ceiling instead of passing it off as one that met the floor.
4212    let fit_scope = crate::PcurveFitScope::open();
4213    // Same for the polyline fits of its carrier×carrier sections, which is
4214    // where a marched rim's accuracy is decided (`geometry/fit.rs`).
4215    let polyline_scope = crate::PolylineFitScope::open();
4216    let result = offset_shell(source, opening_face_ids, distance)?;
4217    fit_scope.close().report_into(&mut diagnostics);
4218    polyline_scope.close().report_into(&mut diagnostics);
4219    // The phase split of the run that just finished (`profile.rs`), in the
4220    // boolean's `timing.<phase>_ms` shape so one reader serves both.
4221    let timings = profile::snapshot();
4222    diagnostics.count_n("shell.attempts", timings.attempts);
4223    for (phase, count) in &timings.carriers {
4224        diagnostics.count_n(format!("shell.{phase}"), *count);
4225    }
4226    for (phase, ms) in &timings.ms {
4227        diagnostics.measure_max(format!("timing.{phase}_ms"), *ms);
4228    }
4229    diagnostics.count_n(
4230        "sew.output_faces",
4231        result
4232            .solid
4233            .shells
4234            .iter()
4235            .map(|shell| shell.faces.len() as u64)
4236            .sum(),
4237    );
4238    diagnostics.count_n("sew.face_images", result.face_images.len() as u64);
4239    let validation = result.solid.validate_detailed(&policy);
4240    diagnostics.measure_max("validate.max_pcurve_error", validation.max_pcurve_error);
4241    diagnostics.count_n("validate.issues", validation.issues.len() as u64);
4242    diagnostics.count_n(
4243        "validate.wire_warnings",
4244        validation.wire_warnings.len() as u64,
4245    );
4246    for warning in validation.wire_warnings {
4247        diagnostics.event(
4248            DiagnosticSeverity::Warning,
4249            KernelStage::Validate,
4250            "validate.uv_wire",
4251            warning.message,
4252        );
4253    }
4254    if !validation.issues.is_empty() {
4255        for issue in &validation.issues {
4256            diagnostics.event(
4257                DiagnosticSeverity::Error,
4258                KernelStage::Validate,
4259                "validate.brep",
4260                issue.message.clone(),
4261            );
4262        }
4263        return Err(KernelRefusal::internal(KernelStage::Validate, "offset_shell_diagnostic_result", format!(
4264            "offset_shell: invalid diagnostic result: {:?}",
4265            validation.issues
4266        )));
4267    }
4268    Ok(KernelOutcome {
4269        value: result,
4270        diagnostics,
4271    })
4272}
4273
4274/// Whether a wall fragment lies wholly in the wall's surplus: it has an edge on
4275/// the wall carrier's own outline (`Boundary` of operand `wall_operand`) and no
4276/// edge imprinted by the SOURCE solid, whose rim every genuine opening-wall
4277/// region borders. `cut_by_source` answers whether an imprint piece has the
4278/// source among its two support faces.
4279pub fn wall_surplus_beyond_the_sections(
4280    fragment: &FaceFragmentRecord,
4281    wall_operand: u8,
4282    cut_by_source: impl Fn(u64) -> bool,
4283) -> bool {
4284    let mut on_outline = false;
4285    for coedge in fragment.loops.iter().flat_map(|record| &record.coedges) {
4286        match &coedge.source {
4287            FragmentEdgeSource::Boundary { operand, .. } if *operand == wall_operand => on_outline = true,
4288            FragmentEdgeSource::Boundary { operand, .. } | FragmentEdgeSource::SharedBoundary { operand, .. }
4289                if *operand == SOURCE_OPERAND =>
4290            {
4291                return false;
4292            }
4293            FragmentEdgeSource::Imprint { piece_id } => {
4294                if cut_by_source(*piece_id) {
4295                    return false;
4296                }
4297            }
4298            _ => {}
4299        }
4300    }
4301    on_outline
4302}
4303
4304
4305/// `BREP_OFFSET_SHELL_CASCADE_OMISSION` (default on; `=0` restores): an inward
4306/// shell judges a carrier that reads shadowed at every fragment's test point
4307/// by its true skin instead ([`fragments_holding_true_skin`]). One test point
4308/// cannot speak for a fragment that is partly skin: a reported cylinder boss model's
4309/// root fillets bound the cavity's bulge toward the boss mouth at every
4310/// distance past the boss limit (checked with
4311/// `scripts/offset_cavity_volume.py`), and were dropped as shadowed. A carrier
4312/// holding no skin at all may then be omitted even after an earlier omission.
4313fn cascade_omission_enabled() -> bool {
4314    switch!("BREP_OFFSET_SHELL_CASCADE_OMISSION", true)
4315}
4316
4317/// A cascade of omissions must leave the deepest point of the true cavity
4318/// hollow: a carrier omitted on a test point that did not stand for its
4319/// fragment would show as material there.
4320fn refuse_a_cascade_that_kept_the_cavity(
4321    source: &BrepSolid,
4322    opening_face_ids: &[u64],
4323    distance: f64,
4324    result: &BrepSolid,
4325) -> Result<(), KernelRefusal> {
4326    let Some(witness) = cavity_witness(source, opening_face_ids, distance)? else {
4327        return Ok(());
4328    };
4329    let scale = crate::solid_scale(source).max(1.0);
4330    let class = classify_point(witness.point, result, 1e-8 * scale).or_refuse(KernelStage::Select, "classify_point")?.class;
4331    if class == PointClass::In {
4332        return Err(KernelRefusal::unsupported(KernelStage::Select, "offset_shell_shadow_cascade", format!(
4333            "offset_shell: omitting offsets that read shadowed only after earlier omissions leaves material at \
4334             ({:.4}, {:.4}, {:.4}), which is {:.4} from every retained face, past the shell distance {distance}; \
4335             the cavity there could not be built — use a smaller shell distance",
4336            witness.point.x, witness.point.y, witness.point.z, witness.clearance
4337        )));
4338    }
4339    Ok(())
4340}
4341
4342/// `BREP_OFFSET_SHELL_CAVITY_WITNESS` (default on; `=0` restores): [`cavity_witness`].
4343fn retained_faces_of<'a>(retained: &[(&'a FaceRecord, Vec<&'a EdgeRecord>)]) -> Vec<&'a FaceRecord> {
4344    retained.iter().map(|(face, _)| *face).collect()
4345}
4346
4347fn sealed_openings_whole_on() -> bool {
4348    switch!("BREP_OFFSET_SHELL_SEALED_OPENINGS_WHOLE", true)
4349}
4350
4351fn empty_cavity_any_enabled() -> bool {
4352    switch!("BREP_OFFSET_SHELL_EMPTY_CAVITY", true)
4353}
4354
4355fn cavity_witness_enabled() -> bool {
4356    switch!("BREP_OFFSET_SHELL_CAVITY_WITNESS", true)
4357}
4358
4359/// A point of the solid farther than the shell distance from every retained
4360/// face, and the faces nearest it, whose skins bound that cavity.
4361#[derive(Debug)]
4362pub struct CavityWitness {
4363    pub(super) point: Vec3,
4364    pub clearance: f64,
4365    pub bounds: HashSet<u64>,
4366}
4367
4368/// Looks for the cavity the shadow reading says is not there. A fragment's
4369/// single test point can read shadowed while most of the fragment is real skin
4370/// (a reported cylinder boss model at 4.8: the r 0.2 bore of a cylinder r 5, one uncut
4371/// fragment whose test point lies 4.72 from a boss wall), and a cavity that
4372/// thin falls between the 12³ cells of [`empty_cavity_shell`], which then
4373/// returned the source as a success.
4374///
4375/// Distance to the retained faces is 1-Lipschitz, so any cavity's maximum is
4376/// climbed to from the samples that read highest: the best cell centres start
4377/// a pattern search that stays inside the solid. It is a search, not a proof;
4378/// what it cannot miss is a cavity whose ridge those starts climb.
4379pub fn cavity_witness(
4380    source: &BrepSolid,
4381    opening_face_ids: &[u64],
4382    distance: f64,
4383) -> Result<Option<CavityWitness>, KernelRefusal> {
4384    if !cavity_witness_enabled() || distance <= 0.0 || opening_face_ids.is_empty() {
4385        return Ok(None);
4386    }
4387    let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
4388    let retained = faces.iter().filter(|face| !opening_face_ids.contains(&face.id)).copied().collect::<Vec<_>>();
4389    if retained.is_empty() {
4390        return Ok(None);
4391    }
4392    // Each face's own edges: a foot off the trim falls back on the edges it is
4393    // given, and the whole solid's would read a wall as near as any rim.
4394    let edge_by_id = source.edges.iter().map(|edge| (edge.id, edge)).collect::<HashMap<_, _>>();
4395    let retained = retained
4396        .into_iter()
4397        .map(|face| {
4398            let edges = face
4399                .loops
4400                .iter()
4401                .flat_map(|loop_record| &loop_record.coedges)
4402                .filter_map(|coedge| edge_by_id.get(&coedge.edge_id).copied())
4403                .collect::<Vec<_>>();
4404            (face, edges)
4405        })
4406        .collect::<Vec<_>>();
4407    let Some((low, high)) = control_hull(source, &faces) else { return Ok(None) };
4408    let scale = crate::solid_scale(source).max(1.0);
4409    let classify_tolerance = 1e-8 * scale;
4410    let margin = 1e-6 * scale;
4411    let readings = |point: Vec3| -> Result<Vec<(u64, f64)>, KernelRefusal> {
4412        retained
4413            .iter()
4414            .map(|(face, edges)| {
4415                // `BREP_OFFSET_RULED_MITER`: a ruled face reads the mitered metric the skin test
4416                // reads it by, or the witness finds a cavity past a rim the skins never reach.
4417                let ruled = if super::carriers::ruled_miter_on() { super::carriers::ruled_miter_distance(face, edges, point, &retained_faces_of(&retained))? } else { None };
4418                Ok((face.id, match ruled {
4419                    Some(mitered) => mitered,
4420                    None => distance_to_trimmed_face(face, edges, point)?,
4421                }))
4422            })
4423            .collect()
4424    };
4425    let clearance = |values: &[(u64, f64)]| values.iter().map(|(_, value)| *value).fold(f64::INFINITY, f64::min);
4426    let inside = |point: Vec3| -> Result<bool, KernelRefusal> {
4427        Ok(classify_point(point, source, classify_tolerance).or_refuse(KernelStage::Select, "classify_point")?.class == PointClass::In)
4428    };
4429    const CELLS: usize = 12;
4430    const STARTS: usize = 24;
4431    const MOVES: usize = 160;
4432    let span = high.sub(low);
4433    let mut starts = Vec::new();
4434    for i in 0..CELLS {
4435        for j in 0..CELLS {
4436            for k in 0..CELLS {
4437                let at = |index: usize| (index as f64 + 0.5) / CELLS as f64;
4438                let point = Vec3::new(low.x + span.x * at(i), low.y + span.y * at(j), low.z + span.z * at(k));
4439                if inside(point)? {
4440                    starts.push((clearance(&readings(point)?), point));
4441                }
4442            }
4443        }
4444    }
4445    starts.sort_by(|a, b| b.0.total_cmp(&a.0));
4446    starts.truncate(STARTS);
4447    const DIRECTIONS: [(f64, f64, f64); 14] = [
4448        (1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, -1.0),
4449        (1.0, 1.0, 1.0), (-1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (-1.0, -1.0, 1.0),
4450        (1.0, -1.0, 1.0), (-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (1.0, -1.0, -1.0),
4451    ];
4452    let first_step = span.x.max(span.y).max(span.z) / CELLS as f64;
4453    let mut footless = None;
4454    for (start_clearance, start) in starts {
4455        let (mut point, mut best, mut step) = (start, start_clearance, first_step);
4456        for _ in 0..MOVES {
4457            if step < 1e-6 * scale {
4458                break;
4459            }
4460            let mut moved = false;
4461            for (x, y, z) in DIRECTIONS {
4462                let length = (x * x + y * y + z * z).sqrt();
4463                let next = Vec3::new(point.x + step * x / length, point.y + step * y / length, point.z + step * z / length);
4464                let value = clearance(&readings(next)?);
4465                if value > best && inside(next)? {
4466                    (point, best, moved) = (next, value, true);
4467                    break;
4468                }
4469            }
4470            if !moved {
4471                step *= 0.5;
4472            }
4473        }
4474        if best > distance + margin {
4475            // The climb ends on the ridge, where every face around it ties.
4476            // Nudged off the ridge, still inside the cavity, each point has one
4477            // nearest face, which counts if its foot lands inside its trim (a
4478            // tie through a face's rim is that edge, not its offset). The faces
4479            // that wrap the cavity collect the votes; a fillet seen only
4480            // through the mouth of a boss does not.
4481            let nudge = 0.5 * (best - distance);
4482            let mut votes = HashMap::<u64, usize>::default();
4483            for (x, y, z) in DIRECTIONS {
4484                let length = (x * x + y * y + z * z).sqrt();
4485                let near = Vec3::new(point.x + nudge * x / length, point.y + nudge * y / length, point.z + nudge * z / length);
4486                let values = readings(near)?;
4487                let Some((id, _)) = values.iter().min_by(|a, b| a.1.total_cmp(&b.1)).copied() else { continue };
4488                let Some((face, _)) = retained.iter().find(|(face, _)| face.id == id) else { continue };
4489                if foot_inside_trim(face, near)? {
4490                    *votes.entry(id).or_default() += 1;
4491                }
4492            }
4493            let most = votes.values().copied().max().unwrap_or(0);
4494            let bounds = votes.iter().filter(|(_, count)| **count * 2 >= most).map(|(id, _)| *id).collect::<HashSet<_>>();
4495            let witness = CavityWitness { point, clearance: best, bounds };
4496            if !witness.bounds.is_empty() {
4497                return Ok(Some(witness));
4498            }
4499            footless = Some(witness);
4500        }
4501    }
4502    Ok(footless)
4503}
4504
4505/// The box of the solid's vertices and face control points; `None` when a
4506/// control point cannot be read.
4507fn control_hull(source: &BrepSolid, faces: &[&FaceRecord]) -> Option<(Vec3, Vec3)> {
4508    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
4509    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
4510    for vertex in &source.vertices {
4511        low = Vec3::new(low.x.min(vertex.point.x), low.y.min(vertex.point.y), low.z.min(vertex.point.z));
4512        high = Vec3::new(high.x.max(vertex.point.x), high.y.max(vertex.point.y), high.z.max(vertex.point.z));
4513    }
4514    for control in faces.iter().flat_map(|face| face.surface.control_points.iter().flatten()) {
4515        let point = control.point().ok()?;
4516        low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
4517        high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
4518    }
4519    Some((low, high))
4520}
4521
4522/// `BREP_OFFSET_SHELL_EMPTY_CAVITY` (default on; `=0` restores): [`empty_cavity_shell`].
4523fn empty_cavity_enabled() -> bool {
4524    switch!("BREP_OFFSET_SHELL_EMPTY_CAVITY", true)
4525}
4526
4527
4528/// An INWARD shell whose every retained face's offset skin is shadowed: the
4529/// cavity, the points of the solid farther than `distance` from every retained
4530/// face, is empty, so the shell is the solid itself, every face its own
4531/// `Source` image (brep-bench shell/box-walls-meeting: the box 10 x 8 x 6
4532/// shelled by 4 open at its top, whose y walls' offsets meet in the plane
4533/// y = 4, was refused "no retained face keeps any offset skin ... there is no
4534/// cavity to shell"; the case reads the box, 480 and 376).
4535///
4536/// The shadow reading is checked before the solid is returned: on a 12³ grid
4537/// of cell centres over the solid's control hull, no point the solid
4538/// classifies Inside may lie farther than `distance` (plus 1e-9 of the
4539/// solid's size) from every retained face. A point that does means the
4540/// cavity is not empty, and the refusal stands.
4541fn empty_cavity_shell(
4542    source: &BrepSolid,
4543    opening_face_ids: &[u64],
4544    distance: f64,
4545) -> Result<Option<OffsetShellResultRecord>, KernelRefusal> {
4546    if !empty_cavity_enabled() || distance <= 0.0 || opening_face_ids.is_empty() {
4547        return Ok(None);
4548    }
4549    let faces = source.shells.iter().flat_map(|shell| &shell.faces).collect::<Vec<_>>();
4550    let retained = faces.iter().filter(|face| !opening_face_ids.contains(&face.id)).copied().collect::<Vec<_>>();
4551    if retained.is_empty() {
4552        return Ok(None);
4553    }
4554    let edges = source.edges.iter().collect::<Vec<_>>();
4555    let Some((low, high)) = control_hull(source, &faces) else { return Ok(None) };
4556    let scale = crate::solid_scale(source).max(1.0);
4557    let tolerance = 1e-9 * scale;
4558    const CELLS: usize = 12;
4559    let span = high.sub(low);
4560    let mut inside = 0usize;
4561    for i in 0..CELLS {
4562        for j in 0..CELLS {
4563            for k in 0..CELLS {
4564                let at = |index: usize| (index as f64 + 0.5) / CELLS as f64;
4565                let point = Vec3::new(low.x + span.x * at(i), low.y + span.y * at(j), low.z + span.z * at(k));
4566                let class = classify_point(point, source, tolerance * 10.0).or_refuse(KernelStage::Select, "classify_point")?.class;
4567                if class != PointClass::In {
4568                    continue;
4569                }
4570                inside += 1;
4571                let mut nearest = f64::INFINITY;
4572                for face in &retained {
4573                    nearest = nearest.min(distance_to_trimmed_face(face, &edges, point)?);
4574                    if nearest <= distance + tolerance {
4575                        break;
4576                    }
4577                }
4578                if nearest > distance + tolerance {
4579                    os_debug!(
4580                        "empty cavity declined: ({:.4}, {:.4}, {:.4}) lies {nearest:.6} from every retained face",
4581                        point.x, point.y, point.z
4582                    );
4583                    return Ok(None);
4584                }
4585            }
4586        }
4587    }
4588    if inside == 0 {
4589        return Ok(None);
4590    }
4591    os_debug!("empty cavity: every retained skin is shadowed and {inside} sampled interior points lie within the distance");
4592    let face_images = faces
4593        .iter()
4594        .map(|face| OffsetShellFaceImageRecord { role: OffsetFaceRole::Source, source_face_id: face.id })
4595        .collect();
4596    Ok(Some(OffsetShellResultRecord { solid: source.clone(), face_images }))
4597}
4598
4599/// `BREP_OFFSET_THIN_PAD_RECTANGLE` (default on; `=0` restores): a thin-skin
4600/// padded plane with a curved outline is trimmed by its padded rectangle, not
4601/// by its slid outline (see the carrier construction).
4602fn thin_pad_rectangle_enabled() -> bool {
4603    switch!("BREP_OFFSET_THIN_PAD_RECTANGLE", true)
4604}
4605
4606/// `BREP_OFFSET_THIN_SKIN_PAD` (default on; `=0` restores): [`thin_skin_pad`].
4607fn thin_skin_pad_enabled() -> bool {
4608    switch!("BREP_OFFSET_THIN_SKIN_PAD", true)
4609}
4610
4611
4612/// The pad of an INWARD planar carrier whose shell is thinner than the
4613/// fragmenter's graze band: `None` otherwise.
4614///
4615/// Cause (the 10 × 8 × 6 box shelled 0.001 open at its top, brep-bench
4616/// shell/box-paper-thin, read 0.1653 against 0.2959 with an open mesh): each
4617/// carrier is its source face moved 0.001, and its neighbours' skins cut it
4618/// 0.001 inside its rim, with both ends 0.001 from the carrier's corners. The
4619/// imprint's pcurves are right (v = 0.001), but `fragment_face_arranged` lets a
4620/// CUT endpoint join a boundary corner image within `arrangement_tolerance ·
4621/// 100` (1.2e-3 on a 10 × 8 chart) with no 3D check, so both ends moved onto
4622/// the corners, the cut lay on the rim and was dropped as its duplicate
4623/// ("drop cut chain 6 as duplicate of boundary chain 0"). Padded past its rims,
4624/// the carrier's corners are far from every section's ends; the surplus
4625/// strips beyond the sections are outside the source or shadowed by the
4626/// neighbours and are dropped by the ordinary selection.
4627///
4628/// Thin: `distance` under 2e-3 of the solid's size (the band is 1e-4 of a
4629/// chart's diagonal, a chart at most the solid's size). The pad is 4e-3 of
4630/// the size plus the distance.
4631///
4632/// The same switch holds the selection's skin band and the assembly's weld to
4633/// a quarter of an inward distance: both had a fixed 2e-3 floor, twice this
4634/// shell's thickness (see `offset_skin_tolerance` and `assembly_weld`).
4635fn thin_skin_pad(source: &BrepSolid, face: &FaceRecord, distance: f64) -> Result<Option<f64>, KernelRefusal> {
4636    if !thin_skin_pad_enabled() || distance <= 0.0 || !face.surface.is_affine().or_refuse(KernelStage::Refine, "is_affine")? {
4637        return Ok(None);
4638    }
4639    let size = crate::solid_scale(source).max(1e-9);
4640    if distance >= 2e-3 * size {
4641        return Ok(None);
4642    }
4643    Ok(Some(4e-3 * size + distance))
4644}