Skip to main content

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