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