Skip to main content

brep_blend/blending/fillet/
edges.rs

1use super::*;
2
3/// Constant-radius rolling-ball fillet of one edge (Golovanov §4.9 march,
4/// §6.9 surgery; the cutter only where the march refuses).
5pub fn fillet_edge(
6    solid: &BrepSolid,
7    edge_id: u64,
8    radius: f64,
9    name: Option<&str>,
10) -> Result<BrepSolid, KernelRefusal> {
11    // One blend operation: the reports of an earlier one, never consumed, are
12    // dropped as it starts (nested calls keep this operation's).
13    let _operation = crate::blend::BlendOperation::enter();
14    check_mixed_concavity(solid, edge_id, "fillet_edge")?;
15    check_support_extent_clipping(solid, edge_id, radius, "fillet_edge")?;
16    fillet_or_chamfer(solid, edge_id, radius, false, name, ToolEnds::default(), Lane::GeneralFirst)
17        .map_err(|refusal| size_refusal(solid, edge_id, radius, false, name, "fillet_edge", refusal))
18}
19
20/// A blend refused because the rolling ball's contact system has no solution
21/// (`Newton is singular`) says so by name, with the size that does build.
22///
23/// A ball that does not fit beside the edge has no contact points to solve
24/// for: on the rim of a bore through a fillet (a wall 1.5 thick between the
25/// bore and the fillet's torus) no ball wider than the wall rolls, and every
26/// lane's solver stops singular, which was reported as an internal error of
27/// three lanes. A chamfer's distance is its ball's radius, so the same holds
28/// for it. This runs only after such a refusal: the same blend is tried at
29/// half, a quarter and an eighth of the size, and where one builds the
30/// largest size that does is bracketed in five more tries and named. Where
31/// none builds, the refusal is returned as it came.
32fn size_refusal(
33    solid: &BrepSolid,
34    edge_id: u64,
35    size: f64,
36    chamfer: bool,
37    name: Option<&str>,
38    entry: &str,
39    refusal: KernelRefusal,
40) -> KernelRefusal {
41    if !refusal.message.contains("Newton is singular") {
42        return refusal;
43    }
44    let builds = |size: f64| fillet_or_chamfer(solid, edge_id, size, chamfer, name, ToolEnds::default(), Lane::GeneralFirst).is_ok();
45    let mut too_large = size;
46    let mut fits = None;
47    for fraction in [0.5, 0.25, 0.125] {
48        if builds(size * fraction) {
49            fits = Some(size * fraction);
50            break;
51        }
52        too_large = size * fraction;
53    }
54    let Some(mut fits) = fits else {
55        return refusal;
56    };
57    for _ in 0..5 {
58        let middle = 0.5 * (fits + too_large);
59        if builds(middle) {
60            fits = middle;
61        } else {
62            too_large = middle;
63        }
64    }
65    KernelRefusal::input(
66        KernelStage::Refine,
67        "blend_size",
68        format!(
69            "{entry}: no rolling ball of radius {size} was found along this edge (a {kind}'s size is its ball's radius); \
70             a size up to about {fits:.3} builds. The solver's own words: {message}",
71            kind = if chamfer { "chamfer" } else { "fillet" },
72            message = refusal.message
73        ),
74    )
75}
76
77
78/// Equal-leg chamfer of one edge (Golovanov §6.11: the same construction
79/// with the arc's chord).
80pub fn chamfer_edge(
81    solid: &BrepSolid,
82    edge_id: u64,
83    distance: f64,
84    name: Option<&str>,
85) -> Result<BrepSolid, KernelRefusal> {
86    // One blend operation: the reports of an earlier one, never consumed, are
87    // dropped as it starts (nested calls keep this operation's).
88    let _operation = crate::blend::BlendOperation::enter();
89    check_mixed_concavity(solid, edge_id, "chamfer_edge")?;
90    check_support_extent(solid, edge_id, distance, "chamfer_edge")?;
91    fillet_or_chamfer(solid, edge_id, distance, true, name, ToolEnds::default(), Lane::GeneralFirst)
92        .map_err(|refusal| size_refusal(solid, edge_id, distance, true, name, "chamfer_edge", refusal))
93}
94
95/// Build and apply the chamfer tool for one straight edge from an already-built
96/// cross-section profile (curve index 1 is the chamfer chord / blend wall).
97/// Shared by the two-distance and distance-angle asymmetric entries.
98fn apply_chamfer_offsets_profile(
99    solid: &BrepSolid,
100    cross: &EdgeCross,
101    profile: &[NurbsCurve],
102    name: Option<&str>,
103    edge_id: u64,
104) -> Result<BrepSolid, KernelRefusal> {
105    // Run through to the faces the edge's ends meet where the rails go on past
106    // them (`BREP_CHAMFER_THROUGH_END_FACES`, default on; `=0` restores); the flush cutter
107    // below answers everything else.
108    if let Some(result) = super::tool::chamfer_through_end_faces(solid, edge_id, cross, profile, name) {
109        return Ok(settle_cutter_scaffold(result));
110    }
111    let mut tool = match &cross.path {
112        EdgePath::Straight { direction, length } => {
113            extrude_profile_brep(profile, *direction, *length)?
114        }
115        // A circular edge between carriers rotationally symmetric about its
116        // axis with straight meridians (`analyze_edge` admits nothing else):
117        // the legs lie on the meridians, so the chordal setbacks are also the
118        // distances along the faces, and the same section revolved about the
119        // axis is the exact tool (`BREP_CHAMFER_ASYM_CURVED`, default on).
120        EdgePath::Circular { .. } if chamfer_asym_curved_on() => {
121            super::tool::build_exact_tool(cross, profile, 0.0, ToolEnds::default(), name)?
122        }
123        EdgePath::Circular { .. } => {
124            return Err(KernelRefusal::unsupported(
125                KernelStage::Classify,
126                "asymmetric_curved_edge",
127                "chamfer_edge_asymmetric: only straight edges on planar faces are supported \
128                 in this slice (asymmetric chamfer on general/curved edges is out of scope)",
129            ));
130        }
131    };
132    // Side faces are emitted in input-curve order; the chamfer wall is the
133    // second profile curve (index 1). Every other face is the cutter's
134    // scaffold, tagged and settled exactly as the symmetric cutter's is.
135    let mut side_index = 0usize;
136    for shell in &mut tool.shells {
137        for face in &mut shell.faces {
138            if side_index == 1 {
139                if face.name.is_none() {
140                    face.name = name.map(str::to_string);
141                }
142            } else {
143                face.name = Some(scaffold_tag(name));
144            }
145            side_index += 1;
146        }
147    }
148    apply_tool(solid, &tool, cross.convex).map(settle_cutter_scaffold)
149}
150
151/// Asymmetric chamfers on curved edges (two-distance and distance-angle):
152/// on by default; `BREP_CHAMFER_ASYM_CURVED=0` restores the refusal
153/// `asymmetric_curved_edge`.
154pub fn chamfer_asym_curved_on() -> bool {
155    switch!("BREP_CHAMFER_ASYM_CURVED", true)
156}
157
158/// Asymmetric (two-distance) chamfer of one STRAIGHT edge between two planar
159/// faces (Golovanov §6.11): setback `d1` along face 1 and `d2` along face 2 —
160/// the standard CAD "d1 × d2" bevel.  General/curved edges are out of scope for
161/// this slice and return a clear error.
162pub fn chamfer_edge_asymmetric(
163    solid: &BrepSolid,
164    edge_id: u64,
165    d1: f64,
166    d2: f64,
167    name: Option<&str>,
168) -> Result<BrepSolid, KernelRefusal> {
169    // One blend operation: the reports of an earlier one, never consumed, are
170    // dropped as it starts (nested calls keep this operation's).
171    let _operation = crate::blend::BlendOperation::enter();
172    if !(d1 > 0.0) || !(d2 > 0.0) || !d1.is_finite() || !d2.is_finite() {
173        return Err(KernelRefusal::input(
174            KernelStage::Collect,
175            "setback_distances",
176            "chamfer_edge_asymmetric: both setback distances must be positive",
177        ));
178    }
179    // `analyze_edge` only uses the radius to size the orientation probe step;
180    // the smaller setback keeps that probe inside both faces.
181    let cross = match analyze_edge(solid, edge_id, d1.min(d2)) {
182        Ok(cross) => cross,
183        Err(refusal) if chamfer_asym_curved_on() => {
184            let faces = setback_faces(solid, edge_id).map_err(|_| refusal)?;
185            let law = crate::blend::setback::SetbackLaw::Distances { faces, distances: [d1, d2] };
186            return chamfer_by_setback_law(solid, edge_id, law, name, "chamfer_edge_asymmetric", false);
187        }
188        Err(refusal) => return Err(refusal),
189    };
190    let profile = chamfer_cross_section_offsets(&cross, d1, d2)?;
191    apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)
192}
193
194/// Conic-section blend of one edge: the rolling ball's two contacts joined by
195/// a conic instead of the ball's arc.
196///
197/// `radius` places the contacts exactly where `fillet_edge` places them, the
198/// distance `radius / tan(θ/2)` from the edge on each face (θ the angle
199/// between the faces; `radius` itself at a right angle). The section is the
200/// rational quadratic through those contacts whose middle pole is the point
201/// where the two faces' section lines meet (a point of the edge), with weights
202/// `1, rho / (1 − rho), 1`. It is tangent to both faces at the contacts. `rho`
203/// in `(0, 1)` is the fraction of the way from the contacts' chord to the edge
204/// that the section's middle reaches: `0.5` is a parabola, below it an ellipse,
205/// above it a hyperbola, and `sin(θ/2) / (1 + sin(θ/2))` (`√2 − 1` at a right
206/// angle) is the ball's own arc.
207///
208/// Built here for a straight edge between two planes, and for a circular edge
209/// between surfaces of revolution about its axis whose meridians are straight
210/// (a plane, a cylinder, a cone); any other edge is refused `conic_edge` by
211/// name. An edge that runs on into its neighbours is cut through to them, as
212/// a chamfer's is.
213pub fn fillet_edge_conic(
214    solid: &BrepSolid,
215    edge_id: u64,
216    radius: f64,
217    rho: f64,
218    name: Option<&str>,
219) -> Result<BrepSolid, KernelRefusal> {
220    let _operation = crate::blend::BlendOperation::enter();
221    if !(radius > 0.0) || !radius.is_finite() {
222        return Err(KernelRefusal::input(
223            KernelStage::Collect,
224            "conic_radius",
225            "fillet_edge_conic: the radius must be positive",
226        ));
227    }
228    if !(rho > 0.0 && rho < 1.0) {
229        return Err(KernelRefusal::input(
230            KernelStage::Collect,
231            "conic_rho",
232            "fillet_edge_conic: rho must lie strictly between 0 and 1",
233        ));
234    }
235    let cross = analyze_edge(solid, edge_id, radius).map_err(|refusal| {
236        KernelRefusal::unsupported(
237            KernelStage::Classify,
238            "conic_edge",
239            format!(
240                "fillet_edge_conic: a conic blend is built only on a straight edge between planes or a \
241                 circular edge between straight-sided surfaces about its axis ({})",
242                refusal.message
243            ),
244        )
245    })?;
246    if matches!(cross.path, EdgePath::Circular { .. }) && !chamfer_asym_curved_on() {
247        return Err(KernelRefusal::unsupported(
248            KernelStage::Classify,
249            "conic_edge",
250            "fillet_edge_conic: circular edges are switched off (BREP_CHAMFER_ASYM_CURVED=0)",
251        ));
252    }
253    let profile = super::tool::conic_cross_section(&cross, radius, rho)?;
254    let result = apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)?;
255    refuse_invalid_result(&result, "fillet_edge_conic")?;
256    Ok(result)
257}
258
259/// `fillet_edge_conic` for edges picked by a point on each. The edges are
260/// blended one after another and independently: where two of them meet, the
261/// vertex stays sharp between the two blends (no corner is built).
262pub fn fillet_edges_conic(
263    solid: &BrepSolid,
264    edge_points: &[Vec3],
265    edge_names: Option<&[String]>,
266    radius: f64,
267    rho: f64,
268    name: Option<&str>,
269) -> Result<BrepSolid, KernelRefusal> {
270    let _operation = crate::blend::BlendOperation::enter();
271    if edge_points.is_empty() {
272        return Err(KernelRefusal::input(
273            KernelStage::Collect,
274            "conic_selection",
275            "fillet_edges_conic: no edges selected",
276        ));
277    }
278    let mut result = solid.clone();
279    for (index, point) in edge_points.iter().enumerate() {
280        let edge_id = resolve_edge_by_point(&result, *point)?;
281        result = fillet_edge_conic(&result, edge_id, radius, rho, per_edge_name(edge_names, name, index))?;
282    }
283    Ok(result)
284}
285
286/// The ids of the edge's two faces in `analyze_edge`'s order (face 1 first):
287/// the faces the setbacks `d1` and `d2` are measured on.
288fn setback_faces(solid: &BrepSolid, edge_id: u64) -> Result<[u64; 2], KernelRefusal> {
289    let (_, faces) = super::analyze::edge_and_faces(solid, edge_id)?;
290    match faces.as_slice() {
291        [first, second] if first.id != second.id => Ok([first.id, second.id]),
292        _ => Err(KernelRefusal::input(
293            KernelStage::Collect,
294            "edge_faces",
295            format!("asymmetric chamfer: edge {edge_id} does not join two faces"),
296        )),
297    }
298}
299
300/// The input positions of the selected points that resolve onto the smooth
301/// chain through `edge_id`, when the chain has two or more edges and the
302/// not-yet-chamfered selection covers every one of them; else `None`.
303fn selected_chain(
304    solid: &BrepSolid,
305    edge_id: u64,
306    edge_points: &[Vec3],
307    done: &[bool],
308) -> Result<Option<Vec<usize>>, KernelRefusal> {
309    let Ok((members, _closed)) = crate::blend::smooth_chain_members(solid, edge_id) else {
310        return Ok(None);
311    };
312    if members.len() < 2 {
313        return Ok(None);
314    }
315    let mut positions = Vec::new();
316    for member in &members {
317        let position = edge_points.iter().enumerate().position(|(index, point)| {
318            !done[index] && resolve_edge_by_point(solid, *point).is_ok_and(|id| id == *member)
319        });
320        match position {
321            Some(position) => positions.push(position),
322            None => return Ok(None),
323        }
324    }
325    Ok(Some(positions))
326}
327
328/// An asymmetric chamfer the exact cutters do not cover (a curved edge on
329/// carriers that are not coaxial straight-meridian revolutions): the closed
330/// rim's march with its stations solved from the setback law
331/// (`blend/setback.rs`): a closed edge as its own rim, an open edge as the
332/// closed smooth chain it lies on or else alone, and with `walk_chain` the
333/// whole smooth chain (open or closed) a selection covers.
334fn chamfer_by_setback_law(
335    solid: &BrepSolid,
336    edge_id: u64,
337    law: crate::blend::setback::SetbackLaw,
338    name: Option<&str>,
339    entry: &str,
340    walk_chain: bool,
341) -> Result<BrepSolid, KernelRefusal> {
342    let edge = solid
343        .edges
344        .iter()
345        .find(|edge| edge.id == edge_id)
346        .ok_or_else(|| KernelRefusal::input(KernelStage::Collect, "edge", format!("{entry}: edge {edge_id} not found")))?;
347    let closed = edge.start_vertex_id == edge.end_vertex_id;
348    // The operand heal the symmetric ladder runs first (ids preserved).
349    let mut healed = solid.clone();
350    let policy = crate::KernelTolerances::for_solid(&healed, 1e-7);
351    crate::heal::heal_operands(&mut healed, &policy)?;
352    let reach = law.reach();
353    let mut result = crate::blend::setback::with_setback_law(law, || {
354        if walk_chain {
355            crate::blend::blend_smooth_chain(&healed, edge_id, reach, true, name)
356        } else if closed {
357            crate::blend::blend_closed_edge(&healed, edge_id, reach, true, name)
358        } else {
359            // An arc of a closed smooth chain (a rim the carriers' seams
360            // split) is chamfered as the whole rim; a lone open edge on its
361            // own.  An open tangent chain is not walked from one of its edges
362            // (`chamfer_edges_asymmetric` takes a whole selected chain).
363            crate::blend::blend_smooth_chain_if_closed(&healed, edge_id, reach, true, name).or_else(|refusal| {
364                let lone = matches!(&refusal.class, RefusalClass::Internal { what } if what == "chain_single_segment");
365                if lone {
366                    crate::blend::blend_open_edge(&healed, edge_id, reach, true, name)
367                } else {
368                    Err(refusal)
369                }
370            })
371        }
372    })?;
373    heal_edge_vertex_gaps(&mut result, reach)?;
374    crate::blend::fit_planar_charts_to_trims(&healed, &mut result)?;
375    let result = settle_cutter_scaffold(result);
376    refuse_invalid_result(&result, entry)?;
377    super::analyze::check_blend_interference(&healed, &result, &[edge_id], "chamfer")?;
378    super::analyze::check_blend_wall_loops(&result, "chamfer")?;
379    Ok(result)
380}
381
382/// Distance-angle chamfer of one STRAIGHT edge between two planar faces
383/// (Golovanov §6.11): setback `d1` along face 1 and angle `angle_rad` between
384/// the chamfer face and face 1.  `d2` is constructed geometrically in the
385/// cross-section plane (see `chamfer_angle_second_distance`), then the
386/// two-distance builder is applied.
387pub fn chamfer_edge_angle(
388    solid: &BrepSolid,
389    edge_id: u64,
390    d1: f64,
391    angle_rad: f64,
392    name: Option<&str>,
393) -> Result<BrepSolid, KernelRefusal> {
394    // One blend operation: the reports of an earlier one, never consumed, are
395    // dropped as it starts (nested calls keep this operation's).
396    let _operation = crate::blend::BlendOperation::enter();
397    if !(d1 > 0.0) || !d1.is_finite() {
398        return Err(KernelRefusal::input(
399            KernelStage::Collect,
400            "setback_d1",
401            "chamfer_edge_angle: setback distance d1 must be positive",
402        ));
403    }
404    let cross = match analyze_edge(solid, edge_id, d1) {
405        Ok(cross) => cross,
406        Err(refusal) if chamfer_asym_curved_on() => {
407            let [first, _] = setback_faces(solid, edge_id).map_err(|_| refusal)?;
408            if !(angle_rad > 1e-9) || !(angle_rad < std::f64::consts::PI) {
409                return Err(KernelRefusal::input(
410                    KernelStage::Collect,
411                    "chamfer_angle",
412                    format!("chamfer_edge_angle: angle {angle_rad} must be positive"),
413                ));
414            }
415            let law = crate::blend::setback::SetbackLaw::Angle { first, distance: d1, angle: angle_rad };
416            return chamfer_by_setback_law(solid, edge_id, law, name, "chamfer_edge_angle", false);
417        }
418        Err(refusal) => return Err(refusal),
419    };
420    let d2 = chamfer_angle_second_distance(&cross, d1, angle_rad)?;
421    let profile = chamfer_cross_section_offsets(&cross, d1, d2)?;
422    apply_chamfer_offsets_profile(solid, &cross, &profile, name, edge_id)
423}
424
425/// Snap small trim/intersection gaps between blend edges and their vertices.
426/// The boolean endpoint welder preserves gaps already inside the validation
427/// band and limits repairs to `max(|radius| * 1e-3, 1e-4)`.
428pub(super) fn heal_edge_vertex_gaps(
429    solid: &mut BrepSolid,
430    radius: f64,
431) -> Result<(), KernelRefusal> {
432    let search = (radius.abs() * 1e-3).max(1e-7);
433    crate::boolean::commit_nearby_edge_endpoints(solid, search)
434}
435
436/// The fillet pipeline's exit acceptance: a solid with a validation ERROR is
437/// refused by name, never returned.
438///
439/// Warnings do not refuse; only the issues `validate()` itself calls errors.
440fn refuse_invalid_result(result: &BrepSolid, entry: &str) -> Result<(), KernelRefusal> {
441    let errors: Vec<_> = result.validate_memoised().into_iter().filter(|issue| issue.severity == "error").collect();
442    let Some(first) = errors.first() else {
443        return Ok(());
444    };
445    Err(KernelRefusal::new(
446        RefusalClass::InvalidResultTopology { issues: errors.len() as u32 },
447        KernelStage::Validate,
448        format!(
449            "{entry}: the blend built a solid that fails validation ({} errors, first: {}); \
450             refused rather than returned",
451            errors.len(),
452            first.message
453        ),
454    ))
455}
456
457/// `BREP_FILLET_PICK_SKIPS_SEAM` (default on; `=0` restores): a pick point that lies as near a
458/// SEAM (an edge one face uses on both sides) as a blendable edge picks the
459/// blendable one.
460///
461/// Cause (brep-bench probe, a ball r 5 bored through by a cylinder r 2, its rim
462/// filleted or chamfered from the point (0, 2, √21), refused "edge 4 borders 1
463/// faces"): the point is the vertex where the rim meets the bore's seam, both
464/// edges read distance 0, and the first found, the seam, was taken. A seam has
465/// one face on both sides and can never be blended, so it loses every tie.
466fn pick_skips_seam_on() -> bool {
467    switch!("BREP_FILLET_PICK_SKIPS_SEAM", true)
468}
469
470/// Whether `edge_id` is a seam: every coedge of it lies on one face.
471fn is_seam(solid: &BrepSolid, edge_id: u64) -> bool {
472    let users = solid
473        .shells
474        .iter()
475        .flat_map(|shell| &shell.faces)
476        .filter(|face| face.loops.iter().flat_map(|loop_record| &loop_record.coedges).any(|coedge| coedge.edge_id == edge_id))
477        .count();
478    users == 1
479}
480
481/// Resolve a point within 1e-3 of a trimmed edge.
482pub fn resolve_edge_by_point(solid: &BrepSolid, point: Vec3) -> Result<u64, KernelRefusal> {
483    let nearest = crate::topology::nearest_edge(solid, point);
484    if pick_skips_seam_on() {
485        if let Some((edge_id, distance)) = nearest {
486            if distance <= 1e-3 && is_seam(solid, edge_id) {
487                let tie = distance + 1e-9 * (1.0 + point.length());
488                let blendable = solid.edges.iter().filter(|edge| edge.id != edge_id && !edge.degenerate).find(|edge| {
489                    crate::project_point_to_curve(&edge.curve, point).ok().is_some_and(|projection| {
490                        let at = projection.u.clamp(edge.t0.min(edge.t1), edge.t0.max(edge.t1));
491                        edge.curve.evaluate(at).is_ok_and(|sample| sample.sub(point).length() <= tie)
492                    }) && !is_seam(solid, edge.id)
493                });
494                if let Some(edge) = blendable {
495                    return Ok(edge.id);
496                }
497            }
498        }
499    }
500    match nearest {
501        Some((edge_id, distance)) if distance <= 1e-3 => Ok(edge_id),
502        Some((_, distance)) => Err(KernelRefusal::input(
503            KernelStage::Collect,
504            "edge_point",
505            format!(
506                "fillet_edges: no edge within tolerance of the point (nearest {distance:.6})"
507            ),
508        )),
509        None => Err(KernelRefusal::input(
510            KernelStage::Collect,
511            "no_edges",
512            "fillet_edges: solid has no edges",
513        )),
514    }
515}
516
517/// Fillet (or chamfer) a GROUP of edges as ONE operation, and — for fillets —
518/// round the convex "star" vertices where three or more of the selected edges
519/// meet (Golovanov §6.9.7).  This is the whole multi-edge fillet in a single
520/// kernel call: the caller passes the object plus one 3D point on each edge,
521/// and the kernel orchestrates the filleting and corner blending against the
522/// full topology (so acute corners resolve coherently instead of being
523/// stitched edge-by-edge by the app).  A corner the kernel cannot round (e.g.
524/// non-orthogonal beyond support, or a general no-common-ball star) is left as
525/// the edge fillets rather than failing the whole group.
526///
527/// When the WHOLE selection cannot be blended as one unit — a shared convex
528/// corner where a revolve axis/pole edge meets the adjacent cap edges can
529/// defeat the sequential corner surgery even though each edge and every proper
530/// SUBSET of the selection blends cleanly (the three fillets converge on the
531/// pole with no single end face across the corner) — a maximal-valid-SUBSET
532/// search blends the largest subset that works, dropping only the edges that
533/// cannot co-blend.  That is a real outcome and [`fillet_edges_reported`]
534/// returns it, WITH the list of edges it could not blend.
535///
536/// This entry point does not.  A solid holding eight of the ten walls that
537/// were asked for is not the answer to the question that was asked, and
538/// returning it as a plain `Ok` reports success for a different result; so an
539/// incomplete selection is an error here, naming every edge that was dropped
540/// and the group refusal behind them.  A caller that genuinely wants the
541/// partial answer asks for it by name.
542///
543/// `edge_names` (when `Some`) is the per-edge blend-FACE name parallel to
544/// `edge_points` — each grown wall is named after ITS originating edge; `None`
545/// names every wall with the single base `name` (the legacy/test behavior,
546/// byte-identical to before). The whole `*_edges` family takes the same
547/// `edge_names` slot in the same position.
548pub fn fillet_edges(
549    solid: &BrepSolid,
550    edge_points: &[Vec3],
551    edge_names: Option<&[String]>,
552    radius: f64,
553    chamfer: bool,
554    name: Option<&str>,
555) -> Result<BrepSolid, KernelRefusal> {
556    // A selected closed rim with a corner at its one vertex, on a mate creased
557    // along its own seam, is blended on the body canonicalised for it — the
558    // mate split along a smooth meridian so the network's miter closes the
559    // crease — and the walls are merged back afterwards
560    // (`blend/creased_rim.rs`). Every other selection takes the body as it
561    // came.
562    let prepared = crate::blend::creased_rim::split_creased_rims(solid, edge_points, edge_names, &resolve_edge_by_point)?;
563    match prepared {
564        Some(prepared) => {
565            let names = prepared.names.as_deref();
566            let built = fillet_edges_prepared(&prepared.solid, &prepared.points, names, radius, chamfer, name)?;
567            Ok(prepared.rejoin(built))
568        }
569        None => {
570            // A chamfer selection holding a MIXED STAR (one concave and two
571            // convex selected edges at a vertex, the convex two on one cap) is
572            // built in two phases (`fillet/chamfer_star.rs`); a phase that
573            // refuses hands the selection to the ordinary path below.
574            if chamfer {
575                let build = |body: &BrepSolid, points: &[Vec3], names: Option<&[String]>| {
576                    fillet_edges_prepared(body, points, names, radius, true, name)
577                };
578                if let Some(built) = super::chamfer_star::chamfer_mixed_stars(solid, edge_points, edge_names, &build) {
579                    return Ok(built);
580                }
581            }
582            let ordinary = fillet_edges_prepared(solid, edge_points, edge_names, radius, chamfer, name);
583            // A closed rim written as a chain of edges along the halves of a
584            // split carrier, refused because only the closed-rim rollover
585            // follows its ball and that lane takes one closed edge, is blended
586            // on the body with those halves merged and the chain joined into one
587            // closed edge (`blend/split_rim.rs`; default on,
588            // `BREP_SPLIT_RIM_MERGE=0` off). Only that refusal asks: a selection
589            // the ordinary path builds keeps its body and names.
590            let answered = match ordinary {
591                Err(refusal)
592                    if crate::blend::split_rim::split_rim_merge_on()
593                        && matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what } if what == super::analyze::TANGENT_ROLLOVER_ONLY_WHAT) =>
594                {
595                    match crate::blend::split_rim::merge_split_rims(solid, edge_points, edge_names, &resolve_edge_by_point) {
596                        // The merged attempt's own reason is appended: the
597                        // first refusal names the lane that is missing, the
598                        // second why the canonical body did not answer either
599                        // (lane F's open item).
600                        Some(merged) => fillet_edges_prepared(&merged.solid, &merged.points, merged.names.as_deref(), radius, chamfer, name)
601                            .map_err(|merged_refusal| {
602                                refusal.with_message(|message| {
603                                    format!("{message} The rim merged into one closed edge refused too: {}", merged_refusal.message)
604                                })
605                            }),
606                        None => Err(refusal),
607                    }
608                }
609                other => other,
610            };
611            // A closed ridge split into two arcs because its walls' seams sit
612            // a hair apart is blended on the body with one wall turned about
613            // the axis onto the other's seam and the arcs joined into one
614            // closed edge (`blend/turned_rim.rs`; default on,
615            // `BREP_FILLET_TURNED_RIM=0` off). Only a refusal asks.
616            let answered = match answered {
617                Err(refusal) if crate::blend::turned_rim::turned_rim_on() => {
618                    match crate::blend::turned_rim::turn_rim_seams_together(solid, edge_points, edge_names, &resolve_edge_by_point) {
619                        Some(turned) => fillet_edges_prepared(&turned.solid, &turned.points, turned.names.as_deref(), radius, chamfer, name)
620                            .map_err(|turned_refusal| {
621                                refusal.with_message(|message| {
622                                    format!("{message} The rim turned into one closed edge refused too: {}", turned_refusal.message)
623                                })
624                            }),
625                        None => Err(refusal),
626                    }
627                }
628                other => other,
629            };
630            // A sheet's edge that runs out at the free boundary has no face
631            // across its end: each such end is closed by a temporary planar
632            // face, the body blended, and the faces removed again
633            // (`blend/sheet_ends.rs`; default on, `BREP_SHEET_FREE_END=0` off).
634            // Only a refused sheet selection asks; the refusal stands unless
635            // the reopened sheet validates.
636            match answered {
637                Err(refusal) if solid.kind == crate::BodyKind::Sheet && crate::blend::sheet_ends::sheet_free_end_on() => {
638                    let edge_ids = edge_points.iter().map(|point| resolve_edge_by_point(solid, *point)).collect::<Result<Vec<_>, _>>();
639                    let Ok(edge_ids) = edge_ids else { return Err(refusal) };
640                    let Some(closed) = crate::blend::sheet_ends::close_free_ends(solid, &edge_ids) else { return Err(refusal) };
641                    let count = crate::blend::sheet_ends::temporary_faces(&closed);
642                    match fillet_edges_prepared(&closed, edge_points, edge_names, radius, chamfer, name) {
643                        Ok(built) => crate::blend::sheet_ends::open_free_ends(built, count).ok_or(refusal),
644                        Err(closed_refusal) => Err(refusal.with_message(|message| {
645                            format!("{message} The sheet with its free ends closed refused too: {}", closed_refusal.message)
646                        })),
647                    }
648                }
649                other => other,
650            }
651        }
652    }
653}
654
655fn fillet_edges_prepared(
656    solid: &BrepSolid,
657    edge_points: &[Vec3],
658    edge_names: Option<&[String]>,
659    radius: f64,
660    chamfer: bool,
661    name: Option<&str>,
662) -> Result<BrepSolid, KernelRefusal> {
663    // One blend operation: the reports of an earlier one, never consumed, are
664    // dropped as it starts (nested calls keep this operation's).
665    let _operation = crate::blend::BlendOperation::enter();
666    // Each operation pays for the first read of every body it validates
667    // (`BrepSolid::validate_memoised`, lane R1 row 3).
668    BrepSolid::clear_validate_memo();
669    // One coedge-check memo per operation, as a boolean opens one (lane R1
670    // row 3b): the surgery's, the group lane's
671    // and the exit's validations re-read the coedges the rims left unchanged.
672    let _coedge_memo = crate::topology::CoedgeMemoScope::open(true);
673    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
674    // The search is capped at one dropped edge here (lane F row 3);
675    // `BREP_SUBSET_SEARCH_FULL=1` restores the full search.
676    let cap = std::env::var_os("BREP_SUBSET_SEARCH_FULL").is_none().then_some(1);
677    let _cap = SubsetDropCap::set(cap);
678    let (result, selection) = match fillet_edges_reported(solid, edge_points, edge_names, radius, chamfer, name) {
679        // A wall that folds is relieved where it folds, not refused
680        // (`blend/relief.rs`).
681        Err(fold) if !chamfer && crate::blend::is_wall_fold(&fold) && crate::blend::relief::radius_relief_on() => {
682            let misfit = crate::blend::relief::is_misfit_fold(&fold);
683            let relieved = relieve_fold(solid, edge_points, edge_names, radius, name, fold);
684            // A misfit (a lane's refusal read as the ball not fitting) took
685            // the group off the ladder that follows the network; when no
686            // relief builds, that ladder answers, as it did before the relief.
687            if relieved.is_err() && misfit {
688                let _off = crate::blend::relief::MisfitOff::enter();
689                return fillet_edges(solid, edge_points, edge_names, radius, chamfer, name);
690            }
691            return relieved;
692        }
693        reported => reported?,
694    };
695    if selection.is_complete() {
696        return Ok(result);
697    }
698    // Every dropped edge BY NAME: the caller's own per-edge name when it gave
699    // one, and always its index and the point it was selected by.
700    let dropped: Vec<String> = selection
701        .rejected
702        .iter()
703        .map(|index| {
704            let point = edge_points[*index];
705            let named = edge_names
706                .and_then(|names| names.get(*index))
707                .map(|name| format!("`{name}` "))
708                .unwrap_or_default();
709            format!(
710                "{named}#{index} at ({:.6}, {:.6}, {:.6})",
711                point.x, point.y, point.z
712            )
713        })
714        .collect();
715    // The selection, as specified, has no single answer the kernel will
716    // stand behind: the group refusal behind the drop travels as TEXT in
717    // `BlendSelection::reason`, so this refusal carries its own class.
718    Err(KernelRefusal::ill_posed(
719        KernelStage::Select,
720        "incomplete_selection",
721        format!(
722            "{entry}: {} of the {} selected edges were blended — {} could not co-blend with the \
723             rest of the selection and carry no wall in the result ({}). The group refusal was: \
724             {}. Blend them separately, or call the reported entry point to accept the partial \
725             selection deliberately.",
726            selection.applied.len(),
727            selection.requested,
728            selection.rejected.len(),
729            dropped.join(", "),
730            selection
731                .reason
732                .as_deref()
733                .unwrap_or("the whole group built but not every edge grew a wall"),
734        ),
735    ))
736}
737
738/// The fillet a constant `radius` would fold: rebuilt with the radius reduced
739/// only where it does not fit (`blend/relief.rs`), and a note saying where
740/// and to what. Selected edges joined (through shared vertices) to no relief
741/// zone are built at the constant radius first; each relieved group is then
742/// built by the taper network on that body. A relief that still folds is
743/// planned again with a wider margin; when none builds, the fold stands with
744/// the last relief's reason appended.
745fn relieve_fold(
746    solid: &BrepSolid,
747    edge_points: &[Vec3],
748    edge_names: Option<&[String]>,
749    radius: f64,
750    name: Option<&str>,
751    fold: KernelRefusal,
752) -> Result<BrepSolid, KernelRefusal> {
753    let _relieving = crate::blend::relief::Relieving::enter();
754    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
755    let selected: Vec<u64> = edge_points.iter().map(|point| resolve_edge_by_point(solid, *point)).collect::<Result<_, _>>()?;
756    // One edge per carrier continued (`relief::join_continuations`): the
757    // selection is read again on the joined body, two points on one joined
758    // edge selecting it once.
759    let joined = crate::blend::relief::join_continuations(solid, &selected);
760    let solid = joined.as_ref().unwrap_or(solid);
761    let mut ids: Vec<u64> = Vec::with_capacity(edge_points.len());
762    let mut points: Vec<Vec3> = Vec::with_capacity(edge_points.len());
763    let mut names: Vec<String> = Vec::with_capacity(edge_points.len());
764    for (index, point) in edge_points.iter().enumerate() {
765        let id = resolve_edge_by_point(solid, *point)?;
766        if !ids.contains(&id) {
767            ids.push(id);
768            points.push(*point);
769            if let Some(name) = edge_names.and_then(|names| names.get(index)) {
770                names.push(name.clone());
771            }
772        }
773    }
774    let (edge_points, edge_names) = (&points[..], edge_names.map(|_| &names[..]));
775    if debug && joined.is_some() {
776        eprintln!("radius relief: joined continuation edges, {} selected edges become {}", selected.len(), ids.len());
777    }
778    let started = web_time::Instant::now();
779    let measured = match crate::blend::relief::measure_ceilings(solid, &ids, radius) {
780        Ok(measured) => measured,
781        Err(refusal) => return Err(fold.with_message(|message| format!("{message}; the relief could not measure the edges: {refusal}"))),
782    };
783    if debug {
784        eprintln!("radius relief: ceilings measured in {:.1} ms", started.elapsed().as_secs_f64() * 1e3);
785    }
786    // A relief is LOCAL: the requested radius stands where it fits. Where it
787    // fits nowhere on the selection (a ball wider than a rod's rim, the whole
788    // rim short alike) a radius lowered everywhere is a different request,
789    // and the fold stands, naming the largest ball that does fit.
790    let largest = measured.iter().flatten().map(|(_, ceiling)| *ceiling).fold(0.0_f64, f64::max);
791    if largest < radius {
792        return Err(fold.with_message(|message| {
793            format!("{message}; r {radius} fits nowhere along the selection, so it is not reduced locally: the largest ball that fits anywhere on it is {largest:.6}")
794        }));
795    }
796    let mut last: Option<KernelRefusal> = None;
797    for attempt in 0..crate::blend::relief::ATTEMPTS {
798        let plan = match crate::blend::relief::plan_relief(solid, &ids, radius, &measured, attempt) {
799            Ok(Some(plan)) => plan,
800            // The ball fits everywhere the probe reads: the fold is not one
801            // a smaller radius answers.
802            Ok(None) => break,
803            Err(refusal) => {
804                last = Some(refusal);
805                break;
806            }
807        };
808        let mark = crate::blend::blend_notes_mark();
809        match build_relief_plan(solid, edge_points, edge_names, &ids, radius, name, &plan) {
810            Ok(body) => {
811                for zone in &plan.zones {
812                    let near: Vec<String> = zone
813                        .edges
814                        .iter()
815                        .filter_map(|index| solid.edges.iter().find(|edge| edge.id == ids[*index]))
816                        .map(|edge| edge.name.clone().unwrap_or_else(|| format!("edge #{}", edge.id)))
817                        .map(|label| format!("`{label}`"))
818                        .collect();
819                    // The note states what was built: where the law never
820                    // climbs back to the requested radius on the zone's edges
821                    // (report 5e49bb42's rim, 1.08 to 1.78 against r 2.2), it
822                    // says so instead of "locally".
823                    let (low, high) = zone
824                        .edges
825                        .iter()
826                        .flat_map(|index| plan.stops[*index].iter().map(|(_, r)| *r))
827                        .fold((f64::INFINITY, 0.0_f64), |(low, high), r| (low.min(r), high.max(r)));
828                    let note = if high < radius * (1.0 - 1e-9) {
829                        format!(
830                            "radius reduced over the whole of {}: {low:.2} to {high:.2}, so r {radius} is reached nowhere \
831                             on them (where they turn tightest the largest ball that fits is {:.2})",
832                            near.join(", "),
833                            zone.ceiling,
834                        )
835                    } else {
836                        format!(
837                            "radius reduced to {:.2} locally near {}: r {radius} does not fit there (the largest ball that does is {:.2})",
838                            zone.radius,
839                            near.join(", "),
840                            zone.ceiling,
841                        )
842                    };
843                    crate::blend::record_blend_note(note);
844                }
845                return Ok(body);
846            }
847            Err(refusal) => {
848                crate::blend::blend_notes_truncate(mark);
849                if debug {
850                    eprintln!("radius relief attempt {attempt} refused at {:.1} ms: {refusal}", started.elapsed().as_secs_f64() * 1e3);
851                }
852                last = Some(refusal);
853            }
854        }
855    }
856    Err(match last {
857        Some(last) => fold.with_message(|message| format!("{message}; a locally reduced radius did not build either: {last}")),
858        None => fold,
859    })
860}
861
862/// Build one relief plan (see [`relieve_fold`]).
863fn build_relief_plan(
864    solid: &BrepSolid,
865    edge_points: &[Vec3],
866    edge_names: Option<&[String]>,
867    ids: &[u64],
868    radius: f64,
869    name: Option<&str>,
870    plan: &crate::blend::relief::ReliefPlan,
871) -> Result<BrepSolid, KernelRefusal> {
872    // Groups of selected edges joined through shared vertices.
873    let count = ids.len();
874    let mut group: Vec<usize> = (0..count).collect();
875    let find = |group: &mut Vec<usize>, mut index: usize| {
876        while group[index] != index {
877            group[index] = group[group[index]];
878            index = group[index];
879        }
880        index
881    };
882    let vertices: Vec<[u64; 2]> = ids
883        .iter()
884        .map(|id| {
885            solid.edges.iter().find(|edge| edge.id == *id).map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).unwrap_or([u64::MAX; 2])
886        })
887        .collect();
888    for a in 0..count {
889        for b in a + 1..count {
890            if vertices[a].iter().any(|vertex| *vertex != u64::MAX && vertices[b].contains(vertex)) {
891                let (root_a, root_b) = (find(&mut group, a), find(&mut group, b));
892                group[root_a] = root_b;
893            }
894        }
895    }
896    let reduced: Vec<bool> = plan.stops.iter().map(|stops| stops.iter().any(|(_, r)| *r < radius)).collect();
897    let relieved_group: Vec<bool> = (0..count)
898        .map(|index| {
899            let root = find(&mut group, index);
900            (0..count).any(|other| reduced[other] && find(&mut group, other) == root)
901        })
902        .collect();
903    let pick = |want: bool| -> (Vec<Vec3>, Option<Vec<String>>, Vec<Vec<(f64, f64)>>) {
904        let indices: Vec<usize> = (0..count).filter(|index| relieved_group[*index] == want).collect();
905        (
906            indices.iter().map(|index| edge_points[*index]).collect(),
907            edge_names.map(|names| indices.iter().filter_map(|index| names.get(*index).cloned()).collect()),
908            indices.iter().map(|index| plan.stops[*index].clone()).collect(),
909        )
910    };
911    let (constant_points, constant_names, _) = pick(false);
912    let (relieved_points, relieved_names, relieved_stops) = pick(true);
913    let mut body = solid.clone();
914    if !constant_points.is_empty() {
915        body = fillet_edges(&body, &constant_points, constant_names.as_deref(), radius, false, name)?;
916    }
917    let built = fillet_edges_variable_impl(
918        &body,
919        &relieved_points,
920        relieved_names.as_deref(),
921        &relieved_stops,
922        false,
923        name,
924        "fillet_edges",
925        false,
926    )?;
927    let issues = built.validate();
928    if !issues.is_empty() {
929        return Err(KernelRefusal::internal(
930            KernelStage::Validate,
931            "relief_validate",
932            format!("radius relief: the relieved fillet does not validate: {issues:?}"),
933        ));
934    }
935    Ok(built)
936}
937
938/// What a blend selection actually achieved.
939///
940/// The kernel can answer a group blend with fewer walls than were asked for —
941/// the maximal-valid-subset search drops the edges that cannot co-blend at a
942/// shared corner rather than failing outright. This says WHICH, so partial
943/// fulfilment is a statement instead of a silence.
944#[derive(Clone, Debug)]
945pub struct BlendSelection {
946    /// How many edges the caller selected.
947    pub requested: usize,
948    /// Indices into that selection that carry a blend wall in the result.
949    pub applied: Vec<usize>,
950    /// Indices that do not.
951    pub rejected: Vec<usize>,
952    /// Why the whole selection could not be built, when something was dropped.
953    pub reason: Option<String>,
954}
955
956impl BlendSelection {
957    /// Every requested edge carries a wall.
958    pub fn is_complete(&self) -> bool {
959        self.rejected.is_empty()
960    }
961}
962
963/// [`fillet_edges`] with the selection outcome reported rather than refused.
964///
965/// The result is the same solid `fillet_edges` would build; the difference is
966/// that an incomplete selection comes back as `Ok` with the misses named,
967/// which is the explicit partial-result contract. Every named refusal that
968/// applies to the WHOLE selection — mixed concavity, a radius the local wall
969/// cannot hold, a mixed-convexity corner — is still an `Err`: dropping edges
970/// cannot rescue those, so a partial answer would be a different defect.
971/// [`fillet_edges_reported`] with the solid and the edge points translated by
972/// `offset` for the operation and the result translated back. Refusal
973/// messages name the translated coordinates.
974pub fn fillet_edges_reported_at_offset(
975    solid: &BrepSolid,
976    edge_points: &[Vec3],
977    edge_names: Option<&[String]>,
978    radius: f64,
979    chamfer: bool,
980    name: Option<&str>,
981    offset: Vec3,
982) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
983    fillet_translated(solid, edge_points, edge_names, radius, chamfer, name, offset, crate::recentre::EntryKind::Control)
984}
985
986/// The translated run behind the control and the guard.
987#[allow(clippy::too_many_arguments)]
988fn fillet_translated(
989    solid: &BrepSolid,
990    edge_points: &[Vec3],
991    edge_names: Option<&[String]>,
992    radius: f64,
993    chamfer: bool,
994    name: Option<&str>,
995    offset: Vec3,
996    kind: crate::recentre::EntryKind,
997) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
998    let _entry = crate::recentre::TranslatedEntry::open(kind);
999    let translate = |solid: &BrepSolid, offset: Vec3| {
1000        crate::recentre::translate_solid(solid, offset).map_err(|message| {
1001            KernelRefusal::internal(
1002                KernelStage::Collect,
1003                "translation_control",
1004                format!("fillet_edges: the translation control could not move the solid: {message}"),
1005            )
1006        })
1007    };
1008    let moved = translate(solid, offset)?;
1009    let points: Vec<Vec3> = edge_points.iter().map(|point| point.add(offset)).collect();
1010    let (result, selection) = fillet_edges_reported(&moved, &points, edge_names, radius, chamfer, name)?;
1011    Ok((translate(&result, offset.scale(-1.0))?, selection))
1012}
1013
1014pub fn fillet_edges_reported(
1015    solid: &BrepSolid,
1016    edge_points: &[Vec3],
1017    edge_names: Option<&[String]>,
1018    radius: f64,
1019    chamfer: bool,
1020    name: Option<&str>,
1021) -> Result<(BrepSolid, BlendSelection), KernelRefusal> {
1022    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`):
1023    // the outermost entry runs the fillet on a translated solid.
1024    if let Some(offset) = crate::recentre::control_offset_at_entry() {
1025        return fillet_edges_reported_at_offset(solid, edge_points, edge_names, radius, chamfer, name, offset);
1026    }
1027    // The recentre guard: a solid far from the origin in its own units
1028    // is filleted at the origin.
1029    let bounds = crate::recentre::solid_bounds(solid);
1030    if let Some(offset) = crate::recentre::guard_offset(bounds) {
1031        crate::recentre::profile_fired("fillet", offset, bounds);
1032        return fillet_translated(solid, edge_points, edge_names, radius, chamfer, name, offset, crate::recentre::EntryKind::Guard);
1033    }
1034    // One blend operation: the reports of an earlier one, never consumed, are
1035    // dropped as it starts (nested calls keep this operation's).
1036    let _operation = crate::blend::BlendOperation::enter();
1037    // Dropped before `_operation`, so the total is on the ledger when the
1038    // outermost operation prints it.
1039    let _total = crate::blend::BlendTimer::start("timing.total_ms");
1040    if !(radius > 0.0) || !radius.is_finite() {
1041        return Err(KernelRefusal::input(
1042            KernelStage::Collect,
1043            "radius",
1044            "fillet_edges: radius must be positive",
1045        ));
1046    }
1047    if edge_points.is_empty() {
1048        return Err(KernelRefusal::input(
1049            KernelStage::Collect,
1050            "selection",
1051            "fillet_edges: no edges selected",
1052        ));
1053    }
1054    // The rolling ball must reach both supports of every SELECTED edge — see
1055    // `check_support_extent`.  Checked ONCE, here, against the solid the
1056    // selection was made on: inside the group build the faces have already
1057    // been eaten into by earlier blends of the same selection, and a fillet
1058    // legitimately runs off that remainder (two rounds pinching on a shared
1059    // face).  Dropping edges cannot rescue an oversized radius either, so
1060    // this runs before the subset search rather than inside it.
1061    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
1062    let mut selected_ids = Vec::with_capacity(edge_points.len());
1063    if crate::blend::blend_operation_outermost() {
1064        super::analyze::clear_rollover_only();
1065    }
1066    let selection_checks = crate::blend::BlendTimer::start("timing.selection_checks_ms");
1067    let _boundaries = super::analyze::SupportBoundaryScope::open();
1068    for point in edge_points {
1069        let resolve = crate::blend::BlendTimer::start("timing.selection_checks.resolve_ms");
1070        let edge_id = resolve_edge_by_point(solid, *point)?;
1071        resolve.stop();
1072        let concavity = crate::blend::BlendTimer::start("timing.selection_checks.concavity_ms");
1073        check_mixed_concavity(solid, edge_id, entry)?;
1074        concavity.stop();
1075        let _extent = crate::blend::BlendTimer::start("timing.selection_checks.extent_ms");
1076        // A lone fillet edge may take the clipped concave fill (lane F row 5).
1077        if edge_points.len() == 1 && !chamfer {
1078            check_support_extent_clipping(solid, edge_id, radius, entry)?;
1079        } else {
1080            check_support_extent(solid, edge_id, radius, entry)?;
1081        }
1082        selected_ids.push(edge_id);
1083    }
1084    drop(_boundaries);
1085    selection_checks.stop();
1086    // A corner where the selection mixes convexity — a convex edge dying into
1087    // the concave edges it meets — has no rolling-ball closure at all: the
1088    // blends run out against each other partway along, which is the vertex
1089    // blend the stripe network does not construct yet.  It is TERMINAL, and
1090    // for the same reason as the two checks above it runs once, here: neither
1091    // the cutter composition nor the subset search below can rescue it.  The
1092    // cutter "succeeds" on this shape by shredding the solid (a sliver end cap
1093    // per corner, the carrier face split and renamed), which is worse than
1094    // the named refusal — see the 2026-09-09 rib-spine report.
1095    //
1096    // Nor can PARTITIONING the selection at the corner rescue it, which is why
1097    // this is still a refusal and not a split (measured 2026-09-13, the
1098    // partition record): the two convexity-pure halves each build on the
1099    // network, and composing them walls every selected edge and leaves every
1100    // other face's area identical to twelve digits — but the convex wall comes
1101    // out as the full untrimmed quarter-round prism (2·(1 − π/4)·r²·L to
1102    // 2.2e-10, with NO rolled-corner term) because its contact rail runs off
1103    // its own face at the TRI-TANGENT STATION and the surgery splices the
1104    // overhang in rather than clipping it. The faces it runs along come back
1105    // with self-crossing loops that `validate()`, `solid_self_intersections`,
1106    // the connectivity report and the Euler check all pass — and that
1107    // `check_loop_self_crossings` REFUSES since 9e50f6d55, so the split is not
1108    // a route to ten walls either: blend the concave half first and the
1109    // acceptance refuses every convex edge whose wall runs out into it — on
1110    // the rib both spines, at that same station, so that feature fails
1111    // outright; blend the convex half first and the maximal-valid-subset
1112    // search drops one ring edge and returns NINE walls of ten. The
1113    // construction that is missing is the runout itself: past that station the
1114    // ball rolls on one input face and on the concave stripe's own surface, so
1115    // the march needs a STRIPE as its second carrier.
1116    //
1117    // And more than that, measured 2026-09-13 (`blend/runout.rs`, which this
1118    // refusal now reports): the KEPT mate runs out too, at the mirror-image
1119    // station, so the FIRST carrier becomes the other concave stripe and the
1120    // last stretch rolls on two stripes; that stretch ends in a POLE where the
1121    // two stripes' rails on the face they share meet and the section shrinks
1122    // to a point. Two carrier switches and a degenerate terminus, not a march
1123    // with a stop.
1124    // A convex spine dying into two concave edges on a CURVED floor is built
1125    // spine first, then the rest with the spine's foot on the floor added to
1126    // the concave chain (`spine_first.rs`); taken by the selection's shape
1127    // alone, and declined to the lanes below when a stage does not build.
1128    // Only where the corner analysis below sees no mixed corner (a closed
1129    // edge in the selection, such as the cylinder's rim, blinds it): where it
1130    // sees them, the rounded-boss and runout compositions already build the
1131    // class (the 2026-10-12 sprocket's spine over its cylindrical rim).
1132    if !chamfer && crate::blend::mixed_convexity_corners(solid, &selected_ids, radius).is_empty() {
1133        if let Some(built) = super::spine_first::spine_first_composition(
1134            solid, &selected_ids, edge_points, edge_names, radius, name,
1135        ) {
1136            return Ok(built);
1137        }
1138    }
1139    if !chamfer {
1140        // The class is BUILT where the runout composition applies — the ring
1141        // first, then one wall per spine from pole to pole (`blend/runout.rs`,
1142        // the 2026-09-30 record §5) — and refused by name, with the
1143        // composition's own reason appended, where it does not.
1144        let corner_analysis = crate::blend::BlendTimer::start("timing.corner_analysis_ms");
1145        let mut corners = crate::blend::mixed_convexity_corners(solid, &selected_ids, radius);
1146        corners.extend(crate::blend::runout::one_ended_runout_corners(solid, &selected_ids, radius));
1147        corner_analysis.stop();
1148        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1149            for corner in &corners {
1150                eprintln!(
1151                    "mixed corner at vertex {} ({:.4}, {:.4}, {:.4}): convex {:?} concave {:?}",
1152                    corner.vertex, corner.point.x, corner.point.y, corner.point.z,
1153                    corner.convex.iter().map(|index| selected_ids[*index]).collect::<Vec<_>>(),
1154                    corner.concave.iter().map(|index| selected_ids[*index]).collect::<Vec<_>>()
1155                );
1156            }
1157        }
1158        if !corners.is_empty() {
1159            // BREP lane L: begin walls_missing_tie_all_stations_20261015
1160            // Cleared on entry: only THIS composition's runout may set it.
1161            RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(false));
1162            // BREP lane L: end walls_missing_tie_all_stations_20261015
1163            let composed = rounded_boss_composition(
1164                solid, &selected_ids, edge_points, edge_names, radius, name, &corners,
1165            ).or_else(|error| {
1166                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1167                    eprintln!("rounded boss composition refused: {error}");
1168                }
1169                runout_composition(
1170                    solid, &selected_ids, edge_points, edge_names, radius, name, &corners, entry,
1171                )
1172            }).or_else(|error| {
1173                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1174                    eprintln!("runout composition refused: {error}");
1175                }
1176                // The open-pad composition (2026-10-17 face-ring report): one
1177                // convex and one concave edge at each mixed corner over a
1178                // planar face, the concave pads continued onto the convex
1179                // walls. Declines by name on any other corner shape, so the
1180                // runout's refusal stands where it stood.
1181                open_pad_composition(
1182                    solid, &selected_ids, edge_points, edge_names, radius, name, &corners, entry,
1183                ).map_err(|pad_error| {
1184                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1185                        eprintln!("open-pad composition refused: {pad_error}");
1186                    }
1187                    // The decline is carried in the refusal's CLASS (`what`),
1188                    // never in its text: 2026-10-18 the text test let the
1189                    // decline replace the runout's named refusal on the
1190                    // nine-pick wedge (three lib tests).
1191                    let declined = matches!(&pad_error.class, crate::RefusalClass::UnsupportedGeometry { what } if what == "open_pad_shape");
1192                    if declined { error } else { pad_error }
1193                })
1194            }).or_else(|error| {
1195                // The cusp composition (reports 80c5d9d1 and 6dfd5a22): every
1196                // mixed corner a CUSP, the convex and concave edges leaving it
1197                // tangent. Declines by class on any other corner, and every
1198                // other refusal keeps the one before it: it is the last try.
1199                cusp_composition(solid, &selected_ids, edge_points, edge_names, radius, name, &corners).map_err(|cusp_error| {
1200                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1201                        eprintln!("cusp composition refused: {cusp_error}");
1202                    }
1203                    error
1204                })
1205            });
1206            match composed {
1207                Ok(result) => {
1208                    // BREP lane L: begin walls_missing_tie_all_stations_20261015
1209                    // The runout composition's walls are built and checked by
1210                    // construction; a station its OWN neighbouring wall consumes
1211                    // (a runout trimmed at an edge's end) is not a missing wall.
1212                    // Only on the NETWORK's ring: there every concave edge has its
1213                    // own wall by construction and a runout trims at most its
1214                    // ends; a ring the cutter fallback built keeps the strict
1215                    // first-station rule (the rounded boss path too).
1216                    let network_ring = RUNOUT_RING_IS_NETWORK.with(|flag| flag.replace(false));
1217                    // Integrator merge 2026-10-16 (lanes F + L): the flag above is consumed
1218                    // BEFORE lane F's exit acceptance can return early, so a refused result
1219                    // never leaves it set for the next call on this thread.
1220                    refuse_invalid_result(&result, entry)?;
1221                    let missing = walls_missing_ties(
1222                        solid, &result, edge_points, &(0..edge_points.len()).collect::<Vec<_>>(), radius, chamfer, entry, network_ring,
1223                    )?;
1224                    // BREP lane L: end walls_missing_tie_all_stations_20261015
1225                    if !missing.is_empty() {
1226                        return Err(KernelRefusal::internal(
1227                            KernelStage::Validate,
1228                            "runout_walls_missing",
1229                            format!(
1230                                "{entry}: the composition built a solid with no wall on {}",
1231                                missing.iter().map(|index| selection_label(*index, edge_points, edge_names, name)).collect::<Vec<_>>().join(", ")
1232                            ),
1233                        ));
1234                    }
1235                    let n = edge_points.len();
1236                    return Ok((
1237                        result,
1238                        BlendSelection { requested: n, applied: (0..n).collect(), rejected: Vec::new(), reason: None },
1239                    ));
1240                }
1241                Err(error) => {
1242                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1243                        eprintln!("runout composition refused: {error}");
1244                    }
1245                    check_mixed_corner_convexity(
1246                        solid, &selected_ids, edge_points, edge_names, radius, name, Some(&error),
1247                    )?;
1248                }
1249            }
1250        }
1251        // A selection whose corner setbacks consume a whole edge — the exact
1252        // degenerate radius, every face shrunk to a point — has no strip for
1253        // the network to build and nothing the cutter or the subset search
1254        // can rescue (the search answered the r = 10 cube with nine walls and
1255        // a 5174 volume against the sphere's 4189).  Terminal, by name, here.
1256        let corner_analysis = crate::blend::BlendTimer::start("timing.corner_analysis_ms");
1257        check_degenerate_corner_setbacks(
1258            solid,
1259            &selected_ids,
1260            edge_points,
1261            edge_names,
1262            radius,
1263            name,
1264        )?;
1265        corner_analysis.stop();
1266    }
1267
1268    let n = edge_points.len();
1269    let complete = |applied: Vec<usize>| BlendSelection {
1270        requested: n,
1271        applied,
1272        rejected: Vec::new(),
1273        reason: None,
1274    };
1275    // Every subset below is built against the SAME solid, and a selection of
1276    // several components is composed one component at a time in input order,
1277    // so two subsets that keep the same leading components rebuild the same
1278    // intermediate solids. The memo keeps each component's result under the
1279    // chain of components composed before it, which is everything that result
1280    // depends on here (the solid, radius, chamfer and name are fixed for the
1281    // call), so the search returns what it did without the memo, only without
1282    // the rebuilding. On the 2026-09-26 cross-drilled sphere report four bored
1283    // rims were re-blended ahead of the same failing component in each of the
1284    // (up to 372) subsets tried: 13 min 25 s for one refusal, 34 s with it.
1285    let mut memo = ComponentMemo::default();
1286    let profile = crate::profile::profile_enabled();
1287    let group_started = web_time::Instant::now();
1288    let group = fillet_edges_group_in(
1289        solid,
1290        edge_points,
1291        edge_names,
1292        radius,
1293        chamfer,
1294        name,
1295        Some(&mut memo),
1296    );
1297    if profile {
1298        profile_line!(
1299            "blend.selection group edges={n} ok={} ms={:.3}",
1300            group.is_ok(),
1301            group_started.elapsed().as_secs_f64() * 1e3
1302        );
1303    }
1304    let group_err = match group {
1305        // A group solid that fails `validate()` is never returned: it becomes
1306        // the group's refusal, so the subset search below (which validates
1307        // every subset it builds) still gets its turn, and a selection with
1308        // nothing to drop refuses by that name.
1309        Ok(result) if refuse_invalid_result(&result, entry).is_err() => {
1310            refuse_invalid_result(&result, entry).unwrap_err()
1311        }
1312        Ok(result) => {
1313            // The group returned a solid, which is NOT the same as the group
1314            // having blended every edge.  `validate()` cannot tell the
1315            // difference — it checks incidence, and a solid missing a wall is
1316            // perfectly incident — so the walls are COUNTED.
1317            let missing =
1318                walls_missing(solid, &result, edge_points, &(0..n).collect::<Vec<_>>(), radius, chamfer, entry)?;
1319            if missing.is_empty() {
1320                return Ok((result, complete((0..n).collect())));
1321            }
1322            let applied: Vec<usize> = (0..n).filter(|index| !missing.contains(index)).collect();
1323            return Ok((
1324                result,
1325                BlendSelection {
1326                    requested: n,
1327                    applied,
1328                    rejected: missing,
1329                    reason: None,
1330                },
1331            ));
1332        }
1333        Err(error) => error,
1334    };
1335    // A wall that FOLDS THROUGH ITSELF is terminal for the whole selection, and
1336    // for the reason the two checks above are: dropping edges cannot rescue it.
1337    // The subset search would happily answer this document's two collars with
1338    // the ONE that does not fold, and return a solid whose volume is a blend
1339    // short — the same silent partial `both_collars_add_independently` exists
1340    // to catch.  Reported by name instead (`blend/fold.rs`).
1341    // A miter past the sharp edge's far vertex needs support-face switching,
1342    // not a smaller selection. Do not let the subset search mask the limit.
1343    // Nor can dropping another edge close a tangential end whose taper failed.
1344    if crate::blend::is_wall_fold(&group_err) || crate::blend::is_miter_support_overrun(&group_err)
1345        || crate::blend::is_tangential_transverse_end(&group_err)
1346        || matches!(&group_err.class, RefusalClass::UnsupportedGeometry { what } if what == "canal_footprint_bound")
1347        || crate::blend::is_ball_does_not_fit(&group_err)
1348    {
1349        return Err(group_err);
1350    }
1351    // Fewer than two edges: nothing to drop, so the group error is final.
1352    // Cap the combinatorial search so a large malformed selection cannot
1353    // explode (the full group carries the common case; the search is a
1354    // rare fallback).
1355    if n < 2 || n > 12 {
1356        return Err(group_err);
1357    }
1358    // Drop the fewest edges first (largest surviving subset), trying the
1359    // drop-sets in lexicographic order so the result is deterministic.
1360    // Take the first subset that blends to a valid solid IN WHICH EVERY KEPT
1361    // EDGE GREW A WALL: a subset that itself silently drops one of its own
1362    // edges is not the maximal subset, it is a smaller one wearing a larger
1363    // one's label.
1364    let max_drop = SUBSET_DROP_CAP.with(|cap| cap.get()).map_or(n - 1, |cap| cap.min(n - 1));
1365    for drop in 1..=max_drop {
1366        for dropped in index_combinations(n, drop) {
1367            let keep: Vec<usize> = (0..n).filter(|i| !dropped.contains(i)).collect();
1368            let points: Vec<Vec3> = keep.iter().map(|i| edge_points[*i]).collect();
1369            // Subset the per-edge blend-face names with the IDENTICAL
1370            // drop-set so `kept_names[k]` still names `kept[k]`.
1371            let kept_names: Option<Vec<String>> =
1372                edge_names.map(|names| keep.iter().map(|i| names[*i].clone()).collect());
1373            crate::blend::record_count("count.subset.builds", 1);
1374            let subset_started = web_time::Instant::now();
1375            let subset = fillet_edges_group_in(
1376                solid,
1377                &points,
1378                kept_names.as_deref(),
1379                radius,
1380                chamfer,
1381                name,
1382                Some(&mut memo),
1383            );
1384            if profile {
1385                profile_line!(
1386                    "blend.selection subset dropped={dropped:?} ok={} ms={:.3}",
1387                    subset.is_ok(),
1388                    subset_started.elapsed().as_secs_f64() * 1e3
1389                );
1390            }
1391            let result = match subset {
1392                Ok(result) => result,
1393                Err(error) => {
1394                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
1395                        eprintln!("subset dropped={dropped:?} refused: {error}");
1396                    }
1397                    continue;
1398                }
1399            };
1400            if !result.validate().is_empty() {
1401                continue;
1402            }
1403            if !walls_missing(solid, &result, edge_points, &keep, radius, chamfer, entry)?.is_empty() {
1404                continue;
1405            }
1406            return Ok((
1407                result,
1408                BlendSelection {
1409                    requested: n,
1410                    applied: keep,
1411                    rejected: dropped,
1412                    reason: Some(group_err.message),
1413                },
1414            ));
1415        }
1416    }
1417    Err(group_err)
1418}
1419
1420
1421/// Which of `selected` (indices into the caller's own selection) carry NO blend
1422/// wall in `result` — decided by the MATERIAL, not by a name.
1423///
1424/// A blended edge is an edge whose material changed: a convex blend removes
1425/// the sliver under the edge, so a point of the original edge ends up OUTSIDE
1426/// the answer; a concave one pads the crease, so it ends up INSIDE. An edge
1427/// the selection dropped is still the sharp edge it was, and its points still
1428/// lie ON the skin. That statement holds for every caller and every lane,
1429/// which the previous attribution did not: it looked for one face per edge
1430/// carrying the caller's per-edge name, so a caller passing `None` (the wasm
1431/// ABI, `fillet_edges_json`) got NO count at all, and a caller passing names
1432/// was told a wall was missing where the network had merged two coaxial walls
1433/// into one face (the U-channel at half its width keeps one name for two
1434/// edges) or collapsed the walls of a full-width star into its corner patch
1435/// (`{base}:CORNER:…`, and no wall name at all). Both were measured
1436/// 2026-09-26; the named path REFUSED those complete blends.
1437///
1438/// The classifier answers `On` inside a band, so the check states how far
1439/// the blend of THIS size moves the edge at each probed station — `r·(1/cos(α/2)
1440/// − 1)` for a fillet and `d·sin(α/2)` for a chamfer, `α` the angle between the
1441/// two faces' outward normals there — and probes the station the blend moves
1442/// MOST. An edge that is tangent at one end (the miter seam two rounds leave
1443/// runs to 180° at its pole) is still attributed where it is sharp. Only when
1444/// no station clears the band is the selection refused by name, rather than
1445/// an unseeable move read as a missing wall.
1446pub fn walls_missing(
1447    original: &BrepSolid,
1448    result: &BrepSolid,
1449    edge_points: &[Vec3],
1450    selected: &[usize],
1451    size: f64,
1452    chamfer: bool,
1453    entry: &str,
1454) -> Result<Vec<usize>, KernelRefusal> {
1455    walls_missing_ties(original, result, edge_points, selected, size, chamfer, entry, false)
1456}
1457
1458// BREP lane L: begin walls_missing_tie_all_stations_20261015
1459/// [`walls_missing`], with `tie_majority`: on a clearance TIE (a uniform
1460/// dihedral, every station moving the same) the first station stands for
1461/// all of them unless this is set, when a wall is missing only if MORE THAN
1462/// HALF of the tied stations still lie on the skin (an unwalled edge whose
1463/// two ends neighbouring walls consume — the wedge nine-pick's unselected
1464/// side A ∩ wall — still reads missing; "every tied station" did not).  Only the runout composition sets it: its
1465/// own neighbouring wall may consume an edge's end (the rib nine-edge
1466/// selection's trimmed runout over the wall ∩ roof pad's first tenth read
1467/// as that pad having no wall), while elsewhere the first station is what
1468/// catches a cutter composition's wrong corners (the one-ended channel with
1469/// its runout switched off: stations ON at both ends of an edge whose middle
1470/// is walled — a measured 1253.219 against its 1253.373 body) and a station
1471/// reading alone cannot tell the two apart.
1472#[allow(clippy::too_many_arguments)]
1473pub fn walls_missing_ties(
1474    original: &BrepSolid,
1475    result: &BrepSolid,
1476    edge_points: &[Vec3],
1477    selected: &[usize],
1478    size: f64,
1479    chamfer: bool,
1480    entry: &str,
1481    tie_majority: bool,
1482) -> Result<Vec<usize>, KernelRefusal> {
1483// BREP lane L: end walls_missing_tie_all_stations_20261015
1484    use crate::{PointClass, SolidClassifier};
1485    if selected.is_empty() {
1486        return Ok(Vec::new());
1487    }
1488    let _timing = crate::blend::BlendTimer::start("timing.walls_missing_ms");
1489    crate::classification::classify_profile_begin();
1490    crate::classification::containment_profile_begin();
1491    let band = crate::KernelTolerances::for_solid(result, 1e-7).model;
1492    // `classify` reads `On` within ten times its band; attribution needs the
1493    // move to clear that by the same margin again.
1494    let visible = band * 100.0;
1495    let build_timing = crate::blend::BlendTimer::start("timing.walls_missing.classifier_ms");
1496    let classifier = SolidClassifier::new(result, band)
1497        .or_refuse(KernelStage::Validate, "wall_classifier")?;
1498    // Lane R1: a station's On-or-not is read
1499    // off its nearest face first (`NearestFaceSide`, the classifier's own On
1500    // band of ten `band`s, answering only where the read is rigorous); the
1501    // ray answers whatever it declines.
1502    let nearest = Some(super::analyze::NearestFaceSide::new(result, band).or_refuse(KernelStage::Validate, "wall_nearest_face")?);
1503    let reads_on = |point: Vec3| -> Result<bool, KernelRefusal> {
1504        if let Some(class) = nearest.as_ref().and_then(|nearest| nearest.side(point)) {
1505            crate::blend::record_count("count.walls_missing.nearest", 1);
1506            return Ok(class == PointClass::On);
1507        }
1508        Ok(classifier.classify(point).or_refuse(KernelStage::Validate, "wall_classify")?.class == PointClass::On)
1509    };
1510    build_timing.stop();
1511    const STATIONS: usize = 9;
1512    let mut missing = Vec::new();
1513    for &index in selected {
1514        let point = edge_points[index];
1515        let edge_id = resolve_edge_by_point(original, point)?;
1516        let (edge, faces) = super::analyze::edge_and_faces(original, edge_id)?;
1517        // The station the blend moves most, and how far.
1518        let mut best: Option<(Vec3, f64)> = None;
1519        // BREP lane L: begin walls_missing_tie_all_stations_20261015
1520        let mut read: Vec<(Vec3, f64)> = Vec::with_capacity(STATIONS);
1521        // BREP lane L: end walls_missing_tie_all_stations_20261015
1522        for step in 1..=STATIONS {
1523            let t = edge.t0 + (edge.t1 - edge.t0) * step as f64 / (STATIONS + 1) as f64;
1524            let Ok(station) = edge.curve.evaluate(t) else {
1525                continue;
1526            };
1527            let clearance = match faces[..] {
1528                [first, second] => {
1529                    let (Ok((_, a)), Ok((_, b))) = (
1530                        super::analyze::face_plane_normal(first, station),
1531                        super::analyze::face_plane_normal(second, station),
1532                    ) else {
1533                        continue;
1534                    };
1535                    let half: f64 = 0.5 * a.dot(b).clamp(-1.0, 1.0).acos();
1536                    if chamfer {
1537                        size * half.sin()
1538                    } else {
1539                        size * (1.0 / half.cos().max(1e-12) - 1.0)
1540                    }
1541                }
1542                // No dihedral to read: probe anyway, unguarded.
1543                _ => f64::INFINITY,
1544            };
1545            if best.map_or(true, |(_, known)| clearance > known) {
1546                best = Some((station, clearance));
1547            }
1548            // BREP lane L: begin walls_missing_tie_all_stations_20261015
1549            read.push((station, clearance));
1550            // BREP lane L: end walls_missing_tie_all_stations_20261015
1551        }
1552        let Some((station, clearance)) = best else {
1553            return Err(KernelRefusal::internal(
1554                KernelStage::Validate,
1555                "wall_attribution_stations",
1556                format!(
1557                    "{entry}: cannot attribute a wall to edge #{index} at ({:.6}, {:.6}, {:.6}) — no \
1558                     station of it could be evaluated",
1559                    point.x, point.y, point.z
1560                ),
1561            ));
1562        };
1563        if !(clearance > visible) {
1564            // The faces themselves put the move under the band: the input
1565            // leaves the attribution undecidable, and it is refused rather
1566            // than guessed.
1567            return Err(KernelRefusal::ill_posed(
1568                KernelStage::Validate,
1569                "wall_attribution_band",
1570                format!(
1571                    "{entry}: cannot attribute a wall to edge #{index} at ({:.6}, {:.6}, {:.6}) — \
1572                     its faces are so nearly tangent that a size-{size} blend moves the edge by at \
1573                     most {clearance:.3e}, inside the {visible:.3e} the classifier can see; the \
1574                     selection is refused rather than reported on a guess",
1575                    point.x, point.y, point.z
1576                ),
1577            ));
1578        }
1579        let classify_timing = crate::blend::BlendTimer::start("timing.walls_missing.classify_ms");
1580        // The question is On or not On, never In against Out: a station the
1581        // certificate below puts farther than `visible` from every face of
1582        // the result cannot read On by the classifier's band pass (a foot on
1583        // a carrier within ten bands) nor by its ray pass (a hit within ten
1584        // bands), so it is not asked. Anything the certificate declines is
1585        // classified as before.
1586        let certified = station_clear_of_skin(result, station, band * 10.0, visible)
1587            || station_clear_of_trimmed_skin(result, station, band * 10.0, visible);
1588        let on = if certified {
1589            crate::blend::record_count("count.walls_missing.certified", 1);
1590            false
1591        } else {
1592            crate::blend::record_count("count.walls_missing.classified", 1);
1593            reads_on(station)?
1594        };
1595        classify_timing.stop();
1596        // BREP lane L: begin walls_missing_tie_all_stations_20261015
1597        let on = on && (!tie_majority || {
1598            // The most-moved station read On; on a tie, so must more than
1599            // half of the tied stations (itself included).
1600            let tolerance = 1e-12 * clearance.abs().max(1.0);
1601            let (mut tied, mut on_skin) = (1usize, 1usize);
1602            for (other, other_clearance) in read.iter().copied() {
1603                if other.sub(station).length() == 0.0 || clearance - other_clearance > tolerance {
1604                    continue;
1605                }
1606                tied += 1;
1607                if !station_clear_of_skin(result, other, band * 10.0, visible) && reads_on(other)? {
1608                    on_skin += 1;
1609                }
1610            }
1611            2 * on_skin > tied
1612        });
1613        // BREP lane L: end walls_missing_tie_all_stations_20261015
1614        if on {
1615            missing.push(index);
1616        }
1617    }
1618    crate::classification::classify_profile_report("blend.walls_missing");
1619    crate::classification::containment_profile_report("blend.walls_missing");
1620    Ok(missing)
1621}
1622
1623
1624
1625/// Is `station` certainly farther than `margin` from every face of `result`,
1626/// trims included, read without a classifier query? `true` only when every
1627/// face is certified by one of three readings, each a lower bound on the
1628/// distance from the station to that face's trimmed carrier:
1629///
1630/// - its control-point box, widened by `on_band`, does not hold the station
1631///   (the carrier lies in the hull of positively weighted control points);
1632/// - its carrier is a recognised revolution (`NurbsSurface::analytic`,
1633///   matched to 1e-9 relative): a sphere or torus farther than `margin` in
1634///   closed form; a cone, cylinder or straight-generatrix partial sweep
1635///   whose PATCH is farther than `margin` by the larger of three lower
1636///   bounds, the meridian distance to the generatrix line, the axial
1637///   clearance from the generatrix's slab and the clearance from the
1638///   sweep's wedge (a station on one box edge lies ON the infinite cylinder
1639///   of each neighbouring wall, a radius from its centre line, and is a
1640///   radius short of its slab);
1641/// - its carrier is a recognised plane, the station's foot on it is
1642///   `Outside` the trims (`parameter_point_in_face`, the kernel's own lane
1643///   at the band the classifier would use), every loop pcurve is a straight
1644///   two-point unit-weight chord (so its image under the affine chart is a
1645///   straight 3-D segment, and the trim polygon is exact), and the station
1646///   is farther than `margin` from every chord's segment: a foot outside the
1647///   region is nearer to the region's boundary than to any of its points.
1648///
1649/// Any face none of the three reads (an unrecognised carrier, a plane the
1650/// station lies on whose trims are curved, a foot inside or on the trims)
1651/// declines the whole station to the classifier. The recogniser's 1e-9
1652/// relative bar sits four orders below the `margin` the caller passes
1653/// (a hundred model bands), which is what absorbs it.
1654fn station_clear_of_skin(result: &BrepSolid, station: Vec3, on_band: f64, margin: f64) -> bool {
1655    use crate::AnalyticSurface;
1656    // The station in a revolution frame: (ρ, h) in the meridian plane and
1657    // its azimuth θ in [0, 2π) from the frame's x axis.
1658    let meridian = |frame: &crate::RevolutionFrame| -> (f64, f64, f64) {
1659        let offset = station.sub(frame.origin);
1660        let axial = offset.dot(frame.axis);
1661        let radial = offset.sub(frame.axis.scale(axial));
1662        let mut azimuth = radial.dot(frame.y_axis).atan2(radial.dot(frame.x_axis));
1663        if azimuth < 0.0 {
1664            azimuth += std::f64::consts::TAU;
1665        }
1666        (radial.length(), axial, azimuth)
1667    };
1668    // A patch of a revolution lies inside the axial slab of its generatrix
1669    // and inside the wedge of its sweep, so the station's clearance from
1670    // either is a lower bound on its distance to the patch.
1671    let axial_clearance = |axial: f64, h0: f64, h1: f64| (h0.min(h1) - axial).max(axial - h0.max(h1)).max(0.0);
1672    let wedge_clearance = |radial: f64, azimuth: f64, sweep: f64| -> f64 {
1673        if sweep >= std::f64::consts::TAU || azimuth <= sweep {
1674            return 0.0;
1675        }
1676        // Outside the sweep: the angle to the nearer bounding meridian.
1677        let turn = (azimuth - sweep).min(std::f64::consts::TAU - azimuth);
1678        if turn >= std::f64::consts::FRAC_PI_2 { radial } else { radial * turn.sin() }
1679    };
1680    // Distance in the meridian plane from (ρ, h) to the LINE through two
1681    // generatrix points: a lower bound for a cone or cylinder's carrier.
1682    let line_distance = |radial: f64, axial: f64, (rho0, h0): (f64, f64), (rho1, h1): (f64, f64)| -> Option<f64> {
1683        let (du, dv) = (rho1 - rho0, h1 - h0);
1684        let length = (du * du + dv * dv).sqrt();
1685        (length > 0.0).then(|| ((radial - rho0) * dv - (axial - h0) * du).abs() / length)
1686    };
1687    let clear = |distance: f64| distance.is_finite() && distance > margin;
1688    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
1689        let Ok(controls) = crate::Aabb::from_surface_controls(&face.surface) else { return false };
1690        if !controls.expanded(on_band).contains(station) {
1691            continue;
1692        }
1693        let certified = match face.surface.analytic() {
1694            Some(AnalyticSurface::RuledRevolution { frame, rho0, rho1, height }) => {
1695                let (radial, axial, _) = meridian(frame);
1696                let Some(line) = line_distance(radial, axial, (*rho0, 0.0), (*rho1, *height)) else { return false };
1697                clear(line.max(axial_clearance(axial, 0.0, *height)))
1698            }
1699            Some(AnalyticSurface::Sphere { frame, radius }) => clear((station.sub(frame.origin).length() - radius).abs()),
1700            Some(AnalyticSurface::Torus { frame, major_radius, minor_radius }) => {
1701                let (radial, axial, _) = meridian(frame);
1702                let tube = radial - major_radius;
1703                clear(((tube * tube + axial * axial).sqrt() - minor_radius).abs())
1704            }
1705            Some(AnalyticSurface::Revolution { frame, sweep, generatrix, .. }) => {
1706                // A STRAIGHT generatrix in the frame's zero meridian (the
1707                // extruded-arc walls: a line parallel to the axis at the
1708                // radius): its two control points read as (ρ, h), and the
1709                // patch's distance is bounded below by the meridian line
1710                // distance, the axial clearance and the wedge clearance
1711                // together. A curved or off-meridian generatrix declines.
1712                let [a, b] = generatrix.control_points.as_slice() else { return false };
1713                if generatrix.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1714                    return false;
1715                }
1716                let meridian_of = |point: Vec3| -> Option<(f64, f64)> {
1717                    let offset = point.sub(frame.origin);
1718                    let axial = offset.dot(frame.axis);
1719                    let radial = offset.sub(frame.axis.scale(axial));
1720                    let rho = radial.length();
1721                    let on_meridian = radial.dot(frame.y_axis).abs() <= 1e-9 * rho.max(1.0) && radial.dot(frame.x_axis) >= -1e-9 * rho.max(1.0);
1722                    on_meridian.then_some((rho, axial))
1723                };
1724                let (Some(p0), Some(p1)) = (meridian_of(Vec3::new(a.x, a.y, a.z)), meridian_of(Vec3::new(b.x, b.y, b.z))) else {
1725                    return false;
1726                };
1727                let (radial, axial, azimuth) = meridian(frame);
1728                let Some(line) = line_distance(radial, axial, p0, p1) else { return false };
1729                // The TRIMMED face's slab is narrower than the surface's:
1730                // a station on one box edge lies on the untrimmed surface
1731                // of each perpendicular wall (that wall's rail line runs
1732                // through the corner), a radius short of its trimmed face.
1733                let slab = trimmed_axial_slab(face, frame).unwrap_or((p0.1, p1.1));
1734                clear(line.max(axial_clearance(axial, slab.0, slab.1)).max(wedge_clearance(radial, azimuth, *sweep)))
1735            }
1736            Some(plane @ AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) => {
1737                let Ok(normal) = u_dir.cross(*v_dir).normalized() else { return false };
1738                if clear(station.sub(*origin).dot(normal).abs()) {
1739                    true
1740                } else {
1741                    planar_trims_clear_of(face, plane, station, on_band, margin)
1742                }
1743            }
1744            None => false,
1745        };
1746        if !certified {
1747            return false;
1748        }
1749    }
1750    true
1751}
1752
1753/// A tighter sufficient Not-On certificate. General carriers use subdivided
1754/// positive-weight hulls. Analytic carriers retain the projector and trim
1755/// band used by the nearest-face reader; an exterior foot also needs every
1756/// exact boundary edge farther than the existing attribution margin.
1757/// Any inconclusive read leaves the original nearest/ray query in charge.
1758fn station_clear_of_trimmed_skin(result: &BrepSolid, point: Vec3, on_band: f64, margin: f64) -> bool {
1759    let _timer = crate::blend::BlendTimer::start("timing.walls_missing.trimmed_bound_ms");
1760    if !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite()
1761        || !margin.is_finite() || !(margin > on_band && on_band > 0.0)
1762    { return false; }
1763    for face in result.shells.iter().flat_map(|shell| &shell.faces) {
1764        let Ok(bounds) = crate::Aabb::from_surface_controls(&face.surface) else { return false; };
1765        if !bounds.expanded(margin).contains(point) { continue; }
1766        if face.surface.analytic().is_none() {
1767            if general_carrier_clear(&face.surface, point, margin) { continue; }
1768            return false;
1769        }
1770        // Within `margin`, these regular carriers have a unique nearest
1771        // foot; every other stationary foot is farther than the margin.
1772        // The sphere/torus medial sets and spindle/horn tori decline. Thus
1773        // an exterior nearest foot can meet a trimmed region within the
1774        // margin only by crossing a boundary edge inside that same ball.
1775        match face.surface.analytic() {
1776            Some(crate::AnalyticSurface::Plane { .. }) => {},
1777            Some(crate::AnalyticSurface::Sphere { radius, .. }) if *radius > 4.0 * margin => {},
1778            Some(crate::AnalyticSurface::Torus { major_radius, minor_radius, .. })
1779                if *minor_radius > 4.0 * margin && *major_radius > *minor_radius + 4.0 * margin => {},
1780            _ => return false,
1781        }
1782        let Ok(projection) = crate::project_point_to_surface(&face.surface, point) else { return false; };
1783        if !projection.distance.is_finite() { return false; }
1784        if projection.distance > margin { continue; }
1785        let band = crate::classification::surface_uv_band(&face.surface, projection.u, projection.v, on_band);
1786        let Ok(inside) = crate::parameter_point_in_face(face, crate::Vec2 { x: projection.u, y: projection.v }, band) else { return false; };
1787        if inside != crate::PolygonClass::Outside { return false; }
1788        let mut edges = 0;
1789        for coedge in face.loops.iter().flat_map(|lp| &lp.coedges) {
1790            let Some(edge) = result.edges.iter().find(|edge| edge.id == coedge.edge_id) else { return false; };
1791            let Some(piece) = super::analyze::edge_piece(&edge.curve, edge.t0.min(edge.t1), edge.t0.max(edge.t1)) else { return false; };
1792            let Ok(foot) = crate::project_point_to_curve(&piece, point) else { return false; };
1793            if !foot.distance.is_finite() || foot.distance <= margin { return false; }
1794            edges += 1;
1795        }
1796        if edges == 0 { return false; }
1797    }
1798    true
1799}
1800
1801/// A sufficient clearance test for a general carrier, without finding its
1802/// nearest point. Positive-weight Bezier patches lie inside their control
1803/// hulls. Decompose both clamped knot vectors, then bisect only boxes still
1804/// within `margin` of the query. Any unsupported net or exhausted work budget
1805/// declines to the existing classifier; no approximate distance is accepted.
1806fn general_carrier_clear(surface: &crate::NurbsSurface, point: Vec3, margin: f64) -> bool {
1807    use crate::Vec4;
1808    let rows = surface.control_points.len();
1809    let columns = surface.control_points.first().map_or(0, Vec::len);
1810    if rows == 0 || columns == 0 || rows.saturating_mul(columns) > 4096
1811        || surface.degree_u > 16 || surface.degree_v > 16 || surface.control_points.iter().any(|row| row.len() != columns)
1812        || !margin.is_finite() || margin <= 0.0
1813        || !point.x.is_finite() || !point.y.is_finite() || !point.z.is_finite()
1814    { return false; }
1815    let mut scale = 1.0_f64;
1816    for control in surface.control_points.iter().flatten() {
1817        if !(control.w > 0.0) || !control.w.is_finite() { return false; }
1818        let Ok(p) = control.point() else { return false; };
1819        if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { return false; }
1820        scale = scale.max(p.x.abs()).max(p.y.abs()).max(p.z.abs());
1821    }
1822    // Leave a rounding cushion far below the caller's existing model margin.
1823    // Unsupported scales decline rather than consume the classification band.
1824    let roundoff = 256.0 * f64::EPSILON * scale * (surface.degree_u + 1) as f64 * (surface.degree_v + 1) as f64;
1825    if roundoff >= margin * 0.01 { return false; }
1826    let zero = Vec4 { x: 0.0, y: 0.0, z: 0.0, w: 0.0 };
1827    let blend = |a: Vec4, b: Vec4, alpha: f64| a.scale(alpha).add(b.scale(1.0 - alpha));
1828    let mut fibres = Vec::with_capacity(columns);
1829    for column in 0..columns {
1830        let controls: Vec<_> = surface.control_points.iter().map(|row| row[column]).collect();
1831        let Some(spans) = crate::curve::bezier_decompose_raw(&surface.knots_u, &controls, surface.degree_u, zero, blend) else { return false; };
1832        fibres.push(spans);
1833    }
1834    let mut budget = 256usize;
1835    for u_span in 0..fibres[0].len() {
1836        let mut across = Vec::with_capacity(surface.degree_u + 1);
1837        for row in 0..=surface.degree_u {
1838            let controls: Vec<_> = fibres.iter().map(|fibre| fibre[u_span][row]).collect();
1839            let Some(spans) = crate::curve::bezier_decompose_raw(&surface.knots_v, &controls, surface.degree_v, zero, blend) else { return false; };
1840            across.push(spans);
1841        }
1842        for v_span in 0..across[0].len() {
1843            let net = across.iter().map(|row| row[v_span].clone()).collect();
1844            if !bezier_box_clear(net, point, margin + roundoff, 0, &mut budget) { return false; }
1845        }
1846    }
1847    true
1848}
1849
1850fn bezier_box_clear(net: Vec<Vec<crate::Vec4>>, point: Vec3, margin: f64, depth: usize, budget: &mut usize) -> bool {
1851    if *budget == 0 { return false; }
1852    *budget -= 1;
1853    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
1854    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
1855    for control in net.iter().flatten() {
1856        if !(control.w > 0.0) || !control.w.is_finite() { return false; }
1857        let Ok(p) = control.point() else { return false; };
1858        if !p.x.is_finite() || !p.y.is_finite() || !p.z.is_finite() { return false; }
1859        low.x = low.x.min(p.x); low.y = low.y.min(p.y); low.z = low.z.min(p.z);
1860        high.x = high.x.max(p.x); high.y = high.y.max(p.y); high.z = high.z.max(p.z);
1861    }
1862    // One separating coordinate is enough, and avoids a rounded square root.
1863    if point.x < low.x - margin || point.x > high.x + margin
1864        || point.y < low.y - margin || point.y > high.y + margin
1865        || point.z < low.z - margin || point.z > high.z + margin
1866    { return true; }
1867    if depth == 10 { return false; }
1868    let rows = net.len();
1869    let columns = net[0].len();
1870    let mut left = net.clone();
1871    let mut right = net.clone();
1872    // Alternate directions: every child covers exactly half the parent's
1873    // parameter rectangle; both must prove clearance.
1874    if depth % 2 == 0 {
1875        for column in 0..columns {
1876            let mut work: Vec<_> = net.iter().map(|row| row[column]).collect();
1877            for level in 1..rows {
1878                for i in 0..rows - level { work[i] = work[i].scale(0.5).add(work[i + 1].scale(0.5)); }
1879                left[level][column] = work[0];
1880                right[rows - level - 1][column] = work[rows - level - 1];
1881            }
1882        }
1883    } else {
1884        for row in 0..rows {
1885            let mut work = net[row].clone();
1886            for level in 1..columns {
1887                for i in 0..columns - level { work[i] = work[i].scale(0.5).add(work[i + 1].scale(0.5)); }
1888                left[row][level] = work[0];
1889                right[row][columns - level - 1] = work[columns - level - 1];
1890            }
1891        }
1892    }
1893    bezier_box_clear(left, point, margin, depth + 1, budget)
1894        && bezier_box_clear(right, point, margin, depth + 1, budget)
1895}
1896
1897/// The axial range `(h_low, h_high)` of a face's TRIMMED region on a
1898/// revolution whose generatrix is straight: the region lies in the uv box
1899/// of its straight-chord loops (every pcurve a two-point unit-weight
1900/// chord), the surface is a tensor product in which the axial coordinate
1901/// `h = (S − origin)·axis` depends on one parameter only and affinely
1902/// (degree 1, two control points along it), so `h` over the box is the
1903/// range between its values at the box's corners. `None` when any of that
1904/// is not read: a curved chord, an `h` that moves along both parameters,
1905/// a degree or control count that is not affine, an evaluation that fails.
1906fn trimmed_axial_slab(face: &FaceRecord, frame: &crate::RevolutionFrame) -> Option<(f64, f64)> {
1907    let (mut u_low, mut u_high, mut v_low, mut v_high) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
1908    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1909        let pcurve = &coedge.pcurve;
1910        let [a, b] = pcurve.control_points.as_slice() else { return None };
1911        if pcurve.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1912            return None;
1913        }
1914        for control in [a, b] {
1915            u_low = u_low.min(control.x);
1916            u_high = u_high.max(control.x);
1917            v_low = v_low.min(control.y);
1918            v_high = v_high.max(control.y);
1919        }
1920    }
1921    if !(u_low <= u_high && v_low <= v_high) {
1922        return None;
1923    }
1924    let axial_at = |u: f64, v: f64| face.surface.evaluate(u, v).ok().map(|point| point.sub(frame.origin).dot(frame.axis));
1925    let corners = [axial_at(u_low, v_low)?, axial_at(u_high, v_low)?, axial_at(u_low, v_high)?, axial_at(u_high, v_high)?];
1926    let scale = corners.iter().fold(1.0_f64, |scale, h| scale.max(h.abs()));
1927    let same = |a: f64, b: f64| (a - b).abs() <= 1e-9 * scale;
1928    let surface = &face.surface;
1929    // h constant along u (the generatrix runs along v), or along v.
1930    let affine_in_v = same(corners[0], corners[1]) && same(corners[2], corners[3])
1931        && surface.degree_v == 1 && surface.control_points.first().is_some_and(|row| row.len() == 2);
1932    let affine_in_u = same(corners[0], corners[2]) && same(corners[1], corners[3])
1933        && surface.degree_u == 1 && surface.control_points.len() == 2;
1934    if !(affine_in_v || affine_in_u) {
1935        return None;
1936    }
1937    let low = corners.iter().copied().fold(f64::INFINITY, f64::min);
1938    let high = corners.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1939    (low.is_finite() && high.is_finite()).then_some((low, high))
1940}
1941
1942/// The planar reading of [`station_clear_of_skin`]: the station's foot on
1943/// the plane lies `Outside` the face's trims and every straight loop chord's
1944/// 3-D segment is farther than `margin` from the station.
1945fn planar_trims_clear_of(
1946    face: &FaceRecord,
1947    plane: &crate::AnalyticSurface,
1948    station: Vec3,
1949    on_band: f64,
1950    margin: f64,
1951) -> bool {
1952    use crate::PolygonClass;
1953    let Some(foot) = plane.project(&face.surface, station) else { return false };
1954    let uv_band = crate::classification::surface_uv_band(&face.surface, foot.u, foot.v, on_band);
1955    match crate::parameter_point_in_face(face, crate::Vec2 { x: foot.u, y: foot.v }, uv_band) {
1956        Ok(PolygonClass::Outside) => {}
1957        _ => return false,
1958    }
1959    for coedge in face.loops.iter().flat_map(|loop_record| &loop_record.coedges) {
1960        let pcurve = &coedge.pcurve;
1961        let [a, b] = pcurve.control_points.as_slice() else { return false };
1962        if pcurve.degree != 1 || a.w != 1.0 || b.w != 1.0 {
1963            return false;
1964        }
1965        let (Ok(start), Ok(end)) = (face.surface.evaluate(a.x, a.y), face.surface.evaluate(b.x, b.y)) else { return false };
1966        let chord = end.sub(start);
1967        let length_squared = chord.dot(chord);
1968        let offset = station.sub(start);
1969        let along = if length_squared > 0.0 { (offset.dot(chord) / length_squared).clamp(0.0, 1.0) } else { 0.0 };
1970        let distance = offset.sub(chord.scale(along)).length();
1971        if !(distance.is_finite() && distance > margin) {
1972            return false;
1973        }
1974    }
1975    true
1976}
1977
1978/// The blend-FACE name for the `i`-th selected edge: its per-edge name when the
1979/// caller supplied the parallel `edge_names` (feature path — each wall named
1980/// after its originating edge, `{fid}:BLEND:{edge}`), else the single base
1981/// `name` for every wall (the legacy/test path, byte-identical to before).
1982fn per_edge_name<'a>(
1983    edge_names: Option<&'a [String]>,
1984    base: Option<&'a str>,
1985    i: usize,
1986) -> Option<&'a str> {
1987    match edge_names {
1988        Some(names) => names.get(i).map(|value| value.as_str()),
1989        None => base,
1990    }
1991}
1992
1993/// The star-corner patch name: `{base}:CORNER:{sorted+join of adjacent edge
1994/// names}` when per-edge names were supplied (feature path), else the single
1995/// `base` (legacy/test path — the corner keeps the wall name, pre-change
1996/// behavior).  `base` is `{fid}:BLEND` and each `edge_names[i]` is the composed
1997/// `{fid}:BLEND:{edge}`, so stripping the `{base}:` prefix recovers the bare
1998/// originating-edge name for the join.  Unique per corner: two distinct corners
1999/// never share the same set of >=3 selected edges.
2000fn corner_face_name(
2001    edge_names: Option<&[String]>,
2002    base: Option<&str>,
2003    adjacent: &[usize],
2004) -> Option<String> {
2005    match (edge_names, base) {
2006        (Some(names), Some(base)) => {
2007            let prefix = format!("{base}:");
2008            let mut raws: Vec<&str> = adjacent
2009                .iter()
2010                .filter_map(|&i| names.get(i))
2011                .map(|composed| composed.strip_prefix(&prefix).unwrap_or(composed.as_str()))
2012                .collect();
2013            raws.sort_unstable();
2014            raws.dedup();
2015            Some(format!("{base}:CORNER:{}", raws.join("+")))
2016        }
2017        _ => base.map(|value| value.to_string()),
2018    }
2019}
2020
2021/// Round a connected group of convex edges first, including its ordinary
2022/// convex corner patches, then blend the concave rim across a curved bridge
2023/// at each transverse mixed corner. The spine's carriers and the cap may be
2024/// planes or curved analytic faces alike: transversality is read from the
2025/// three normals at the corner, and the rim network marches the bridge on the
2026/// actual carriers. Without these bridges the rim stripes would remain
2027/// disconnected. Redispatch the remaining selection: other mixed corners may
2028/// need another convex group or a pole-to-pole runout.
2029/// Each step removes the rounded group from the pending selection.
2030#[allow(clippy::too_many_arguments)]
2031fn rounded_boss_composition(
2032    solid: &BrepSolid,
2033    selected_ids: &[u64],
2034    edge_points: &[Vec3],
2035    edge_names: Option<&[String]>,
2036    radius: f64,
2037    name: Option<&str>,
2038    corners: &[crate::blend::MixedCorner],
2039) -> Result<BrepSolid, KernelRefusal> {
2040    // The legacy API gives every wall the same base name (or none). Use
2041    // distinct temporary identities through the recursive composition so a
2042    // bridge can be attributed to its own convex wall. Restore that API's
2043    // naming contract after the whole selection has been built.
2044    if edge_names.is_none() {
2045        let prefix = "FILLET:COMPOSITION";
2046        let names: Vec<_> = selected_ids
2047            .iter()
2048            .map(|id| format!("{prefix}:{id}"))
2049            .collect();
2050        let mut result = rounded_boss_composition(
2051            solid,
2052            selected_ids,
2053            edge_points,
2054            Some(&names),
2055            radius,
2056            Some(prefix),
2057            corners,
2058        )?;
2059        for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
2060            if face
2061                .name
2062                .as_deref()
2063                .is_some_and(|value| value.starts_with("FILLET:COMPOSITION:"))
2064            {
2065                face.name = name.map(str::to_owned);
2066            }
2067        }
2068        return Ok(result);
2069    }
2070    let decline = || {
2071        KernelRefusal::unsupported(KernelStage::Classify, "rounded_boss_selection",
2072        "the rounded boss composition requires a convex group meeting transverse mixed corners at one end of each spine")
2073    };
2074    if std::env::var("BREP_NO_NETWORK").is_ok() {
2075        return Err(decline());
2076    }
2077    // Select by topology id so reversing the requested edges preserves the
2078    // construction order. Two-ended spines are left for runout composition.
2079    let corner = corners
2080        .iter()
2081        .filter(|corner| {
2082            corner.convex.len() == 1
2083                && corner.concave.len() == 2
2084                && corners
2085                    .iter()
2086                    .filter(|other| other.convex.contains(&corner.convex[0]))
2087                    .count()
2088                    == 1
2089        })
2090        .min_by_key(|corner| selected_ids[corner.convex[0]])
2091        .ok_or_else(decline)?;
2092    let convexity =
2093        crate::blend::selection_convexity(solid, selected_ids, radius).ok_or_else(decline)?;
2094    if !convexity[corner.convex[0]] {
2095        return Err(decline());
2096    }
2097    let spine_index = corner.convex[0];
2098    // Resolve once so a missing selected edge refuses before connectivity
2099    // traversal rather than panicking inside the adjacency predicate.
2100    let selected_edges: Vec<&EdgeRecord> = selected_ids
2101        .iter()
2102        .map(|id| {
2103            solid
2104                .edges
2105                .iter()
2106                .find(|edge| edge.id == *id)
2107                .ok_or_else(|| {
2108                    KernelRefusal::internal(
2109                        KernelStage::Collect,
2110                        "rounded_boss_selected_edge",
2111                        format!("rounded boss composition: selected edge {id} is missing"),
2112                    )
2113                })
2114        })
2115        .collect::<Result<_, _>>()?;
2116    // Round the connected convex selection together. Its far corners need
2117    // their usual vertex patches before a concave rim can cross these walls.
2118    let mut rounded_indices = vec![spine_index];
2119    loop {
2120        let next = (0..selected_ids.len()).find(|index| {
2121            convexity[*index]
2122                && !rounded_indices.contains(index)
2123                && rounded_indices.iter().any(|other| {
2124                    let edge = selected_edges[*index];
2125                    let mate = selected_edges[*other];
2126                    [edge.start_vertex_id, edge.end_vertex_id]
2127                        .iter()
2128                        .any(|v| *v == mate.start_vertex_id || *v == mate.end_vertex_id)
2129                })
2130        });
2131        match next {
2132            Some(index) => rounded_indices.push(index),
2133            None => break,
2134        }
2135    }
2136    // Keep complete stars together. A selected concave edge between two
2137    // convex rims is part of their vertex blend, even though it is not part
2138    // of the convex flood above. Rounding the rims without it builds a horn
2139    // torus for an *unselected* third edge; adding that edge later leaves a
2140    // flat cap against the torus instead of the selected star's tangent sector.
2141    // Only absorb an edge whose selected neighbours are already in this
2142    // group at BOTH ends. In particular, never pull in a concave rim leading
2143    // to another mixed corner: that rim still needs the bridge below.
2144    loop {
2145        let next = (0..selected_ids.len()).find(|&index| {
2146            if convexity[index] || rounded_indices.contains(&index) {
2147                return false;
2148            }
2149            let edge = selected_edges[index];
2150            let mut has_star = false;
2151            for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
2152                let neighbours: Vec<_> = selected_edges.iter().enumerate()
2153                    .filter(|(other, mate)| *other != index
2154                        && (mate.start_vertex_id == vertex || mate.end_vertex_id == vertex))
2155                    .map(|(other, _)| other)
2156                    .collect();
2157                if neighbours.iter().any(|other| !rounded_indices.contains(other)) {
2158                    return false;
2159                }
2160                has_star |= neighbours.len() >= 2;
2161            }
2162            has_star
2163        });
2164        match next {
2165            Some(index) => rounded_indices.push(index),
2166            None => break,
2167        }
2168    }
2169    rounded_indices.sort_by_key(|index| selected_ids[*index]);
2170    let mixed: Vec<_> = corners
2171        .iter()
2172        .filter(|corner| {
2173            corner
2174                .convex
2175                .iter()
2176                .any(|index| rounded_indices.contains(index))
2177        })
2178        .collect();
2179    if mixed.iter().any(|corner| {
2180        corner.convex.len() != 1
2181            || corner.concave.len() != 2
2182            || corners
2183                .iter()
2184                .filter(|other| other.convex.contains(&corner.convex[0]))
2185                .count()
2186                != 1
2187    }) {
2188        return Err(decline());
2189    }
2190    let uses = |face: &FaceRecord, edge: u64| {
2191        face.loops
2192            .iter()
2193            .flat_map(|rim| &rim.coedges)
2194            .any(|coedge| coedge.edge_id == edge)
2195    };
2196    let mut caps = Vec::new();
2197    for corner in &mixed {
2198        let spine_id = selected_ids[corner.convex[0]];
2199        let cap = solid
2200            .shells
2201            .iter()
2202            .flat_map(|shell| &shell.faces)
2203            .find(|face| {
2204                corner
2205                    .concave
2206                    .iter()
2207                    .all(|index| uses(face, selected_ids[*index]))
2208            })
2209            .ok_or_else(decline)?;
2210        let faces: Vec<_> = solid
2211            .shells
2212            .iter()
2213            .flat_map(|shell| &shell.faces)
2214            .filter(|face| face.id == cap.id || uses(face, spine_id))
2215            .collect();
2216        // The normals at the corner: a plane's from its frame, any other
2217        // carrier's at the corner's own foot on it.  The 2026-10-12 sprocket
2218        // report (`inbox_20261012_sprocket_fillet`) was the first curved CAP;
2219        // the 2026-10-13 reports on the same part put the SPINE on a cylinder
2220        // (the rim top's arc, rim wall ∩ rim top, dying into the spoke wall)
2221        // and were declined here before anything was tried, which handed the
2222        // whole selection to the runout lane and its refusal
2223        // (`inbox_20261013_sprocket_spoke_fillet`).
2224        let normals: Option<Vec<Vec3>> = faces
2225            .iter()
2226            .map(|face| match face.surface.analytic() {
2227                Some(crate::AnalyticSurface::Plane { u_dir, v_dir, .. }) => {
2228                    u_dir.cross(*v_dir).normalized().ok()
2229                }
2230                _ => {
2231                    let uv = crate::project_point_to_surface(&face.surface, corner.point).ok()?;
2232                    face.surface.normal(uv.u, uv.v).ok()
2233                }
2234            })
2235            .collect();
2236        let normals = normals.ok_or_else(decline)?;
2237        // The cap need not be perpendicular to the spine's two carriers.
2238        // An oblique or cylindrical cap cuts the rounded wall in a curved
2239        // bridge. The rim network marches that bridge on the actual carriers.
2240        // Test transversality at the corner; a cylindrical cap need not be
2241        // replaced by its tangent plane to build this composition.
2242        if normals.len() != 3
2243            || normals[0].cross(normals[1]).dot(normals[2]).abs() < 1e-6
2244        {
2245            return Err(decline());
2246        }
2247        caps.push(cap.id);
2248    }
2249    // Give unnamed walls distinct identities too: bridges are located by
2250    // their two carriers, never proximity to the old corner.
2251    let rounded_names: Vec<String> = rounded_indices
2252        .iter()
2253        .map(|index| {
2254            per_edge_name(edge_names, name, *index)
2255                .map(str::to_owned)
2256                .unwrap_or_else(|| format!("FILLET:ROUNDED_BOSS_SPINE:{index}"))
2257        })
2258        .collect();
2259    let rounded_points: Vec<Vec3> = rounded_indices
2260        .iter()
2261        .map(|index| edge_points[*index])
2262        .collect();
2263    let rounded = fillet_edges_group_in(
2264        solid,
2265        &rounded_points,
2266        Some(&rounded_names),
2267        radius,
2268        false,
2269        name,
2270        None,
2271    )?;
2272    let mut bridges = Vec::new();
2273    for (corner, cap) in mixed.iter().zip(&caps) {
2274        let wall_index = rounded_indices
2275            .iter()
2276            .position(|index| *index == corner.convex[0])
2277            .ok_or_else(|| {
2278                KernelRefusal::internal(
2279                    KernelStage::Classify,
2280                    "rounded_boss_bridge_wall",
2281                    format!(
2282                        "rounded boss composition: no convex wall for corner {}",
2283                        corner.vertex
2284                    ),
2285                )
2286            })?;
2287        let candidates: Vec<_> = rounded
2288            .edges
2289            .iter()
2290            .filter(|edge| {
2291                let faces: Vec<_> = rounded
2292                    .shells
2293                    .iter()
2294                    .flat_map(|shell| &shell.faces)
2295                    .filter(|face| uses(face, edge.id))
2296                    .collect();
2297                faces.iter().any(|face| face.id == *cap)
2298                    && faces
2299                        .iter()
2300                        .any(|face| face.name.as_deref() == Some(&rounded_names[wall_index]))
2301            })
2302            .collect();
2303        if candidates.len() != 1 {
2304            return Err(decline());
2305        }
2306        bridges.push(candidates[0]);
2307    }
2308    let rim_ids: Vec<u64> = selected_ids
2309        .iter()
2310        .enumerate()
2311        .filter(|(index, _)| !rounded_indices.contains(index))
2312        .map(|(_, id)| *id)
2313        .collect();
2314    // Both ends must join requested rim edges: never extend a selection
2315    // into an unselected perimeter.
2316    if !bridges.iter().all(|bridge| {
2317        [bridge.start_vertex_id, bridge.end_vertex_id]
2318            .iter()
2319            .all(|vertex| {
2320                rounded.edges.iter().any(|edge| {
2321                    rim_ids.contains(&edge.id)
2322                        && (edge.start_vertex_id == *vertex || edge.end_vertex_id == *vertex)
2323                })
2324            })
2325    }) {
2326        return Err(decline());
2327    }
2328    let mut points = Vec::new();
2329    let mut names = Vec::new();
2330    for (index, id) in selected_ids.iter().enumerate() {
2331        if rounded_indices.contains(&index) {
2332            continue;
2333        }
2334        let edge = rounded
2335            .edges
2336            .iter()
2337            .find(|edge| edge.id == *id)
2338            .ok_or_else(decline)?;
2339        points.push(
2340            edge.curve
2341                .evaluate(0.5 * (edge.t0 + edge.t1))
2342                .or_refuse(KernelStage::Collect, "rim_midpoint")?,
2343        );
2344        names.push(
2345            per_edge_name(edge_names, name, index)
2346                .unwrap_or("FILLET:RIM")
2347                .to_owned(),
2348        );
2349    }
2350    for (corner, bridge) in mixed.iter().zip(&bridges) {
2351        points.push(
2352            bridge
2353                .curve
2354                .evaluate(0.5 * (bridge.t0 + bridge.t1))
2355                .or_refuse(KernelStage::Collect, "bridge_midpoint")?,
2356        );
2357        let mut adjacent = corner.concave.clone();
2358        adjacent.push(corner.convex[0]);
2359        names.push(
2360            corner_face_name(edge_names, name, &adjacent)
2361                .unwrap_or_else(|| format!("FILLET:BOSS_CORNER:{}", corner.vertex)),
2362        );
2363    }
2364    // A partial rim would leave an open mixed-corner construction. Require
2365    // every pending wall, including each bridge, before accepting composition.
2366    fillet_edges_reported(&rounded, &points, Some(&names), radius, false, name).and_then(
2367        |(result, selection)| {
2368            if selection.applied.len() != points.len() {
2369                Err(decline())
2370            } else {
2371                Ok(result)
2372            }
2373        },
2374    )
2375}
2376
2377// A corner with two concave edges and a convex one requires composition.
2378//
2379// Where selected edges meet, the rolling ball has to touch every face around
2380// the vertex from ONE side. A convex edge running into the concave edges it
2381// meets (a rib spine dying into the fillets at its own base) asks the ball to
2382// sit under the shared face for one blend and over it for the other, so no
2383// ball seats there and the corner has no closure: physically the convex blend
2384// runs out against the concave beads partway along the edge, which is a vertex
2385// blend the stripe network does not construct.
2386//
2387// The re-entrant vertex of a notch — ONE concave edge, the rest convex — is
2388// NOT this: the ball rolls round that single concave edge from one convex
2389// blend to the next, and `round_concave_chain_corner` / `round_convex_corner`
2390// close it with the horn-torus sector.  Only its mirror is refused.
2391//
2392// This is TERMINAL — deliberately not a fall-through to the cutter
2393// composition. The cutter answers this shape with a watertight but shredded
2394// solid: a sliver end cap at each unclosed corner and the carrier face split
2395// so the original name lands on a fragment, which breaks every downstream
2396// reference to it. A named refusal that says which edges to separate is
2397// worth more than that solid. The runout composition (the 2026-09-30 record
2398// §5): a selection whose convex edges die into concave ones at
2399// mixed-convexity corners is built in two stages — the CONCAVE edges first,
2400// through the ordinary group path (exactly the ring the user gets selecting
2401// them alone), then one runout wall per convex spine on that ring result,
2402// marched from pole to pole with its carriers switching onto the ring's own
2403// pads. Accepted under the network's own checks.
2404//
2405// The class built here: every convex edge of the selection ends on a mixed
2406// corner at BOTH ends and shares no vertex with another convex edge, and
2407// every other selected edge is concave.  Anything else keeps the named
2408// refusal.
2409#[allow(clippy::too_many_arguments)]
2410/// The OPEN-PAD composition (the 2026-10-17 "fillet takes way too long"
2411/// face-ring report): a selection whose every mixed corner is ONE convex edge
2412/// meeting ONE concave edge over the planar face they share, the third edge
2413/// at the corner either a tangent rail (the convex edge is a blend's own end
2414/// cut by the plane, the concave one the boss it was blended to: a zero-angle
2415/// sliver on the plane) or a sharp concave edge (the boss meeting the convex
2416/// edge's other mate). Neither the rounded-boss nor the runout composition
2417/// admits it (flush-joined convex chains, concave pads ending at the corners,
2418/// no concave ring).
2419///
2420/// Built in two stages on the stripe network, each an ordinary group build:
2421///
2422/// 1. Every CONVEX edge first. A convex chain's free end at a mixed corner
2423///    is the §6.9 transverse construction against the boss as the end face:
2424///    the wall is trimmed where its envelope enters the boss, the sliver tip
2425///    of the planar face goes, and the boss skin that lay under it is exposed
2426///    along the trim curve (no cliff: the trim runs from the wall's floor
2427///    rail to its rail on the other mate, which at a tangent-rail corner
2428///    lands on that rail where wall and boss are tangent).
2429/// 2. Every CONCAVE edge on the stage-1 body, EXTENDED by the trim curves it
2430///    now continues into G1 at each trimmed end (floor|boss into wall|boss
2431///    across the wall's floor rail, a tangent seam): a flush join with a seam
2432///    at the trim's start, and at the trim's far end a pole where the wall
2433///    is tangent to the boss, or a cap where the trim meets an unselected
2434///    sharp edge. The pad rides the wall past the floor rails' crossing.
2435///
2436/// The walls are named after their edges; a trim continuation is named
2437/// `{base}:RUNOUT:{pad}+{wall}` from the two bare edge names.
2438#[allow(clippy::too_many_arguments)]
2439fn open_pad_composition(
2440    solid: &BrepSolid,
2441    selected_ids: &[u64],
2442    edge_points: &[Vec3],
2443    edge_names: Option<&[String]>,
2444    radius: f64,
2445    name: Option<&str>,
2446    corners: &[crate::blend::MixedCorner],
2447    entry: &str,
2448) -> Result<BrepSolid, KernelRefusal> {
2449    let shape = |message: String| KernelRefusal::unsupported(KernelStage::Classify, "open_pad_shape", message);
2450    if std::env::var("BREP_NO_NETWORK").is_ok() {
2451        return Err(shape("the open-pad composition is a network construction and BREP_NO_NETWORK is set".into()));
2452    }
2453    if corners.is_empty() || corners.iter().any(|corner| corner.convex.len() != 1 || corner.concave.len() != 1) {
2454        return Err(shape("the open-pad composition is built for corners of one convex and one concave edge".into()));
2455    }
2456    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2457        .ok_or_else(|| shape("the selection's convexity could not be read edge by edge".into()))?;
2458    let concave: Vec<usize> = (0..selected_ids.len()).filter(|index| !convexity[*index]).collect();
2459    let convex: Vec<usize> = (0..selected_ids.len()).filter(|index| convexity[*index]).collect();
2460    if concave.is_empty() || convex.is_empty() {
2461        return Err(shape("the open-pad composition needs convex and concave edges".into()));
2462    }
2463    // Every concave edge ends at mixed corners (an open pad), and the face
2464    // the two edges share at each corner is planar.
2465    let mates = crate::blend::selection_mates(solid, selected_ids, radius)
2466        .map_err(|error| shape(format!("the selection's mates could not be read: {error}")))?;
2467    for corner in corners {
2468        let (_, convex_faces) = &mates[corner.convex[0]];
2469        let (_, concave_faces) = &mates[corner.concave[0]];
2470        let Some(shared) = convex_faces.iter().find(|face| concave_faces.iter().any(|other| other.id == face.id)) else {
2471            return Err(shape(format!("the two edges at vertex {} share no face", corner.vertex)));
2472        };
2473        if !matches!(shared.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) {
2474            return Err(shape(format!("the face {} the edges share at vertex {} is not planar", shared.id, corner.vertex)));
2475        }
2476    }
2477    for &index in &concave {
2478        let edge = mates[index].0;
2479        for vertex in [edge.start_vertex_id, edge.end_vertex_id] {
2480            if !corners.iter().any(|corner| corner.vertex == vertex && corner.concave[0] == index) {
2481                return Err(shape(format!(
2482                    "concave {} does not end at a mixed corner at vertex {vertex}; the open-pad composition is built for pads that do",
2483                    selection_label(index, edge_points, edge_names, name)
2484                )));
2485            }
2486        }
2487    }
2488    let base = name.unwrap_or("FILLET:OPEN_PAD");
2489    let bare = |index: usize| -> String {
2490        per_edge_name(edge_names, name, index)
2491            .map(|composed| composed.strip_prefix(&format!("{base}:")).unwrap_or(composed).to_string())
2492            .unwrap_or_else(|| selected_ids[index].to_string())
2493    };
2494    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2495
2496    // ---- Stage 1: the convex edges, as the group they are. ----
2497    let convex_points: Vec<Vec3> = convex.iter().map(|index| edge_points[*index]).collect();
2498    let convex_names: Vec<String> = convex
2499        .iter()
2500        .map(|index| per_edge_name(edge_names, name, *index).map(str::to_owned).unwrap_or_else(|| format!("{base}:WALL:{}", selected_ids[*index])))
2501        .collect();
2502    // Stage 1's body is an intermediate: the bowtie and soundness scans run
2503    // once, on stage 2's body (and the caller's acceptance after it), not on
2504    // a body the pads are about to change (1.2 s of tessellation on the
2505    // reported ring).
2506    // Both stages run as the open-pad composition's network
2507    // (`with_open_pad_network`: carrier-boundary stations, the march
2508    // extended to a section end outside the overshoot); no other network
2509    // takes those, so every body the plain network built stays as it was.
2510    let stage1 = crate::blend::with_open_pad_network(|| {
2511        fillet_edges_group_with_corner_policy(solid, &convex_points, Some(&convex_names), radius, false, name, None, true, false)
2512    })
2513    .map_err(|error| error.with_message(|error| format!("open-pad composition, the convex walls: {error}")))?;
2514    if debug {
2515        eprintln!("open-pad composition: stage 1 built the {} convex walls", convex.len());
2516    }
2517
2518    // ---- Stage 2: each pad with its trim continuations, on the stage-1 body. ----
2519    let uses = |face: &FaceRecord, edge_id: u64| face.loops.iter().flat_map(|l| &l.coedges).any(|c| c.edge_id == edge_id);
2520    let mut points: Vec<Vec3> = Vec::new();
2521    let mut names: Vec<String> = Vec::new();
2522    for &index in &concave {
2523        let (edge, faces) = &mates[index];
2524        let boss_id = if matches!(faces[0].surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) { faces[1].id } else { faces[0].id };
2525        let pad = stage1
2526            .edges
2527            .iter()
2528            .find(|candidate| candidate.id == edge.id)
2529            .ok_or_else(|| KernelRefusal::internal(KernelStage::Classify, "open_pad_edge", format!(
2530                "open-pad composition: concave edge {} vanished from the stage-1 body", edge.id
2531            )))?;
2532        points.push(pad.curve.evaluate(0.5 * (pad.t0 + pad.t1)).or_refuse(KernelStage::Collect, "pad_midpoint")?);
2533        names.push(per_edge_name(edge_names, name, index).map(str::to_owned).unwrap_or_else(|| format!("{base}:PAD:{}", edge.id)));
2534        // The trim continuations: at each end of the (trimmed) pad, the edge
2535        // that borders the boss and a stage-1 wall.
2536        for vertex in [pad.start_vertex_id, pad.end_vertex_id] {
2537            let trims: Vec<&EdgeRecord> = stage1
2538                .edges
2539                .iter()
2540                .filter(|candidate| {
2541                    candidate.id != pad.id
2542                        && !candidate.degenerate
2543                        && (candidate.start_vertex_id == vertex || candidate.end_vertex_id == vertex)
2544                })
2545                .filter(|candidate| {
2546                    let faces: Vec<&FaceRecord> = stage1.shells.iter().flat_map(|shell| &shell.faces).filter(|face| uses(face, candidate.id)).collect();
2547                    faces.iter().any(|face| face.id == boss_id)
2548                        && faces.iter().any(|face| face.name.as_deref().is_some_and(|value| convex_names.iter().any(|wall| wall == value)))
2549                })
2550                .collect();
2551            match trims.as_slice() {
2552                [trim] => {
2553                    let wall_name = stage1
2554                        .shells
2555                        .iter()
2556                        .flat_map(|shell| &shell.faces)
2557                        .filter(|face| uses(face, trim.id))
2558                        .find_map(|face| face.name.clone().filter(|value| convex_names.contains(value)))
2559                        .unwrap_or_default();
2560                    let wall_bare = wall_name.strip_prefix(&format!("{base}:")).unwrap_or(&wall_name).to_string();
2561                    points.push(trim.curve.evaluate(0.5 * (trim.t0 + trim.t1)).or_refuse(KernelStage::Collect, "trim_midpoint")?);
2562                    names.push(format!("{base}:RUNOUT:{}+{wall_bare}", bare(index)));
2563                    if debug {
2564                        eprintln!("open-pad composition: pad {} continues into trim edge {} (wall {wall_name}) at vertex {vertex}", edge.id, trim.id);
2565                    }
2566                }
2567                [] => {
2568                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "open_pad_trim", format!(
2569                        "open-pad composition: at vertex {vertex} the concave {} meets no trim curve of a stage-1 wall on the boss",
2570                        selection_label(index, edge_points, edge_names, name)
2571                    )));
2572                }
2573                _ => {
2574                    return Err(KernelRefusal::unsupported(KernelStage::Classify, "open_pad_trim", format!(
2575                        "open-pad composition: at vertex {vertex} the concave {} meets {} trim curves",
2576                        selection_label(index, edge_points, edge_names, name), trims.len()
2577                    )));
2578                }
2579            }
2580        }
2581    }
2582    let result = crate::blend::with_open_pad_network(|| fillet_edges_group_in(&stage1, &points, Some(&names), radius, false, name, None))
2583        .map_err(|error| error.with_message(|error| format!("open-pad composition, the pads on the walls: {error}")))?;
2584    let _ = entry;
2585    Ok(result)
2586}
2587
2588/// The CUSP composition (2026-10-24/25 reports 80c5d9d1 and 6dfd5a22): a
2589/// selection whose every mixed corner is a CUSP — a convex edge and a concave
2590/// edge leaving the vertex tangent to each other, the face they share
2591/// narrowing to zero width between them. Report 6dfd5a22 selects the whole
2592/// of E6's start-face sliver outside F2's r 5 round: its two straight convex
2593/// edges run on G1 into the concave arc at both tips.
2594///
2595/// No other composition admits it: the pads of the open-pad composition
2596/// trim into the boss, and here both blends must TAPER to the tip, each
2597/// against the face the other leaves. Built in two stages, each an ordinary
2598/// group build, the order report 80c5d9d1 took by hand (F9, then F10):
2599///
2600/// 1. Every CONCAVE edge first: its round tapers to zero at each cusp
2601///    (`blend/taper_runout.rs`), leaving a hairline of the shared face
2602///    beside it.
2603/// 2. Every CONVEX edge on the stage-1 body: its round tapers to zero at the
2604///    same tips, with the width read against the stage-1 round's rail (the
2605///    face's boundary past the cusp line, `taper_runout::boundary_chain`).
2606///    The two rounds are G1 to the hairline between them.
2607fn cusp_composition(
2608    solid: &BrepSolid,
2609    selected_ids: &[u64],
2610    edge_points: &[Vec3],
2611    edge_names: Option<&[String]>,
2612    radius: f64,
2613    name: Option<&str>,
2614    corners: &[crate::blend::MixedCorner],
2615) -> Result<BrepSolid, KernelRefusal> {
2616    let shape = |message: String| KernelRefusal::unsupported(KernelStage::Classify, "cusp_composition_shape", message);
2617    if std::env::var("BREP_NO_NETWORK").is_ok() {
2618        return Err(shape("the cusp composition is a network construction and BREP_NO_NETWORK is set".into()));
2619    }
2620    let edge_of = |index: usize| solid.edges.iter().find(|edge| edge.id == selected_ids[index]);
2621    // The unit tangent leaving `vertex` into the edge.
2622    let away = |index: usize, vertex: u64| -> Option<Vec3> {
2623        let edge = edge_of(index)?;
2624        let at_start = edge.start_vertex_id == vertex;
2625        let tangent = edge.curve.unit_tangent(if at_start { edge.t0 } else { edge.t1 }, edge.t0, edge.t1).ok()?;
2626        Some(if at_start { tangent } else { tangent.scale(-1.0) })
2627    };
2628    if corners.is_empty() {
2629        return Err(shape("no mixed corners".into()));
2630    }
2631    for corner in corners {
2632        let cusped = corner.convex.iter().all(|&convex| {
2633            corner.concave.iter().any(|&concave| {
2634                matches!((away(convex, corner.vertex), away(concave, corner.vertex)), (Some(a), Some(b)) if a.dot(b) >= 1.0 - 1e-6)
2635            })
2636        });
2637        if !cusped || corner.convex.is_empty() || corner.concave.is_empty() {
2638            return Err(shape(format!("the mixed corner at vertex {} is not a cusp", corner.vertex)));
2639        }
2640    }
2641    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2642        .ok_or_else(|| shape("the selection's convexity could not be read edge by edge".into()))?;
2643    let concave: Vec<usize> = (0..selected_ids.len()).filter(|index| !convexity[*index]).collect();
2644    let convex: Vec<usize> = (0..selected_ids.len()).filter(|index| convexity[*index]).collect();
2645    if concave.is_empty() || convex.is_empty() {
2646        return Err(shape("the cusp composition needs convex and concave edges".into()));
2647    }
2648    let names_of = |indices: &[usize]| -> Option<Vec<String>> { edge_names.map(|names| indices.iter().map(|index| names[*index].clone()).collect()) };
2649    let points_of = |indices: &[usize]| -> Vec<Vec3> { indices.iter().map(|index| edge_points[*index]).collect() };
2650    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2651    let stage1 = fillet_edges_group_in(solid, &points_of(&concave), names_of(&concave).as_deref(), radius, false, name, None)
2652        .map_err(|error| error.with_message(|error| format!("cusp composition, the concave rounds: {error}")))?;
2653    if debug {
2654        eprintln!("cusp composition: stage 1 built the {} concave rounds", concave.len());
2655    }
2656    // Each convex edge is read again on the stage-1 body by its point: the
2657    // taper split it only at its hairline's end, beside the tip.
2658    for &index in &convex {
2659        resolve_edge_by_point(&stage1, edge_points[index])
2660            .map_err(|error| error.with_message(|error| format!("cusp composition: a convex edge is not on the stage-1 body: {error}")))?;
2661    }
2662    let result = fillet_edges_group_in(&stage1, &points_of(&convex), names_of(&convex).as_deref(), radius, false, name, None)
2663        .map_err(|error| error.with_message(|error| format!("cusp composition, the convex rounds: {error}")))?;
2664    // Every round here tapers to zero at a tip, and the two rounds meet on
2665    // the hairline of the face between them: an edge's end stations stay ON
2666    // the skin (the concave arc's first tenth, where the convex round's
2667    // contact lands back on the arc), and the wall check reads the majority
2668    // of a tie, as it does for the runout composition's network ring.
2669    RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(true));
2670    Ok(result)
2671}
2672
2673fn runout_composition(
2674    solid: &BrepSolid,
2675    selected_ids: &[u64],
2676    edge_points: &[Vec3],
2677    edge_names: Option<&[String]>,
2678    radius: f64,
2679    name: Option<&str>,
2680    corners: &[crate::blend::MixedCorner],
2681    entry: &str,
2682) -> Result<BrepSolid, KernelRefusal> {
2683    if std::env::var("BREP_NO_NETWORK").is_ok() {
2684        return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_no_network", "the runout composition is a network construction and BREP_NO_NETWORK is set"));
2685    }
2686    let convexity = crate::blend::selection_convexity(solid, selected_ids, radius)
2687        .ok_or(KernelRefusal::unsupported(KernelStage::Classify, "runout_convexity", "the selection's convexity could not be read edge by edge"))?;
2688    let mut spine_ends = vec![0usize; selected_ids.len()];
2689    for corner in corners {
2690        if corner.convex.len() != 1 {
2691            return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_corner_shape", format!(
2692                "the corner at ({:.3}, {:.3}, {:.3}) has {} convex edges; the runout is built for one convex edge dying into concave ones",
2693                corner.point.x, corner.point.y, corner.point.z, corner.convex.len()
2694            )));
2695        }
2696        spine_ends[corner.convex[0]] += 1;
2697    }
2698    let mut spines: Vec<usize> = Vec::new();
2699    let mut concave: Vec<usize> = Vec::new();
2700    for (index, ends) in spine_ends.iter().enumerate() {
2701        match (*ends, convexity[index]) {
2702            (2, true) => spines.push(index),
2703            (1, true) => spines.push(index),
2704            (0, false) => concave.push(index),
2705            (ends, convex) => {
2706                return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_selection_shape", format!(
2707                    "{} is {} and meets a mixed corner at {ends} of its ends; the runout is built for a convex edge running out at both ends among concave edges",
2708                    selection_label(index, edge_points, edge_names, name),
2709                    if convex { "convex" } else { "concave" },
2710                )));
2711            }
2712        }
2713    }
2714    if concave.is_empty() {
2715        return Err(KernelRefusal::unsupported(KernelStage::Classify, "runout_selection_shape", "no concave edges to build the ring from"));
2716    }
2717    // Stage 1: the ring, exactly as the concave edges build on their own.
2718    let ring_points: Vec<Vec3> = concave.iter().map(|index| edge_points[*index]).collect();
2719    let ring_names: Option<Vec<String>> = edge_names.map(|names| concave.iter().map(|index| names[*index].clone()).collect());
2720    LAST_NETWORK_REFUSAL.with(|last| *last.borrow_mut() = None);
2721    let ring = fillet_edges_group_with_corner_policy(solid, &ring_points, ring_names.as_deref(), radius, false, name, None, false, true)
2722        .map_err(|error| {
2723            LAST_NETWORK_REFUSAL.with(|last| last.borrow_mut().take());
2724            error.with_message(|error| format!("the concave ring did not build: {error}"))
2725        })?;
2726    // Whether the ring is the NETWORK's ring (no network refusal recorded).
2727    let network_declined = LAST_NETWORK_REFUSAL.with(|last| last.borrow_mut().take());
2728    // BREP lane L: begin walls_missing_tie_all_stations_20261015
2729    let ring_is_network = network_declined.is_none();
2730    // BREP lane L: end walls_missing_tie_all_stations_20261015
2731    // Stage 2: the runout walls on it.
2732    let spine_walls: Vec<(u64, Option<String>)> = spines
2733        .iter()
2734        .map(|index| (selected_ids[*index], per_edge_name(edge_names, name, *index).map(str::to_string)))
2735        .collect();
2736    let spine_ids: Vec<u64> = spine_walls.iter().map(|(id, _)| *id).collect();
2737    let mut result = crate::blend::build_runout_walls(&ring, &spine_walls, radius)?;
2738    heal_edge_vertex_gaps(&mut result, radius)?;
2739    crate::blend::fit_planar_charts_to_trims(&ring, &mut result)?;
2740    let issues = result.validate();
2741    if !issues.is_empty() {
2742        return Err(KernelRefusal::new(
2743            RefusalClass::InvalidResultTopology { issues: issues.len() as u32 },
2744            KernelStage::Validate,
2745            format!("the runout walls do not validate: {issues:?}"),
2746        ));
2747    }
2748    check_blend_interference(&ring, &result, &spine_ids, entry)?;
2749    check_loop_self_crossings(&result, entry)?;
2750    check_blend_wall_loops(&result, entry)?;
2751    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
2752    let accepted = crate::accept_sound(result, entry)?;
2753    // BREP lane L: begin walls_missing_tie_all_stations_20261015
2754    RUNOUT_RING_IS_NETWORK.with(|flag| flag.set(ring_is_network));
2755    // BREP lane L: end walls_missing_tie_all_stations_20261015
2756    Ok(accepted)
2757}
2758
2759// BREP lane L: begin walls_missing_tie_all_stations_20261015
2760thread_local! {
2761    /// Set by a runout composition that SUCCEEDED on the network's ring (no
2762    /// network refusal recorded while its ring was built), and by a cusp
2763    /// composition that built (`cusp_composition`), read and cleared by the
2764    /// acceptance: only there does a tie take the majority.
2765    static RUNOUT_RING_IS_NETWORK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2766}
2767// BREP lane L: end walls_missing_tie_all_stations_20261015
2768
2769fn check_mixed_corner_convexity(
2770    solid: &BrepSolid,
2771    edge_ids: &[u64],
2772    edge_points: &[Vec3],
2773    edge_names: Option<&[String]>,
2774    radius: f64,
2775    name: Option<&str>,
2776    composition_error: Option<&KernelRefusal>,
2777) -> Result<(), KernelRefusal> {
2778    match crate::blend::mixed_convexity_corner(solid, edge_ids, radius) {
2779        Some(corner) => {
2780            // The refusal carries the RUNOUT's own numbers when they can be
2781            // measured — the station, the carrier pair, the stop and the pole
2782            // — so it says which construction is missing and where, not only
2783            // that the corner has none.  A measurement that fails leaves the
2784            // refusal exactly as it was: the corner is refused either way.
2785            let measured = match crate::blend::plan_runout(solid, edge_ids, radius, &corner) {
2786                Ok(plan) => Some(plan),
2787                Err(error) => {
2788                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
2789                        eprintln!("runout not measured: {error}");
2790                    }
2791                    None
2792                }
2793            };
2794            // "this kernel does not build that runout here": a named deferral,
2795            // carrying why the composition declined this selection.
2796            let mut message = mixed_corner_message(
2797                &corner,
2798                edge_points,
2799                edge_names,
2800                name,
2801                measured.as_ref(),
2802            );
2803            if let Some(error) = composition_error {
2804                message.push_str(&format!(" The runout composition was tried on this selection and refused: {error}"));
2805            }
2806            Err(KernelRefusal::unsupported(
2807                KernelStage::Classify,
2808                "mixed_corner_convexity",
2809                message,
2810            ))
2811        }
2812        None => Ok(()),
2813    }
2814}
2815
2816/// Refuse a selection one of whose edges keeps NO blend strip between the
2817/// corner balls at its two ends (see `degenerate_corner_setbacks`).
2818fn check_degenerate_corner_setbacks(
2819    solid: &BrepSolid,
2820    edge_ids: &[u64],
2821    edge_points: &[Vec3],
2822    edge_names: Option<&[String]>,
2823    radius: f64,
2824    name: Option<&str>,
2825) -> Result<(), KernelRefusal> {
2826    let Some(setback) = crate::blend::degenerate_corner_setbacks(solid, edge_ids, radius) else {
2827        return Ok(());
2828    };
2829    let [from, to] = setback.stops;
2830    let how = if setback.crossed {
2831        format!(
2832            "run {:.3e} PAST each other along it (the radius is beyond the limit)",
2833            setback.strip
2834        )
2835    } else {
2836        format!(
2837            "meet there ({:.3e} apart against a bar of {:.3e})",
2838            setback.strip, setback.bar
2839        )
2840    };
2841    // "The radius is at or past the degenerate limit … reduce it": a
2842    // parameter the geometry refuses, read at `Classify`.
2843    Err(KernelRefusal::input(
2844        KernelStage::Classify,
2845        "degenerate_corner_setbacks",
2846        format!(
2847            "fillet_edges: at r = {radius} the corner setbacks consume the whole of {} — the rolling \
2848             balls seated at its two corners touch face {} at ({:.4}, {:.4}, {:.4}) and ({:.4}, \
2849             {:.4}, {:.4}) and {how}, so no blend strip is left between them and the faces it lies \
2850             on are consumed whole. The radius is at or past the degenerate limit for this \
2851             selection; reduce it.",
2852            selection_label(setback.edge, edge_points, edge_names, name),
2853            setback.face_id,
2854            from.x,
2855            from.y,
2856            from.z,
2857            to.x,
2858            to.y,
2859            to.z,
2860        ),
2861    ))
2862}
2863
2864/// How a refusal names the `index`-th selected edge: its originating edge
2865/// name when the feature layer supplied one (with the feature's base prefix
2866/// stripped), else the picked point.
2867fn selection_label(
2868    index: usize,
2869    edge_points: &[Vec3],
2870    edge_names: Option<&[String]>,
2871    name: Option<&str>,
2872) -> String {
2873    let named = edge_names.and_then(|names| names.get(index)).map(|composed| match name {
2874        Some(base) => composed
2875            .strip_prefix(&format!("{base}:"))
2876            .unwrap_or(composed)
2877            .to_string(),
2878        None => composed.clone(),
2879    });
2880    named.unwrap_or_else(|| match edge_points.get(index) {
2881        Some(point) => format!("the edge at ({:.3}, {:.3}, {:.3})", point.x, point.y, point.z),
2882        None => format!("selection #{}", index + 1),
2883    })
2884}
2885
2886/// The refusal text for [`check_mixed_corner_convexity`], naming the edges the
2887/// way the user selected them (their originating edge names when the feature
2888/// layer supplied them, else the picked point).
2889fn mixed_corner_message(
2890    corner: &crate::blend::MixedCorner,
2891    edge_points: &[Vec3],
2892    edge_names: Option<&[String]>,
2893    name: Option<&str>,
2894    measured: Option<&crate::blend::RunoutPlan>,
2895) -> String {
2896    let label = |index: usize| selection_label(index, edge_points, edge_names, name);
2897    let list = |indices: &[usize]| -> String {
2898        let parts: Vec<String> = indices.iter().map(|index| label(*index)).collect();
2899        match parts.split_last() {
2900            None => "none".to_string(),
2901            Some((last, [])) => last.clone(),
2902            Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
2903        }
2904    };
2905    let mut message = format!(
2906        "fillet_edges: the selection mixes convexity at the corner ({:.3}, {:.3}, {:.3}) — convex \
2907         {} meets concave {} there. One rolling ball cannot touch the face they share from both \
2908         sides at once, so that corner has no closure: the convex blend runs out against the \
2909         concave ones partway along the edge, and this kernel does not build that runout yet. \
2910         Blending the concave edges in one fillet and the convex ones in another does not reach \
2911         a wall on every one of them either: the convex wall comes out at FULL length in either \
2912         order, and its contact leaves the faces it runs along where their own loops would then \
2913         cross. Blend the concave edges first and the blend acceptance refuses each convex edge \
2914         whose wall runs out into them; blend the convex ones first and the subset search drops \
2915         the concave edges it cannot compose instead, leaving those unfilleted.",
2916        corner.point.x,
2917        corner.point.y,
2918        corner.point.z,
2919        list(&corner.convex),
2920        list(&corner.concave),
2921    );
2922    // The runout, measured: where the ball's carriers switch, what they switch
2923    // to, and where the last stretch degenerates.  These are the numbers the
2924    // construction owes, so the refusal states them rather than leaving the
2925    // reader to derive them (`blend/runout.rs`).
2926    if let Some(plan) = measured {
2927        message.push_str(&format!(
2928            " Measured on this selection: the convex edge {}'s ball becomes tangent to face {} — \
2929             the face its two concave neighbours share — at s = {:.6} from the corner, centred \
2930             ({:.6}, {:.6}, {:.6}), where its contact on face {} reaches edge {}'s own rail \
2931             (ball-to-stripe residual {:.3e}). Past that station the second carrier is edge {}'s \
2932             STRIPE SURFACE, not a face of the input, and the march holds on it for {} \
2933             stations that fit rows reproducing their own contacts to {:.3e}. On the way the \
2934             kept mate's contact walks {:.3e} of a span off that face's own patch — into the \
2935             strip the concave stripe's pad ADDS to it — which is the shape, not an escape: \
2936             the bar a march is refused at is a full span.",
2937            plan.convex_edge,
2938            plan.shared_face,
2939            plan.station.s,
2940            plan.station.center.x,
2941            plan.station.center.y,
2942            plan.station.center.z,
2943            plan.replaced_mate,
2944            plan.second_carrier,
2945            plan.station.stripe_residual,
2946            plan.second_carrier,
2947            plan.marched,
2948            plan.fit_residual,
2949            plan.carrier_excursion,
2950        ));
2951        match (&plan.stop, plan.first_carrier) {
2952            (Some(stop), Some(first)) => message.push_str(&format!(
2953                " It does not simply stop there: at s = {:.6} the KEPT mate (face {}) runs out too \
2954                 — the ball's contact on it reaches edge {}'s rail, residual {:.3e} — so the FIRST \
2955                 carrier becomes that stripe as well and the last stretch rolls on two stripes.",
2956                stop.s, plan.kept_mate, first, stop.stripe_residual,
2957            )),
2958            _ => message.push_str(&format!(
2959                " Where the kept mate (face {}) runs out was not measurable on this selection.",
2960                plan.kept_mate
2961            )),
2962        }
2963        if let Some(pole) = plan.pole {
2964            message.push_str(&format!(
2965                " That stretch ends at a POLE, ({:.6}, {:.6}, {:.6}), where the two concave \
2966                 stripes' rails on face {} meet and the ball's two contacts merge, so the blend \
2967                 section shrinks to a point. Two carrier switches and a degenerate terminus is \
2968                 more than a stop station on a stripe, and none of it is composed yet.",
2969                pole.x, pole.y, pole.z, plan.shared_face,
2970            ));
2971        }
2972    }
2973    message
2974}
2975
2976/// All ways to choose `k` distinct indices from `0..n`, in lexicographic order.
2977fn index_combinations(n: usize, k: usize) -> Vec<Vec<usize>> {
2978    let mut out = Vec::new();
2979    if k == 0 || k > n {
2980        return out;
2981    }
2982    let mut idx: Vec<usize> = (0..k).collect();
2983    loop {
2984        out.push(idx.clone());
2985        // Advance to the next combination (like counting with carry).
2986        let mut i = k;
2987        loop {
2988            if i == 0 {
2989                return out;
2990            }
2991            i -= 1;
2992            if idx[i] != i + n - k {
2993                break;
2994            }
2995        }
2996        idx[i] += 1;
2997        for j in (i + 1)..k {
2998            idx[j] = idx[j - 1] + 1;
2999        }
3000    }
3001}
3002
3003thread_local! {
3004    /// Running count (per thread) of group builds that reached the CUTTER
3005    /// COMPOSITION — every network lane above it refused or was rejected.  A
3006    /// zero delta across a call is the witness that the network answered it;
3007    /// a face count or a volume cannot say which lane built a solid, since the
3008    /// cutter can build the same one.  Test-observable; not part of any result.
3009    pub static CUTTER_COMPOSITIONS: std::cell::Cell<u64> =
3010        const { std::cell::Cell::new(0) };
3011}
3012
3013thread_local! {
3014    /// The most edges the maximal-valid-subset search may drop on this
3015    /// thread; `None` searches every subset. Set by [`fillet_edges`] for its
3016    /// own call (lane F row 3, 2026-10-15): that entry refuses any partial
3017    /// selection, so the search there only words the refusal, and a search
3018    /// past one dropped edge cost lCount_125 117 s of booleans (112 subsets)
3019    /// to refuse what the drop-one level refuses in 11 s.
3020    static SUBSET_DROP_CAP: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
3021}
3022
3023/// Restores the previous [`SUBSET_DROP_CAP`] when the strict entry returns.
3024struct SubsetDropCap(Option<usize>);
3025
3026impl SubsetDropCap {
3027    fn set(cap: Option<usize>) -> Self {
3028        Self(SUBSET_DROP_CAP.with(|current| current.replace(cap)))
3029    }
3030}
3031
3032impl Drop for SubsetDropCap {
3033    fn drop(&mut self) {
3034        SUBSET_DROP_CAP.with(|current| current.set(self.0));
3035    }
3036}
3037
3038thread_local! {
3039    /// Running count (per thread) of [`fillet_edges_group_in`] builds, nested
3040    /// component builds included. Test-observable; not part of any result.
3041    pub static GROUP_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
3042    /// The network's last refusal in a group build on this thread, read
3043    /// back by the runout composition when its ring stage fails.
3044    static LAST_NETWORK_REFUSAL: std::cell::RefCell<Option<KernelRefusal>> = const { std::cell::RefCell::new(None) };
3045    /// The wall fold the network refused THIS group build's selection by,
3046    /// scoped to one [`fillet_edges_group_unchecked`] call (nested component
3047    /// builds save and restore it).
3048    static GROUP_NETWORK_FOLD: std::cell::RefCell<Option<KernelRefusal>> = const { std::cell::RefCell::new(None) };
3049}
3050
3051/// One component of a selection: its edge points (as bits, so the key is
3052/// exact) and its per-edge wall names.
3053type ComponentKey = (Vec<[u64; 3]>, Option<Vec<String>>);
3054
3055/// One step of the cutter composition's sequential build: the edge's
3056/// selection point (as bits), its wall name, the cutter's end pads (as bits)
3057/// and the composition lane (0 = general first, 1 = cutter first). The pads
3058/// and the lane are part of the key because both are read off the WHOLE
3059/// selection (its corners), so the same edge can take a different cutter in
3060/// a subset that drops a corner's third edge.
3061type SequentialKey = ([u64; 3], Option<String>, [u64; 2], u8);
3062
3063/// Component results of one [`fillet_edges_reported`] call, keyed by the chain
3064/// of components composed up to and including the one built. Valid only for
3065/// the solid, radius, chamfer flag and name of that call.
3066///
3067/// `sequential` is the same memo one level down, for a single connected
3068/// component: the evolving body of the cutter composition after each edge
3069/// blended, keyed by the chain of steps composed up to and including it. The
3070/// subset search's one-drop subsets of a connected selection mostly open
3071/// with the same edges in the same order, so without it every such subset
3072/// rebuilt the same cutter booleans before reaching the edge that refuses.
3073/// On the 2026-10-17 "fillet takes way too long" report (a 7-edge face ring
3074/// whose second edge refuses after the first edge's 6-8 s cutter boolean)
3075/// that boolean ran six times for one refusal: for the group and for the
3076/// five subsets that keep the first edge.
3077///
3078/// A one-drop subset of a connected ring can split it into two components
3079/// (the ring minus an edge that is not an end of a path), and the component
3080/// chains then differ from subset to subset while the cutter composition's
3081/// first steps do not; so the sequential memo is keyed by the chain of
3082/// components composed BEFORE the body being built (`prefix`, empty for a
3083/// single-component selection) together with the steps, and the component
3084/// builds carry the memo down instead of `None`. A FIRST component's steps
3085/// key under the empty prefix like a single-component selection's, which
3086/// is sound because both start from the same body: the component build
3087/// re-heals the selection's already healed input, and `heal_operands`
3088/// leaves a clean input byte-identical (its contract, stated at the heal
3089/// above; the cross-partition hits on the reported ring are its evidence).
3090#[derive(Default)]
3091struct ComponentMemo {
3092    built: std::collections::HashMap<Vec<ComponentKey>, Result<BrepSolid, KernelRefusal>>,
3093    /// The components composed before the build in progress, from the
3094    /// outermost selection down (set around each component build).
3095    prefix: Vec<ComponentKey>,
3096    sequential: std::collections::HashMap<
3097        (Vec<ComponentKey>, Vec<SequentialKey>),
3098        Result<BrepSolid, KernelRefusal>,
3099    >,
3100}
3101
3102/// [`fillet_edges_group_in`], with the subset search's component memo when
3103/// `memo` is `Some`. The search passes it on its own solid, and the component
3104/// builds pass it on down with `ComponentMemo::prefix` naming the components
3105/// composed before them (see `ComponentMemo::sequential`).
3106fn fillet_edges_group_in(
3107    solid: &BrepSolid,
3108    edge_points: &[Vec3],
3109    edge_names: Option<&[String]>,
3110    radius: f64,
3111    chamfer: bool,
3112    name: Option<&str>,
3113    memo: Option<&mut ComponentMemo>,
3114) -> Result<BrepSolid, KernelRefusal> {
3115    fillet_edges_group_with_corner_policy(solid, edge_points, edge_names, radius, chamfer, name, memo, true, true)
3116}
3117
3118fn fillet_edges_group_with_corner_policy(
3119    solid: &BrepSolid,
3120    edge_points: &[Vec3],
3121    edge_names: Option<&[String]>,
3122    radius: f64,
3123    chamfer: bool,
3124    name: Option<&str>,
3125    memo: Option<&mut ComponentMemo>,
3126    wrap_concave: bool,
3127    accept: bool,
3128) -> Result<BrepSolid, KernelRefusal> {
3129    GROUP_BUILDS.with(|count| count.set(count.get() + 1));
3130    let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3131    let GroupBody { body: result, bowtie_clean } =
3132        fillet_edges_group_unchecked(solid, edge_points, edge_names, radius, chamfer, name, memo, wrap_concave)?;
3133    if !accept {
3134        return Ok(result);
3135    }
3136    // A body the network or the closed-rim lane already scanned clean and
3137    // handed up untouched is not scanned again (the scan is a pure function
3138    // of the body, 2026-10-12). The composite road and the cutter road hand
3139    // up bodies no lane scanned, and are scanned here.
3140    if bowtie_clean {
3141        crate::blend::record_count("count.bowtie.lane_scan_reused", 1);
3142    } else {
3143        check_loop_self_crossings(&result, entry)?;
3144        check_blend_wall_loops(&result, entry)?;
3145    }
3146    let soundness = crate::blend::BlendTimer::start("timing.soundness_ms");
3147    // The BODY's own soundness, beside the loop's. A blend wall is a FITTED
3148    // surface and a fit can carry two parameters of one wall to one point in
3149    // space — measured on `inbox-20260902-fillet-two-torus-box-edges`, whose
3150    // wall `F8:BLEND:Box_NZ|P.T5_Side[0]` does exactly that while `validate()`,
3151    // connectivity, Euler parity, the loop scan and the face-versus-face scan
3152    // are all silent. Two walls crossing each other is the same class and is
3153    // repaired where it can be. Neither is visible to a volume oracle, so a
3154    // result carrying one reports success for a different shape.
3155    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
3156    let accepted = crate::accept_sound(result, entry);
3157    soundness.stop();
3158    accepted
3159}
3160
3161/// What the unchecked group lane hands up: the body, and whether a lane's
3162/// own acceptance already ran the bowtie scan on exactly this body and
3163/// found it clean (the network and closed-rim exits return the scanned
3164/// body unchanged; the composite and cutter exits do not scan).
3165struct GroupBody {
3166    body: BrepSolid,
3167    bowtie_clean: bool,
3168}
3169
3170/// [`fillet_edges_group_lanes`], answering a selection the network refused
3171/// by a WALL FOLD and the cutter composition then failed too by that fold,
3172/// not by the composition's own text: the fold is the reason, and the
3173/// composition's last cutter ("mates share their end boundary edge" on the
3174/// 2026-10-21 sculpted cap, report 5e49bb42) names nothing the user can act
3175/// on. The fold keeps its class, so the subset search above stops on it.
3176fn fillet_edges_group_unchecked(
3177    solid: &BrepSolid,
3178    edge_points: &[Vec3],
3179    edge_names: Option<&[String]>,
3180    radius: f64,
3181    chamfer: bool,
3182    name: Option<&str>,
3183    memo: Option<&mut ComponentMemo>,
3184    wrap_concave: bool,
3185) -> Result<GroupBody, KernelRefusal> {
3186    let outer = GROUP_NETWORK_FOLD.with(|fold| fold.borrow_mut().take());
3187    let built = fillet_edges_group_lanes(solid, edge_points, edge_names, radius, chamfer, name, memo, wrap_concave);
3188    let fold = GROUP_NETWORK_FOLD.with(|fold| std::mem::replace(&mut *fold.borrow_mut(), outer));
3189    match (built, fold) {
3190        (Err(error), Some(fold)) if !crate::blend::is_wall_fold(&error) => Err(fold),
3191        (built, _) => built,
3192    }
3193}
3194
3195/// `BREP_FILLET_CONCAVE_FIRST_STAGES` (default on; `=0` restores the cutter
3196/// composition): a selection the network refuses for MIXED CONVEXITY whose
3197/// concave edges also meet each other at a corner no selected convex edge
3198/// reaches is built in two network stages, concave edges first.
3199///
3200/// Cause: a boss standing across a block's top edge, filleted along its base
3201/// (two vertical concave edges on the block's side, the concave arc on its
3202/// top) together with the boss's bottom face. The bottom corners are
3203/// re-entrant stars (one concave, two convex edges), which the network
3204/// refuses by convexity, so the WHOLE selection went to the sequential
3205/// cutter build; that build runs each concave cutter past the block's sharp
3206/// top edge and closes it with folded flat caps (a crease of 180 degrees)
3207/// instead of the miter the network builds where the two concave pads meet
3208/// over that edge.
3209/// The stage name a concave pad carries between the two stages of
3210/// [`concave_first_stages`], followed by its selection index.
3211const CONCAVE_FIRST_PAD: &str = "FILLET:CONCAVE_FIRST:";
3212
3213fn concave_first_stages_on() -> bool {
3214    switch!("BREP_FILLET_CONCAVE_FIRST_STAGES", true)
3215}
3216
3217/// One network stage of [`concave_first_stages`], under the acceptance the
3218/// group's own network result gets (heal, planar charts, validation,
3219/// interference, loop scans). `None` when the network refuses or the result
3220/// fails any check.
3221fn concave_first_network_stage(
3222    input: &BrepSolid,
3223    edge_ids: &[u64],
3224    network_names: &[Option<String>],
3225    corner_name: &dyn Fn(&[usize]) -> Option<String>,
3226    radius: f64,
3227    wrap_concave: bool,
3228) -> Option<BrepSolid> {
3229    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
3230    let mut body = match crate::blend::blend_star_network_with_corner_policy(
3231        input, edge_ids, radius, false, network_names, corner_name, wrap_concave,
3232    ) {
3233        Ok(body) => body,
3234        Err(refusal) => {
3235            if debug {
3236                eprintln!("concave-first stage on {edge_ids:?} refused: {refusal}");
3237            }
3238            return None;
3239        }
3240    };
3241    let entry = "fillet_edges";
3242    let healed = heal_edge_vertex_gaps(&mut body, radius);
3243    let charts = crate::blend::fit_planar_charts_to_trims(input, &mut body);
3244    let issues = body.validate_memoised();
3245    let interference = check_blend_interference(input, &body, edge_ids, entry);
3246    let bowtie = check_loop_self_crossings(&body, entry).and_then(|()| check_blend_wall_loops(&body, entry));
3247    if healed.is_ok() && charts.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
3248        return Some(body);
3249    }
3250    crate::blend::reject_wrapped_network();
3251    if debug {
3252        eprintln!(
3253            "concave-first stage on {edge_ids:?} rejected: heal={healed:?} charts={charts:?} issues={issues:?} \
3254             interference={interference:?} bowtie={bowtie:?}"
3255        );
3256    }
3257    None
3258}
3259
3260/// The two-stage build [`concave_first_stages_on`] describes: the concave
3261/// edges through the network on the input, then the convex edges through the
3262/// network on that body. Where a concave pad now separates two selected
3263/// convex edges that met it at a re-entrant star, the pad's own edge on their
3264/// shared face joins the second stage, so the star closes as one rounded run
3265/// (named as the star's corner) rather than with flat caps. `None` when the
3266/// selection is not of this shape or either stage fails: the caller's ladder
3267/// then goes on unchanged.
3268#[allow(clippy::too_many_arguments)]
3269fn concave_first_stages(
3270    solid: &BrepSolid,
3271    edge_points: &[Vec3],
3272    edge_names: Option<&[String]>,
3273    selected_edge_ids: &[u64],
3274    radius: f64,
3275    name: Option<&str>,
3276    wrap_concave: bool,
3277) -> Option<BrepSolid> {
3278    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
3279    let convex = crate::blend::selection_convexity(solid, selected_edge_ids, radius)?;
3280    let concave_indices: Vec<usize> = (0..convex.len()).filter(|&index| !convex[index]).collect();
3281    let convex_indices: Vec<usize> = (0..convex.len()).filter(|&index| convex[index]).collect();
3282    if concave_indices.is_empty() || convex_indices.is_empty() {
3283        return None;
3284    }
3285    let edge = |id: u64| solid.edges.iter().find(|edge| edge.id == id);
3286    let ends = |id: u64| edge(id).map(|edge| [edge.start_vertex_id, edge.end_vertex_id]);
3287    // The shape this answers: two concave edges meeting where no selected
3288    // convex edge ends (the miter the cutter build caps).
3289    let concave_corner = concave_indices.iter().enumerate().any(|(slot, &a)| {
3290        concave_indices[slot + 1..].iter().any(|&b| {
3291            let (Some(ends_a), Some(ends_b)) = (ends(selected_edge_ids[a]), ends(selected_edge_ids[b])) else {
3292                return false;
3293            };
3294            ends_a.iter().any(|vertex| {
3295                ends_b.contains(vertex)
3296                    && !convex_indices.iter().any(|&c| ends(selected_edge_ids[c]).is_some_and(|ends_c| ends_c.contains(vertex)))
3297            })
3298        })
3299    });
3300    if !concave_corner {
3301        return None;
3302    }
3303    let names_of = |indices: &[usize]| -> Vec<Option<String>> {
3304        indices.iter().map(|&index| per_edge_name(edge_names, name, index).map(str::to_string)).collect()
3305    };
3306    // Stage 1: the concave edges on the input. Each pad carries a stage name
3307    // of its own until the end, so finding a pad below never depends on the
3308    // names the caller supplied (or did not).
3309    let concave_ids: Vec<u64> = concave_indices.iter().map(|&index| selected_edge_ids[index]).collect();
3310    let stage_name = |index: usize| format!("{CONCAVE_FIRST_PAD}{index}");
3311    let concave_names: Vec<Option<String>> = concave_indices.iter().map(|&index| Some(stage_name(index))).collect();
3312    let concave_corner_name = |adjacent: &[usize]| {
3313        let members: Vec<usize> = adjacent.iter().map(|&slot| concave_indices[slot]).collect();
3314        corner_face_name(edge_names, name, &members)
3315    };
3316    let staged = concave_first_network_stage(solid, &concave_ids, &concave_names, &concave_corner_name, radius, wrap_concave)?;
3317    let original_faces: rustc_hash::FxHashSet<u64> =
3318        solid.shells.iter().flat_map(|shell| &shell.faces).map(|face| face.id).collect();
3319    let faces_of = |id: u64| -> Vec<&FaceRecord> {
3320        staged
3321            .shells
3322            .iter()
3323            .flat_map(|shell| &shell.faces)
3324            .filter(|face| face.loops.iter().flat_map(|rim| &rim.coedges).any(|coedge| coedge.edge_id == id))
3325            .collect()
3326    };
3327    // Stage 2: the convex edges, resolved on the staged body by their pick
3328    // points (a concave pad trims a convex edge at its end, never at the
3329    // point it was picked by).
3330    let mut stage_ids: Vec<u64> = Vec::with_capacity(convex_indices.len() + 2);
3331    let mut members: Vec<Vec<usize>> = Vec::with_capacity(convex_indices.len() + 2);
3332    for &index in &convex_indices {
3333        let id = resolve_edge_by_point(&staged, edge_points[index]).ok()?;
3334        // A pick that now lands on a pad (one made inside the stretch the pad
3335        // trimmed away) is not the convex edge it named.
3336        if stage_ids.contains(&id) || faces_of(id).iter().any(|face| !original_faces.contains(&face.id)) {
3337            return None;
3338        }
3339        stage_ids.push(id);
3340        members.push(vec![index]);
3341    }
3342    let staged_edge = |id: u64| staged.edges.iter().find(|edge| edge.id == id);
3343    let convex_count = stage_ids.len();
3344    for pad in &staged.edges {
3345        if pad.degenerate || stage_ids.contains(&pad.id) || pad.start_vertex_id == pad.end_vertex_id {
3346            continue;
3347        }
3348        let faces = faces_of(pad.id);
3349        if faces.len() != 2 {
3350            continue;
3351        }
3352        // One side is a stage-1 pad, named after the concave edge it rounds.
3353        let Some(concave_index) = faces.iter().find(|face| !original_faces.contains(&face.id)).and_then(|face| {
3354            concave_indices.iter().copied().find(|&index| face.name.as_deref() == Some(stage_name(index).as_str()))
3355        }) else {
3356            continue;
3357        };
3358        // Its two ends are ends of two DIFFERENT selected convex edges.
3359        let ender = |vertex: u64| {
3360            (0..convex_count).find(|&slot| {
3361                staged_edge(stage_ids[slot]).is_some_and(|edge| edge.start_vertex_id == vertex || edge.end_vertex_id == vertex)
3362            })
3363        };
3364        let (Some(first), Some(second)) = (ender(pad.start_vertex_id), ender(pad.end_vertex_id)) else {
3365            continue;
3366        };
3367        if first == second {
3368            continue;
3369        }
3370        // And the other side is a face both of those convex edges run along.
3371        let Some(other) = faces.iter().find(|face| original_faces.contains(&face.id)) else {
3372            continue;
3373        };
3374        let borders = |slot: usize| faces_of(stage_ids[slot]).iter().any(|face| face.id == other.id);
3375        if !borders(first) || !borders(second) {
3376            continue;
3377        }
3378        match super::analyze::scan_dihedral(&staged, pad.id) {
3379            Ok(profile) if profile.samples > 0 && profile.any_convex && !profile.any_concave => {}
3380            _ => continue,
3381        }
3382        let mut star = vec![concave_index, convex_indices[first], convex_indices[second]];
3383        star.sort_unstable();
3384        stage_ids.push(pad.id);
3385        members.push(star);
3386    }
3387    let mut stage_names = names_of(&convex_indices);
3388    stage_names.extend(members[convex_count..].iter().map(|star| corner_face_name(edge_names, name, star)));
3389    let stage_corner_name = |adjacent: &[usize]| {
3390        let mut flat: Vec<usize> = adjacent.iter().flat_map(|&slot| members[slot].iter().copied()).collect();
3391        flat.sort_unstable();
3392        flat.dedup();
3393        corner_face_name(edge_names, name, &flat)
3394    };
3395    let mut built = concave_first_network_stage(&staged, &stage_ids, &stage_names, &stage_corner_name, radius, wrap_concave)?;
3396    for face in built.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
3397        // The stage name, and anything a stage appended to it, back to the
3398        // pad's own name.
3399        let Some(tail) = face.name.as_deref().and_then(|value| value.strip_prefix(CONCAVE_FIRST_PAD)) else {
3400            continue;
3401        };
3402        let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
3403        let Ok(index) = tail[..digits].parse::<usize>() else {
3404            return None;
3405        };
3406        let rest = tail[digits..].to_string();
3407        face.name = per_edge_name(edge_names, name, index).map(|own| format!("{own}{rest}"));
3408    }
3409    if debug {
3410        eprintln!(
3411            "concave-first stages: {} concave, {} convex and {} star pad edge(s) built",
3412            concave_ids.len(),
3413            convex_count,
3414            stage_ids.len() - convex_count
3415        );
3416    }
3417    Some(built)
3418}
3419
3420fn fillet_edges_group_lanes(
3421    solid: &BrepSolid,
3422    edge_points: &[Vec3],
3423    edge_names: Option<&[String]>,
3424    radius: f64,
3425    chamfer: bool,
3426    name: Option<&str>,
3427    mut memo: Option<&mut ComponentMemo>,
3428    wrap_concave: bool,
3429) -> Result<GroupBody, KernelRefusal> {
3430    use rustc_hash::FxHashSet as HashSet;
3431
3432    // Fuse-first operand heal (Lever A) before the multi-edge surgery: snap the
3433    // input's near-coincident / off-plane vertices (e.g. a revolve pole apex
3434    // sitting a few microns off the axis) to exact and re-anchor incident
3435    // edges.  The selected edges are resolved geometrically below, so a
3436    // sub-heal_tol vertex move never changes which edges are picked; a clean
3437    // input is left byte-identical.
3438    let heal = crate::blend::BlendTimer::start("timing.heal_operands_ms");
3439    let mut healed_input = solid.clone();
3440    let heal_policy = crate::KernelTolerances::for_solid(&healed_input, 1e-7);
3441    crate::heal::heal_operands(&mut healed_input, &heal_policy)?;
3442    let solid = &healed_input;
3443    heal.stop();
3444    let group_analysis = crate::blend::BlendTimer::start("timing.group_analysis_ms");
3445
3446    // 1. Detect convex corners from the ORIGINAL solid: a point that is an
3447    //    endpoint of >=3 of the selected edges (a cube/prism-style vertex).
3448    let mut endpoints: Vec<(Vec3, usize)> = Vec::with_capacity(edge_points.len() * 2);
3449    // The extent each selected edge has BEFORE any blend trims it, so the
3450    // sequential build can run every cutter through the shared corners.
3451    let mut original_extents: Vec<(Vec3, Vec3)> = Vec::with_capacity(edge_points.len());
3452    let mut selected_edge_ids: Vec<u64> = Vec::with_capacity(edge_points.len());
3453    for (i, point) in edge_points.iter().enumerate() {
3454        let edge_id = resolve_edge_by_point(solid, *point)?;
3455        let edge = solid
3456            .edges
3457            .iter()
3458            .find(|e| e.id == edge_id)
3459            .ok_or_else(|| {
3460                KernelRefusal::internal(
3461                    KernelStage::Collect,
3462                    "resolved_edge",
3463                    "fillet_edges: resolved edge vanished",
3464                )
3465            })?;
3466        let (start, end) = (
3467            edge.curve
3468                .evaluate(edge.t0)
3469                .or_refuse(KernelStage::Collect, "edge_start")?,
3470            edge.curve
3471                .evaluate(edge.t1)
3472                .or_refuse(KernelStage::Collect, "edge_end")?,
3473        );
3474        endpoints.push((start, i));
3475        endpoints.push((end, i));
3476        original_extents.push((start, end));
3477        selected_edge_ids.push(edge_id);
3478    }
3479    let mut corners: Vec<Vec3> = Vec::new();
3480    // The selected-edge INPUT INDICES meeting at each star corner (parallel to
3481    // `corners`), sorted — used to name the corner patch after its adjacent
3482    // edges (`{fid}:BLEND:CORNER:{e_a}+{e_b}+…`), UNIQUE per corner because no
3483    // two distinct corners share the same set of >=3 selected edges.
3484    let mut corner_edges: Vec<Vec<usize>> = Vec::new();
3485    let mut chain_corner_count = 0usize;
3486    let mut chain_corners: Vec<(Vec3, [usize; 2])> = Vec::new();
3487    let mut used = vec![false; endpoints.len()];
3488    for i in 0..endpoints.len() {
3489        if used[i] {
3490            continue;
3491        }
3492        used[i] = true;
3493        let mut edges_here: HashSet<usize> = HashSet::default();
3494        edges_here.insert(endpoints[i].1);
3495        for j in (i + 1)..endpoints.len() {
3496            if used[j] {
3497                continue;
3498            }
3499            if endpoints[i].0.sub(endpoints[j].0).length() < 1e-6 {
3500                used[j] = true;
3501                edges_here.insert(endpoints[j].1);
3502            }
3503        }
3504        if edges_here.len() >= 3 {
3505            corners.push(endpoints[i].0);
3506            let mut adjacent: Vec<usize> = edges_here.into_iter().collect();
3507            adjacent.sort_unstable();
3508            corner_edges.push(adjacent);
3509        } else if edges_here.len() == 2 {
3510            chain_corner_count += 1;
3511            let mut adjacent = edges_here.into_iter().collect::<Vec<_>>();
3512            adjacent.sort_unstable();
3513            chain_corners.push((endpoints[i].0, [adjacent[0], adjacent[1]]));
3514        }
3515    }
3516
3517    // A FACE selection may contain several disconnected boundary components
3518    // (the common example is an outer perimeter plus a circular hole rim).
3519    // Miter composition is only meaningful inside one connected edge graph.
3520    // Feeding every component into the same INTERSECT/UNION combines multiple
3521    // independently filleted copies of otherwise untouched support faces; the
3522    // boolean then imprints those coincident copies and can leave redundant
3523    // seams (the reported through-hole cylinder split into three faces).
3524    //
3525    // Partition by shared original endpoints and process components in input
3526    // order.  Each recursive call sees one connected component, so it follows
3527    // the existing miter/sequential path without recursion cycling.  Distinct
3528    // components are then composed sequentially on the evolving solid.
3529    let mut component_of = vec![usize::MAX; edge_points.len()];
3530    let mut components: Vec<Vec<usize>> = Vec::new();
3531    for seed in 0..edge_points.len() {
3532        if component_of[seed] != usize::MAX {
3533            continue;
3534        }
3535        let component_index = components.len();
3536        component_of[seed] = component_index;
3537        let mut component = vec![seed];
3538        let mut cursor = 0;
3539        while cursor < component.len() {
3540            let current = component[cursor];
3541            cursor += 1;
3542            for candidate in 0..edge_points.len() {
3543                if component_of[candidate] != usize::MAX {
3544                    continue;
3545                }
3546                let connected = [original_extents[current].0, original_extents[current].1]
3547                    .into_iter()
3548                    .any(|a| {
3549                        [original_extents[candidate].0, original_extents[candidate].1]
3550                            .into_iter()
3551                            .any(|b| a.sub(b).length() < 1e-6)
3552                    });
3553                if connected {
3554                    component_of[candidate] = component_index;
3555                    component.push(candidate);
3556                }
3557            }
3558        }
3559        component.sort_unstable();
3560        components.push(component);
3561    }
3562    group_analysis.stop();
3563    if components.len() > 1 {
3564        let mut separated = solid.clone();
3565        // The chain continues the memo's prefix, so a component composed
3566        // inside another's build keys under the whole path to it.
3567        let mut chain: Vec<ComponentKey> = memo.as_deref().map(|memo| memo.prefix.clone()).unwrap_or_default();
3568        chain.reserve(components.len());
3569        for component in components {
3570            let points = component
3571                .iter()
3572                .map(|index| edge_points[*index])
3573                .collect::<Vec<_>>();
3574            let names = edge_names.map(|all| {
3575                component
3576                    .iter()
3577                    .map(|index| all[*index].clone())
3578                    .collect::<Vec<_>>()
3579            });
3580            let Some(memo) = memo.as_deref_mut() else {
3581                separated = fillet_edges_group_with_corner_policy(
3582                    &separated,
3583                    &points,
3584                    names.as_deref(),
3585                    radius,
3586                    chamfer,
3587                    name,
3588                    None,
3589                    wrap_concave,
3590                    false,
3591                )?;
3592                continue;
3593            };
3594            let bits = points.iter().map(|p| [p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]);
3595            chain.push((bits.collect(), names.clone()));
3596            let built = match memo.built.get(&chain) {
3597                Some(built) => built.clone(),
3598                None => {
3599                    // The component builds on the body the chain before it
3600                    // composed: its own cutter steps key under that chain.
3601                    let outer_prefix = std::mem::replace(&mut memo.prefix, chain[..chain.len() - 1].to_vec());
3602                    let built = fillet_edges_group_with_corner_policy(
3603                        &separated,
3604                        &points,
3605                        names.as_deref(),
3606                        radius,
3607                        chamfer,
3608                        name,
3609                        Some(&mut *memo),
3610                        wrap_concave,
3611                        false,
3612                    );
3613                    memo.prefix = outer_prefix;
3614                    memo.built.insert(chain.clone(), built.clone());
3615                    built
3616                }
3617            };
3618            separated = built?;
3619        }
3620        return Ok(GroupBody { body: separated, bowtie_clean: false });
3621    }
3622
3623    // 2a. The stripe network (blend/network.rs) is the lane for EVERY
3624    //     selection: each stripe is marched against THIS solid, each shared
3625    //     vertex is solved before anything is cut — a star closed by a patch
3626    //     of the corner ball, a two-edge corner by the seam between the two
3627    //     blends, a re-entrant corner by a horn torus, a tangent pair by a
3628    //     flush join, an unselected tangent continuation by a cap — and
3629    //     nothing is subtracted, so no cutter can overshoot into a neighbour
3630    //     and no leftover cap has to be identified afterwards.  It refuses
3631    //     BY NAME on what it does not yet construct (mixed-convexity corners,
3632    //     no-common-ball stars, pinched edges), and those fall through to the
3633    //     cutter composition below.
3634    //
3635    //     A CLOSED edge is one of those refusals and it has an answer the
3636    //     network is simply not the lane for: a closed rim has no corner to
3637    //     share, so `blend_star_network` says "edge N is closed and has no
3638    //     corner to share" and the composition took it.  `blend_closed_edge`
3639    //     builds exactly that case and the single-edge ladder in `tool.rs`
3640    //     has always tried it first — but this function reached only the
3641    //     network, so a closed rim inside a GROUP went to a cutter that the
3642    //     same rim selected on its own never saw.  A bored hole's rim splits
3643    //     out as its own one-edge component (see the component partition
3644    //     above), so that was every hole rim chamfered as part of a face
3645    //     selection.  Try it here too, under the same acceptance the network
3646    //     result gets, and under the same `BREP_NO_NETWORK` A/B.
3647    if std::env::var("BREP_NO_NETWORK").is_err() {
3648        if selected_edge_ids.len() == 1 {
3649            let edge_id = selected_edge_ids[0];
3650            let closed = solid
3651                .edges
3652                .iter()
3653                .find(|edge| edge.id == edge_id)
3654                .is_some_and(|edge| edge.start_vertex_id == edge.end_vertex_id);
3655            if closed {
3656                let rim_name = per_edge_name(edge_names, name, 0);
3657                match crate::blend::blend_closed_edge(solid, edge_id, radius, chamfer, rim_name) {
3658                    Ok(mut rim) => {
3659                        let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3660                        let heal = crate::blend::BlendTimer::start("timing.heal_vertex_gaps_ms");
3661                        let healed = heal_edge_vertex_gaps(&mut rim, radius);
3662                        heal.stop();
3663                        // A trim the surgery ran outside its planar carrier's
3664                        // chart is a wrong body the three checks below all pass
3665                        // (`crate::blend::fit_planar_charts_to_trims`), so the
3666                        // carrier is widened here, after the heal has settled
3667                        // the edges the trims are rebuilt from and before the
3668                        // bowtie scan reads them.  Its refusals are TERMINAL:
3669                        // the composition is not a second opinion on a body
3670                        // whose trims left their carrier.
3671                        let charts = crate::blend::BlendTimer::start("timing.planar_charts_ms");
3672                        crate::blend::fit_planar_charts_to_trims(solid, &mut rim)?;
3673                        charts.stop();
3674                        let validate = crate::blend::BlendTimer::start("timing.validate_ms");
3675                        let issues = rim.validate_memoised();
3676                        validate.stop();
3677                        let interference =
3678                            check_blend_interference(solid, &rim, &selected_edge_ids, entry);
3679                        let bowtie = check_loop_self_crossings(&rim, entry).and_then(|()| check_blend_wall_loops(&rim, entry));
3680                        if healed.is_ok()
3681                            && issues.is_empty()
3682                            && interference.is_ok()
3683                            && bowtie.is_ok()
3684                        {
3685                            return Ok(GroupBody { body: rim, bowtie_clean: true });
3686                        }
3687                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3688                            eprintln!(
3689                                "closed-rim result rejected: heal={healed:?} issues={issues:?} \
3690                                 interference={interference:?} bowtie={bowtie:?}"
3691                            );
3692                        }
3693                    }
3694                    Err(refusal) => {
3695                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3696                            eprintln!("closed-rim refused: {refusal}");
3697                        }
3698                    }
3699                }
3700            }
3701        }
3702        let network_names: Vec<Option<String>> = (0..edge_points.len())
3703            .map(|index| per_edge_name(edge_names, name, index).map(str::to_string))
3704            .collect();
3705        let network_corner_name =
3706            |adjacent: &[usize]| corner_face_name(edge_names, name, adjacent);
3707        // BREP lane L: begin lcount229_knot_aware_group_network_20261016 A
3708        // support pcurve off the floor ends the group's network here, and
3709        // the ladder would go on to the cutter composition: re-run the
3710        // network ONCE with the knot-aware support fit; a re-run that also
3711        // fails keeps the first refusal.
3712        let group_network = || {
3713            crate::blend::blend_star_network_with_corner_policy(
3714                solid,
3715                &selected_edge_ids,
3716                radius,
3717                chamfer,
3718                &network_names,
3719                &network_corner_name,
3720                wrap_concave,
3721            )
3722        };
3723        let network_result = group_network().or_else(|first| {
3724            if crate::blend::is_pcurve_floor_refusal(&first) {
3725                crate::blend::with_pcurve_knot_retry(group_network).map_err(|_| first)
3726            } else {
3727                Err(first)
3728            }
3729        });
3730        // BREP lane L: end lcount229_knot_aware_group_network_20261016
3731        // The network's result under its acceptance: `Ok(Some)` accepted,
3732        // `Ok(None)` rejected (the ladder goes on), `Err` terminal.
3733        let accept_network = |mut network: BrepSolid, built_radius: f64| -> Result<Option<GroupBody>, KernelRefusal> {
3734                // Fail-safe like the rest of the ladder: a heal or validation
3735                // problem in the network result falls through to the cutter,
3736                // it does not fail the group.  So does an UNTRIMMED result: the
3737                // network re-trims only each stripe's two mates, and
3738                // `check_blend_interference` is what notices a third face
3739                // crossing the swept volume -- `validate` cannot, because a
3740                // self-intersecting solid is still a watertight one.
3741                let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
3742                let heal = crate::blend::BlendTimer::start("timing.heal_vertex_gaps_ms");
3743                let healed = heal_edge_vertex_gaps(&mut network, built_radius);
3744                heal.stop();
3745                // See the closed-rim lane above: widen a planar carrier the
3746                // surgery overran, or refuse — terminally — rather than fall
3747                // through to a composition that cannot answer that question.
3748                let charts = crate::blend::BlendTimer::start("timing.planar_charts_ms");
3749                crate::blend::fit_planar_charts_to_trims(solid, &mut network)?;
3750                charts.stop();
3751                let validate = crate::blend::BlendTimer::start("timing.validate_ms");
3752                let issues = network.validate_memoised();
3753                validate.stop();
3754                let interference =
3755                    check_blend_interference(solid, &network, &selected_edge_ids, entry);
3756                // And the fourth question, which the other three all pass: does
3757                // any face of the result have a loop that crosses ITSELF? A
3758                // wall whose rail ran off its own face comes back as a bowtie,
3759                // and a bowtie is watertight, incident and connected.
3760                let bowtie = check_loop_self_crossings(&network, entry).and_then(|()| check_blend_wall_loops(&network, entry));
3761                if healed.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
3762                    return Ok(Some(GroupBody { body: network, bowtie_clean: true }));
3763                }
3764                crate::blend::reject_wrapped_network();
3765                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3766                    eprintln!(
3767                        "network result rejected: heal={healed:?} issues={issues:?} \
3768                         interference={interference:?} bowtie={bowtie:?}"
3769                    );
3770                    dump_loops_debug("INPUT", solid);
3771                    dump_loops_debug("RESULT", &network);
3772                }
3773                Ok(None)
3774        };
3775        match network_result {
3776            Ok(network) => {
3777                if let Some(body) = accept_network(network, radius)? {
3778                    return Ok(body);
3779                }
3780            }
3781            Err(refusal) => {
3782                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3783                    eprintln!("network refused: {refusal}");
3784                }
3785                // A mixed-convexity refusal over a selection whose concave
3786                // edges also miter each other: build them first, then the
3787                // convex edges (`concave_first_stages_on`).
3788                let mixed = matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what } if what == "mixed_convexity");
3789                if !chamfer && mixed && concave_first_stages_on() {
3790                    if let Some(body) = concave_first_stages(
3791                        solid, edge_points, edge_names, &selected_edge_ids, radius, name, wrap_concave,
3792                    ) {
3793                        return Ok(GroupBody { body, bowtie_clean: true });
3794                    }
3795                }
3796                // A stripe whose TAPER to a cusp reaches its full radius only
3797                // inside the corner setback at its other end has no constant
3798                // run at all (report 80c5d9d1's F10, 2026-10-24: r 1 on the two
3799                // straight edges of a sliver at most 2 wide within 0.9 of its
3800                // square corner). The round is built at the largest smaller
3801                // radius whose taper clears the setback, and says so, as the
3802                // relief says it over a whole rim. Before 2026-10-26 the group
3803                // fell through to the cutter composition, which closed each
3804                // round on a web and a cap under the neighbouring blend (an
3805                // undercut) in 9 minutes.
3806                let pinched_taper = matches!(&refusal.class, crate::RefusalClass::UnsupportedGeometry { what }
3807                    if what == crate::blend::STRIPE_PINCH_TAPER_WHAT);
3808                if !chamfer && pinched_taper && crate::blend::relief::radius_relief_on() {
3809                    let labels: Vec<String> =
3810                        (0..edge_points.len()).map(|index| selection_label(index, edge_points, edge_names, name)).collect();
3811                    for step in 1..=10u32 {
3812                        let reduced = radius * (1.0 - 0.05 * f64::from(step));
3813                        let built = crate::blend::blend_star_network_with_corner_policy(
3814                            solid, &selected_edge_ids, reduced, chamfer, &network_names, &network_corner_name, wrap_concave,
3815                        );
3816                        if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3817                            eprintln!(
3818                                "taper pinch ladder: r {reduced:.4} -> {}",
3819                                match &built {
3820                                    Ok(_) => "built".to_string(),
3821                                    Err(error) => format!("refused: {error}"),
3822                                }
3823                            );
3824                        }
3825                        match built {
3826                            Ok(network) => {
3827                                let Some(body) = accept_network(network, reduced)? else { break };
3828                                crate::blend::record_blend_note(format!(
3829                                    "radius reduced over the whole of {} to {reduced:.4}: at r {radius} the round tapering to \
3830                                     its tip reaches the full radius only inside the corner setback at its other end, so \
3831                                     r {radius} is reached nowhere",
3832                                    labels.join(", ")
3833                                ));
3834                                return Ok(body);
3835                            }
3836                            Err(again) if matches!(&again.class, crate::RefusalClass::UnsupportedGeometry { what }
3837                                if what == crate::blend::STRIPE_PINCH_TAPER_WHAT) => continue,
3838                            Err(_) => break,
3839                        }
3840                    }
3841                }
3842                // Independent stripe cutters cannot close a corner whose ball
3843                // exceeds the canal footprint. Preserve the requested radius
3844                // and its named refusal instead of searching partial selections.
3845                if matches!(&refusal.class, RefusalClass::UnsupportedGeometry { what }
3846                    if what == "canal_footprint_bound") || crate::blend::is_ball_does_not_fit(&refusal) {
3847                    return Err(refusal);
3848                }
3849                // The runout composition reads the ring's own classification
3850                // back when the ring stage falls through to the cutter and
3851                // that refuses too (`LAST_NETWORK_REFUSAL`).
3852                LAST_NETWORK_REFUSAL.with(|last| *last.borrow_mut() = Some(refusal.clone()));
3853                if crate::blend::is_wall_fold(&refusal) {
3854                    GROUP_NETWORK_FOLD.with(|fold| *fold.borrow_mut() = Some(refusal.clone()));
3855                }
3856                // A refusal that is not a fold where the ball does not fit
3857                // (report 37e16630 at r 1.0, a ball the size of the round it
3858                // rides: its centre curve collapses to a point and the station
3859                // Newton is singular) is the fold the relief answers, not a
3860                // question for the composition, which took 143 s over it.
3861                if !chamfer && !crate::blend::is_wall_fold(&refusal) && crate::blend::relief::radius_relief_on() {
3862                    let started = web_time::Instant::now();
3863                    let misfit = crate::blend::relief::first_misfit(solid, &selected_edge_ids, radius);
3864                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
3865                        eprintln!("radius relief: misfit probe {misfit:?} in {:.1} ms", started.elapsed().as_secs_f64() * 1e3);
3866                    }
3867                    if let Some((edge_id, least)) = misfit {
3868                        return Err(crate::blend::relief::misfit_fold(edge_id, least, radius, &refusal));
3869                    }
3870                }
3871                // The fail-safe above is for a refusal that says "not this
3872                // lane".  A marched fit that left its carriers does not say
3873                // that, and the cutter's answer to the same selection is not a
3874                // second opinion on it: on the notched cap's stuck connector
3875                // the composition reads 1724.506048919, +1.81e-2 against the
3876                // closed form, and it VALIDATES.  A refusal that falls through
3877                // to a validating wrong solid is not a refusal.
3878                //
3879                // Not every WALL FOLD, though the single-edge tool reads them all
3880                // as terminal (`is_terminal_blend_refusal`): a fold of the lens
3881                // between the rails is one the composition's cutter carves
3882                // (`inbox_20260902_corner_torus_collar_fillet::each_collar_has_its_own_fold_threshold`,
3883                // the r 2.1 collar at fold factor 1.036). One that reaches a
3884                // RAIL is not: the ball pokes out through the face it rides,
3885                // there is no lens to carve, and every cutter sweeps the same
3886                // envelope. Until 2026-10-21 the group fell through on that too:
3887                // report 37e16630's end face at r 1.7 around an r 1 round on its
3888                // outline ran the composition and its subset search for over 20
3889                // minutes. A lens fold the composition cannot rescue either is
3890                // answered by the fold (`fillet_edges_group_unchecked`).
3891                //
3892                // A blend stopping within a sliver of its face's width that
3893                // cannot be snapped onto the far edge without opening the shell
3894                // is terminal for the same reason: the SIZE is the question
3895                // (`blend::CONSUMED_SNAP_UNSOUND`), and the composition's tool
3896                // cut a sliver short of an edge leaves the sliver no lane keeps.
3897                //
3898                // And a FULL-WIDTH corner the network cannot collapse soundly
3899                // (`blend::RAIL_COLLAPSE_UNSUPPORTED`,
3900                // `blend::FULL_WIDTH_COLLAPSE_UNSOUND`): the composition's answer
3901                // to a full-width corner was measured wrong — a 5F/8E/5V miter
3902                // 8.0e-4 off its closed form at 1e-5 short of the width, and the
3903                // picture-frame corner at a full-width chamfer star.
3904                //
3905                // And a trim that left its planar carrier's chart
3906                // (`blend::PLANAR_CHART_EDGE_OFF_PLANE`,
3907                // `blend::PLANAR_CHART_WIDEN_UNSOUND`): the clamped body the
3908                // composition would answer with is the defect being refused.
3909                // A tangential end whose taper could not be planned also has
3910                // no supported closure for cutter composition to recover.
3911                if crate::blend::is_rail_fold(&refusal)
3912                    || crate::blend::is_marched_fit_off_carriers(&refusal)
3913                    || crate::blend::is_consumed_snap(&refusal)
3914                    || crate::blend::is_rail_collapse(&refusal)
3915                    || crate::blend::is_full_width_collapse(&refusal)
3916                    || crate::blend::is_planar_chart_refusal(&refusal)
3917                    || crate::blend::is_miter_support_overrun(&refusal)
3918                    || crate::blend::is_tangential_transverse_end(&refusal)
3919                {
3920                    return Err(refusal);
3921                }
3922            }
3923        }
3924    }
3925
3926    // An edge whose ball reaches its support only by rolling over a tangent
3927    // neighbour (`analyze::rollover_only_refusal`): the composition's tool
3928    // rides the mates' own carriers past the tangent edge and fills over air
3929    // (lCount_409 at r 2: +1.096 against the quadrature's 1103.315046), so
3930    // the reach refusal the unsigned check gave stands.
3931    if let Some(refusal) = super::analyze::rollover_only_refusal(&selected_edge_ids) {
3932        return Err(refusal);
3933    }
3934    CUTTER_COMPOSITIONS.with(|count| count.set(count.get() + 1));
3935    crate::blend::record_count("count.cutter_fallback", 1);
3936    let _cutter = crate::blend::BlendTimer::start("timing.cutter_ms");
3937    // 2. Build the blends.
3938    //
3939    //    CHAIN corners (§6.9.6 — exactly TWO selected edges share a vertex):
3940    //    the sequential build truncates the later blend where it runs into the
3941    //    earlier one and closes it with a flat bulkhead across the fillet
3942    //    channel — a hard step, not a transition.  For selections containing
3943    //    chain corners, blend each edge FULL-LENGTH on the ORIGINAL solid and
3944    //    INTERSECT the per-edge results instead: the removal volumes union, so
3945    //    adjacent blends run through the shared corner and trim each other
3946    //    along their intersection curve — the standard MITER corner, tangent
3947    //    to the shared face at the seam's tangency end.  Non-adjacent edges
3948    //    are unaffected (their removals are disjoint, intersection ≡
3949    //    sequential).
3950    //
3951    //    Selections without chain corners keep the sequential build unchanged
3952    //    (star corners are rounded in step 3 against exactly the sequential
3953    //    geometry round_convex_corner was built for).
3954    //    CONVEXITY GUARD: a convex blend REMOVES material (fillet = orig −
3955    //    cut), a concave blend ADDS it (orig + pad).  Full-length blends
3956    //    combine as orig − ∪cuts + ∪pads, so the per-edge results compose by
3957    //    INTERSECTION when every edge is convex and by UNION when every edge
3958    //    is concave; a mixed selection has no single composition and falls
3959    //    back to the sequential build.
3960    // Fillet stars keep the sequential topology required by their sphere
3961    // patches. Chamfer stars have no subsequent corner patch: compose their
3962    // full-length removals too, so all bevel planes meet at the corner.
3963    let miter_operation = if (chain_corner_count > 0 || !corners.is_empty())
3964        && (chamfer || corners.is_empty())
3965    {
3966        let mut any_convex = false;
3967        let mut any_concave = false;
3968        for point in edge_points {
3969            // Convexity is a DIHEDRAL property, so it is read from the general
3970            // scan (`scan_dihedral`) — the same one `check_mixed_concavity`
3971            // has already run over every selected edge.  `analyze_edge` used
3972            // to answer here and it ALSO refuses an edge the EXACT CUTTER
3973            // cannot build: a straight edge whose mates are not both planes,
3974            // a circular one whose mates do not share its axis.  Reading that
3975            // refusal as "unknown convexity" dropped the §6.9.6 miter for
3976            // every selection touching a curved carrier — the groove rim of a
3977            // bored box, say — and the sequential build then left a bulkhead
3978            // face standing in the shared corner (the 2026-09-10 "chamfer
3979            // produced a spurious face" report).
3980            match resolve_edge_by_point(solid, *point)
3981                .and_then(|edge_id| super::analyze::scan_dihedral(solid, edge_id))
3982            {
3983                // A mixed edge has no single composition either; it takes the
3984                // `_ => None` arm below through both flags.
3985                Ok(profile) if profile.samples > 0 && !profile.is_mixed() => {
3986                    any_convex |= profile.any_convex;
3987                    any_concave |= profile.any_concave;
3988                }
3989                // Unknown edge class: let the sequential path produce its own
3990                // (more specific) error or result.
3991                _ => {
3992                    any_convex = true;
3993                    any_concave = true;
3994                    break;
3995                }
3996            }
3997        }
3998        match (any_convex, any_concave) {
3999            (true, false) => Some(crate::BooleanOperation::Intersect),
4000            (false, true) => Some(crate::BooleanOperation::Union),
4001            _ => None,
4002        }
4003    } else {
4004        None
4005    };
4006
4007    // Fillet/chamfer each edge in turn, resolving its point on the evolving
4008    // solid (ids shift as earlier fillets rewrite topology; the midpoint of an
4009    // edge is untouched by the corner surgery of the others).  This is the
4010    // baseline build used directly for non-miter selections AND as the
4011    // fallback when the miter composition below cannot reassemble.
4012    // The composition's per-edge lane: cutter-first ONLY when a corner
4013    // closure will run afterwards and read cutter-shaped topology (a star or
4014    // a chain corner).  A selection with no shared vertex — a lone closed
4015    // rim, a lone chamfer, disconnected edges — has no such closure, so each
4016    // edge gets the march first there too.
4017    let composition_lane = if corners.is_empty() && chain_corner_count == 0 {
4018        Lane::GeneralFirst
4019    } else {
4020        Lane::CutterFirst
4021    };
4022    // The order the sequential build blends the selection in: the input
4023    // order, except that a CONCAVE edge ending at a star corner goes before
4024    // every convex edge (`sequential_build_order`). The §6.9.7 torus-sector
4025    // closure of a re-entrant vertex whose concave edge is selected too
4026    // (`round_mixed_concave_corner`) reads the concave blend's tangency
4027    // vertices off the convex cap cutters, so it exists only when the concave
4028    // edge was cut FIRST; a user who picks the keyway's rim and then its
4029    // inner corners (the 2026-10-13 sprocket report) got flat caps at both
4030    // corners from the input order, and the closure's own closed form from
4031    // this one. Every other selection keeps its input order, byte for byte.
4032    let concave_at_star = concave_star_edges(solid, &selected_edge_ids, &corner_edges, radius, chamfer);
4033    // And at a star corner whose edges the ladder answers with DIFFERENT
4034    // cutters, the marched edges go before the exact ones and the revolved
4035    // cutters last (`mixed_star_class_ranks`): the 2026-10-13 sprocket
4036    // report whose slit walls were selected as faces.
4037    let class_ranks = mixed_star_class_ranks(solid, &selected_edge_ids, &corner_edges, radius, chamfer);
4038    let sequential_order = sequential_build_order(edge_points.len(), &concave_at_star, &class_ranks);
4039    // And the corners close in the same precedence: a star with a concave
4040    // edge (the torus sector) before the convex stars, which on the report's
4041    // keyway share a 3.8-long rim edge with it — the convex star's surgery
4042    // read an open edge when it ran first (measured 2026-10-13), and closes
4043    // cleanly after the sector has trimmed that rim.
4044    let (corners, corner_edges) = corners_concave_first(corners, corner_edges, &concave_at_star);
4045    let mut build_sequential = || -> Result<BrepSolid, KernelRefusal> {
4046        let mut sequential = solid.clone();
4047        // The prefix chain of this build, for the subset search's memo (see
4048        // `ComponentMemo::sequential`); unused without one.
4049        let mut chain: Vec<SequentialKey> = Vec::with_capacity(sequential_order.len());
4050        for &index in &sequential_order {
4051            let point = &edge_points[index];
4052            let edge_id = resolve_edge_by_point(&sequential, *point)?;
4053            // Earlier cutters in this loop TRIM the edges that share a corner
4054            // with them; extend this cutter back over what they took so the
4055            // two removal volumes union through the corner (§6.9.6 miter)
4056            // instead of leaving a wedge of material standing behind a flush
4057            // end cap.  Untouched edges get a zero pad and the historical
4058            // flush cutter.
4059            let ends = tool_ends_to_original_extent(
4060                &sequential,
4061                edge_id,
4062                radius,
4063                original_extents[index],
4064                if chamfer { &[] } else { &corners },
4065            );
4066            // This edge's blend wall carries the name of THIS input edge
4067            // (`edge_names[index]`); a smooth chain that engulfs several edges
4068            // is named after the FIRST such input edge processed here (input
4069            // order), the chain's representative.
4070            let edge_name = per_edge_name(edge_names, name, index);
4071            if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4072                eprintln!(
4073                    "sequential build: selection #{index} {} is edge {edge_id} on the evolving body (ends {ends:?}, {composition_lane:?})",
4074                    selection_label(index, edge_points, edge_names, name)
4075                );
4076            }
4077            // Every step is a deterministic function of the body it starts
4078            // from and these four inputs, and the body is itself the chain of
4079            // the steps before it: a chain the search already composed on
4080            // this solid is answered from the memo, refusals included.
4081            chain.push((
4082                [point.x.to_bits(), point.y.to_bits(), point.z.to_bits()],
4083                edge_name.map(str::to_string),
4084                ends.key_bits(),
4085                u8::from(composition_lane == Lane::CutterFirst),
4086            ));
4087            if let Some(memo) = memo.as_deref_mut() {
4088                let key = (memo.prefix.clone(), chain.clone());
4089                let hit = memo.sequential.get(&key);
4090                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4091                    eprintln!(
4092                        "sequential memo: {} components before, step {} {} ({} chains stored)",
4093                        memo.prefix.len(),
4094                        chain.len(),
4095                        if hit.is_some() { "HIT" } else { "miss" },
4096                        memo.sequential.len(),
4097                    );
4098                }
4099                if let Some(built) = hit {
4100                    crate::blend::record_count("count.sequential.memo_hits", 1);
4101                    sequential = built.clone()?;
4102                    continue;
4103                }
4104            }
4105            crate::blend::record_count("count.sequential.steps_built", 1);
4106            let built = fillet_or_chamfer(
4107                &sequential,
4108                edge_id,
4109                radius,
4110                chamfer,
4111                edge_name,
4112                ends,
4113                composition_lane,
4114            );
4115            if let Some(memo) = memo.as_deref_mut() {
4116                memo.sequential.insert((memo.prefix.clone(), chain.clone()), built.clone());
4117            }
4118            sequential = built?;
4119        }
4120        Ok(sequential)
4121    };
4122
4123    let mut result = if let Some(operation) = miter_operation {
4124        // The per-edge results still carry their cutters' standing scaffold,
4125        // which the group settles once its corners are closed. A scaffold face
4126        // merged here would hand its tag to whatever it merged with.
4127        let options = crate::BooleanOptions {
4128            keep_unmerged_name_substrs: vec![CUTTER_SCAFFOLD_NAME.to_string()],
4129            ..crate::BooleanOptions::default()
4130        };
4131        let mut combined: Result<Option<BrepSolid>, KernelRefusal> = Ok(None);
4132        // The units the miter composes: one per selected edge, except that
4133        // edges joined at a TANGENT chain corner blend as one unit through
4134        // this same group build (see `miter_tangent_units`).
4135        let units = miter_tangent_units(solid, &selected_edge_ids, &chain_corners, edge_points.len());
4136        for unit in &units {
4137            let index = unit[0];
4138            let point = &edge_points[index];
4139            let blended = if unit.len() > 1 {
4140                let points = unit.iter().map(|&member| edge_points[member]).collect::<Vec<_>>();
4141                let names = edge_names.map(|all| unit.iter().map(|&member| all[member].clone()).collect::<Vec<_>>());
4142                fillet_edges_group_with_corner_policy(
4143                    solid,
4144                    &points,
4145                    names.as_deref(),
4146                    radius,
4147                    chamfer,
4148                    name,
4149                    None,
4150                    wrap_concave,
4151                    false,
4152                )?
4153            } else {
4154                let edge_id = resolve_edge_by_point(solid, *point)?;
4155                let edge_name = per_edge_name(edge_names, name, index);
4156                let entry = if chamfer { "chamfer_edges" } else { "fillet_edges" };
4157                check_mixed_concavity(solid, edge_id, entry)?;
4158                check_support_extent(solid, edge_id, radius, entry)?;
4159                fillet_or_chamfer(
4160                    solid,
4161                    edge_id,
4162                    radius,
4163                    chamfer,
4164                    edge_name,
4165                    ToolEnds::default(),
4166                    Lane::CutterFirst,
4167                )?
4168            };
4169            combined = match combined {
4170                Err(e) => Err(e),
4171                Ok(None) => Ok(Some(blended)),
4172                Ok(Some(previous)) => {
4173                    crate::boolean_operation(&previous, &blended, operation, &options)
4174                        .map(Some)
4175                        .map_err(|error| {
4176                            // The boolean's own class survives the wrap.
4177                            error.with_message(|error| {
4178                                format!("fillet_edges: chain-corner miter composition failed: {error}")
4179                            })
4180                        })
4181                }
4182            };
4183            if combined.is_err() {
4184                break;
4185            }
4186        }
4187        // A §6.9.6 miter (per-edge blends intersected/unioned through the
4188        // shared chain corners) can fail to reassemble on faces whose
4189        // fragmented boundary does not close — e.g. a planar cap whose ENTIRE
4190        // perimeter is selected, where fragment_face reports an "incomplete
4191        // run".  Rather than let `fillet_edges` silently DROP a selected edge
4192        // to recover a valid subset (the reported defect: not every edge of
4193        // the face gets a fillet), fall back to the sequential build, which
4194        // blends EVERY selected edge (chain corners get a flat bulkhead
4195        // instead of a miter).  Only if that also fails to produce a valid
4196        // solid do we surface the miter error so the caller's
4197        // maximal-valid-subset search can still run.
4198        match combined {
4199            Ok(Some(mut mitered)) => {
4200                drop_slit_shells(&mut mitered);
4201                mitered
4202            }
4203            Ok(None) => {
4204                return Err(KernelRefusal::input(
4205                    KernelStage::Collect,
4206                    "miter_selection",
4207                    "fillet_edges: no edges selected",
4208                ))
4209            }
4210            Err(miter_err) => match build_sequential() {
4211                Ok(seq) if seq.validate().is_empty() => seq,
4212                _ => return Err(miter_err),
4213            },
4214        }
4215    } else {
4216        build_sequential()?
4217    };
4218
4219    // A re-entrant vertex of a selected face perimeter has two selected,
4220    // convex cap-wall edges and one UNSELECTED concave wall-wall edge.  The
4221    // two cutter volumes only touch there, so the boolean miter leaves a
4222    // triangular planar end-cap instead of carrying the rolling ball around
4223    // the corner.  Close that exact orthogonal class with its horn-torus
4224    // sector (major radius = minor radius = fillet radius).
4225    // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4226    let mut open_mixed_corners: Vec<(Vec3, [u64; 2], Option<String>)> = Vec::new();
4227    // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4228    if !chamfer {
4229        for (corner, adjacent) in &chain_corners {
4230            let has_concave_unselected_edge = solid.edges.iter().any(|edge| {
4231                if selected_edge_ids.contains(&edge.id) {
4232                    return false;
4233                }
4234                let Ok(a) = edge.curve.evaluate(edge.t0) else {
4235                    return false;
4236                };
4237                let Ok(b) = edge.curve.evaluate(edge.t1) else {
4238                    return false;
4239                };
4240                (a.sub(*corner).length() < 1e-6 || b.sub(*corner).length() < 1e-6)
4241                    && analyze_edge(solid, edge.id, radius)
4242                        .map(|cross| !cross.convex)
4243                        .unwrap_or(false)
4244            });
4245            // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4246            // The OPEN mixed corner (the 2026-10-13 sprocket's keyway floor):
4247            // one selected convex rim, one selected concave vertical and an
4248            // UNSELECTED convex third edge. The rim's cutter ran through the
4249            // concave pad and left a scaffold square and a misplaced
4250            // bulkhead there; the closure is the one-ended runout's body —
4251            // the §6.9.7 torus sector to C5's stop, ended by its cliff
4252            // (`blend/corner/mixed_open.rs`). It reads the SETTLED body (the
4253            // pad's flush end merged into the cap), so the corner is noted
4254            // here and closed after `settle_cutter_scaffold` below.
4255            if !has_concave_unselected_edge {
4256                let convexity = |edge_id: u64| analyze_edge(solid, edge_id, radius).map(|cross| cross.convex).ok();
4257                let selected_pair = [convexity(selected_edge_ids[adjacent[0]]), convexity(selected_edge_ids[adjacent[1]])];
4258                let one_concave = matches!(selected_pair, [Some(true), Some(false)] | [Some(false), Some(true)]);
4259                let has_convex_unselected_edge = solid.edges.iter().any(|edge| {
4260                    if selected_edge_ids.contains(&edge.id) {
4261                        return false;
4262                    }
4263                    let (Ok(a), Ok(b)) = (edge.curve.evaluate(edge.t0), edge.curve.evaluate(edge.t1)) else {
4264                        return false;
4265                    };
4266                    (a.sub(*corner).length() < 1e-6 || b.sub(*corner).length() < 1e-6)
4267                        && analyze_edge(solid, edge.id, radius).map(|cross| cross.convex).unwrap_or(false)
4268                });
4269                if one_concave && has_convex_unselected_edge {
4270                    open_mixed_corners.push((
4271                        *corner,
4272                        [selected_edge_ids[adjacent[0]], selected_edge_ids[adjacent[1]]],
4273                        corner_face_name(edge_names, name, adjacent),
4274                    ));
4275                }
4276                continue;
4277            }
4278            // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4279            let corner_name = corner_face_name(edge_names, name, adjacent);
4280            if let Ok(rounded) = crate::blend::round_concave_chain_corner(
4281                &result,
4282                solid,
4283                *corner,
4284                [
4285                    selected_edge_ids[adjacent[0]],
4286                    selected_edge_ids[adjacent[1]],
4287                ],
4288                radius,
4289                corner_name.as_deref(),
4290            ) {
4291                result = rounded;
4292            }
4293        }
4294    }
4295
4296    // 3. Round the convex corners (fillets only — chamfers keep sharp
4297    //    vertices).  A corner that cannot be rounded is left as the edge
4298    //    fillets so the group still succeeds.  Each corner patch is named after
4299    //    the selected edges meeting there (`{fid}:BLEND:CORNER:{e_a}+…`) so no
4300    //    two corners collide and the patch stays under the `{fid}:BLEND` prefix.
4301    if !chamfer {
4302        for (ci, corner) in corners.iter().enumerate() {
4303            let corner_name = corner_face_name(edge_names, name, &corner_edges[ci]);
4304            match crate::blend::round_convex_corner(&result, *corner, radius, corner_name.as_deref()) {
4305                Ok(rounded) => result = rounded,
4306                Err(error) => {
4307                    if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4308                        eprintln!("corner at {corner:?} left as the edge fillets: {error}");
4309                    }
4310                }
4311            }
4312        }
4313    }
4314
4315    // Heal any residual vertex/edge gaps introduced by the corner-rounding
4316    // surgery (the per-edge results are already healed inside fillet_or_chamfer).
4317    heal_edge_vertex_gaps(&mut result, radius)?;
4318    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
4319    // BREP lane L: begin keyway_floor_open_mixed_corner_20261014
4320    let mut body = settle_cutter_scaffold(result);
4321    for (corner, pair, corner_name) in &open_mixed_corners {
4322        match crate::blend::round_mixed_concave_open_corner(&body, solid, *corner, *pair, radius, corner_name.as_deref()) {
4323            Ok(rounded) => body = rounded,
4324            Err(error) => {
4325                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
4326                    eprintln!("open mixed corner at {corner:?} left as the composition built it: {error}");
4327                }
4328            }
4329        }
4330    }
4331    Ok(GroupBody { body, bowtie_clean: false })
4332    // BREP lane L: end keyway_floor_open_mixed_corner_20261014
4333}
4334
4335/// The selected edges (indices into the selection) that are CONCAVE and end
4336/// at a star corner (`corner_edges`: three or more selected edges at one
4337/// vertex), in input order. Empty for a chamfer, a selection with no star
4338/// corner, one whose star corners carry no concave edge, and one whose
4339/// convexity cannot be read — the cases the composition builds in input
4340/// order, exactly as before.
4341/// Whether the miter composition drops a stray SLIT shell: on unless
4342/// `BREP_FILLET_MITER_DROP_SLIT_SHELLS=0`/`off`.
4343fn drop_slit_shells_on() -> bool {
4344    switch!(live "BREP_FILLET_MITER_DROP_SLIT_SHELLS", true)
4345}
4346
4347/// Remove from a composed miter body every shell beyond the first whose faces
4348/// are all SLITS — each loop runs along each of its edges once forward and
4349/// once back — over edges no other shell uses, then the edges and vertices
4350/// nothing references any more. Returns how many shells went.
4351///
4352/// Such a shell bounds no area and no volume. The 2026-11-07 "fillet fails"
4353/// report's five-edge selection composed to the right body (the volume of
4354/// the same composition on the serialised input, which has one shell) plus
4355/// one face of the hole's floor plane, `Box_NZ_Offset_1_1`, whose single loop
4356/// ran 1.25 out along one edge and straight back; `validate()` accepts it.
4357fn drop_slit_shells(body: &mut BrepSolid) -> usize {
4358    if !drop_slit_shells_on() || body.shells.len() < 2 {
4359        return 0;
4360    }
4361    let mut users: std::collections::HashMap<u64, std::collections::HashSet<usize>> = std::collections::HashMap::new();
4362    for (index, shell) in body.shells.iter().enumerate() {
4363        for coedge in shell.faces.iter().flat_map(|face| &face.loops).flat_map(|lp| &lp.coedges) {
4364            users.entry(coedge.edge_id).or_default().insert(index);
4365        }
4366    }
4367    let slit_face = |face: &crate::topology::FaceRecord| {
4368        face.loops.iter().all(|lp| {
4369            let mut runs: std::collections::HashMap<u64, (usize, usize)> = std::collections::HashMap::new();
4370            for coedge in &lp.coedges {
4371                let entry = runs.entry(coedge.edge_id).or_default();
4372                if coedge.forward {
4373                    entry.0 += 1;
4374                } else {
4375                    entry.1 += 1;
4376                }
4377            }
4378            !runs.is_empty() && runs.values().all(|&(forward, back)| forward == 1 && back == 1)
4379        })
4380    };
4381    let mut index = 0usize;
4382    let mut dropped = 0usize;
4383    body.shells.retain(|shell| {
4384        let this = index;
4385        index += 1;
4386        let slit = this > 0
4387            && !shell.faces.is_empty()
4388            && shell.faces.iter().all(|face| slit_face(face))
4389            && shell
4390                .faces
4391                .iter()
4392                .flat_map(|face| &face.loops)
4393                .flat_map(|lp| &lp.coedges)
4394                .all(|coedge| users.get(&coedge.edge_id).is_some_and(|set| set.len() == 1));
4395        dropped += usize::from(slit);
4396        !slit
4397    });
4398    if dropped == 0 {
4399        return 0;
4400    }
4401    let used_edges: std::collections::HashSet<u64> = body
4402        .shells
4403        .iter()
4404        .flat_map(|shell| &shell.faces)
4405        .flat_map(|face| &face.loops)
4406        .flat_map(|lp| &lp.coedges)
4407        .map(|coedge| coedge.edge_id)
4408        .collect();
4409    body.edges.retain(|edge| used_edges.contains(&edge.id));
4410    let used_vertices: std::collections::HashSet<u64> =
4411        body.edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).collect();
4412    body.vertices.retain(|vertex| used_vertices.contains(&vertex.id));
4413    dropped
4414}
4415
4416/// Whether the miter composition blends a TANGENT run of the selection as
4417/// one unit: on unless `BREP_FILLET_MITER_TANGENT_UNITS=0`/`off`.
4418fn miter_tangent_units_on() -> bool {
4419    switch!(live "BREP_FILLET_MITER_TANGENT_UNITS", true)
4420}
4421
4422/// The units the §6.9.6 miter composition blends and then intersects (or
4423/// unions), in input order of each unit's first edge: every selected edge on
4424/// its own, except that edges meeting at a chain corner where their tangents
4425/// CONTINUE each other (a G1 joint, the 1e-6 bar of the tangent-chain walk)
4426/// form one unit.
4427///
4428/// The miter exists for SHARP chain corners: two full-length blends run
4429/// through the corner and trim each other. At a tangent joint there is
4430/// nothing to trim — the two walls meet flush — and two full-length
4431/// per-edge blends of the edges either side of it, each capped where its
4432/// tangent neighbour was left sharp, overlap along that joint in a sliver
4433/// the boolean cannot conform (2026-11-07 "fillet fails" report: a revolve
4434/// end cap's hole loop, one cylinder edge meeting a ceiling plane edge that
4435/// runs on tangentially through an offset blend into a wall; "one-use edge
4436/// conformance did not converge after 8 passes" on the plane-edge result
4437/// intersected with the blend-edge result). The network lane builds such a
4438/// tangent run whole with flush joins; it refused the selection only for
4439/// its sharp re-entrant corners, so a unit that is a STRICT part of the
4440/// selection goes back through the group build, which reaches it there.
4441/// A selection that is one tangent run keeps per-edge units, so the
4442/// recursion always shrinks the selection.
4443fn miter_tangent_units(
4444    solid: &BrepSolid,
4445    selected_edge_ids: &[u64],
4446    chain_corners: &[(Vec3, [usize; 2])],
4447    count: usize,
4448) -> Vec<Vec<usize>> {
4449    let singles = || (0..count).map(|index| vec![index]).collect::<Vec<_>>();
4450    if !miter_tangent_units_on() || selected_edge_ids.len() != count {
4451        return singles();
4452    }
4453    // The tangent along `edge` pointing AWAY from its end at `corner`.
4454    let leaving = |edge_id: u64, corner: Vec3| -> Option<Vec3> {
4455        let edge = solid.edges.iter().find(|edge| edge.id == edge_id)?;
4456        if edge.degenerate {
4457            return None;
4458        }
4459        let start = edge.curve.evaluate(edge.t0).ok()?;
4460        let end = edge.curve.evaluate(edge.t1).ok()?;
4461        let at_start = start.sub(corner).length() <= end.sub(corner).length();
4462        let t = if at_start { edge.t0 } else { edge.t1 };
4463        let tangent = edge.curve.unit_tangent(t, edge.t0, edge.t1).ok()?;
4464        Some(if at_start { tangent } else { tangent.scale(-1.0) })
4465    };
4466    let mut parent: Vec<usize> = (0..count).collect();
4467    fn root(parent: &mut [usize], mut index: usize) -> usize {
4468        while parent[index] != index {
4469            parent[index] = parent[parent[index]];
4470            index = parent[index];
4471        }
4472        index
4473    }
4474    for (corner, [a, b]) in chain_corners {
4475        let (Some(ta), Some(tb)) = (leaving(selected_edge_ids[*a], *corner), leaving(selected_edge_ids[*b], *corner)) else {
4476            continue;
4477        };
4478        // Leaving the corner, a tangent continuation points the opposite way.
4479        if ta.dot(tb) <= -(1.0 - 1e-6) {
4480            let (ra, rb) = (root(&mut parent, *a), root(&mut parent, *b));
4481            if ra != rb {
4482                parent[ra.max(rb)] = ra.min(rb);
4483            }
4484        }
4485    }
4486    let mut units: Vec<Vec<usize>> = Vec::new();
4487    let mut unit_of_root: std::collections::HashMap<usize, usize> = std::collections::HashMap::new();
4488    for index in 0..count {
4489        let r = root(&mut parent, index);
4490        let slot = *unit_of_root.entry(r).or_insert_with(|| {
4491            units.push(Vec::new());
4492            units.len() - 1
4493        });
4494        units[slot].push(index);
4495    }
4496    if units.len() <= 1 || units.iter().all(|unit| unit.len() == 1) {
4497        return singles();
4498    }
4499    units
4500}
4501
4502fn concave_star_edges(
4503    solid: &BrepSolid,
4504    selected_edge_ids: &[u64],
4505    corner_edges: &[Vec<usize>],
4506    radius: f64,
4507    chamfer: bool,
4508) -> Vec<usize> {
4509    if chamfer || corner_edges.is_empty() || !concave_first_on() {
4510        return Vec::new();
4511    }
4512    let Some(convexity) = crate::blend::selection_convexity(solid, selected_edge_ids, radius) else {
4513        return Vec::new();
4514    };
4515    (0..selected_edge_ids.len())
4516        .filter(|&index| !convexity[index] && corner_edges.iter().any(|adjacent| adjacent.contains(&index)))
4517        .collect()
4518}
4519
4520/// The cutter the sequential build's single-edge ladder answers a selected
4521/// edge with, read on the ORIGINAL solid: an exact extrusion (a straight
4522/// edge between planes), an exact revolution (a circular edge on
4523/// straight-meridian carriers about its own axis) or, for every other edge,
4524/// the general march (`fillet_or_chamfer_exact` refuses it, so the march
4525/// builds it with direct surgery on the evolving body).
4526#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4527enum CutterClass {
4528    Marched,
4529    Straight,
4530    Circular,
4531}
4532
4533fn cutter_class(solid: &BrepSolid, edge_id: u64, radius: f64) -> CutterClass {
4534    match super::analyze::analyze_edge(solid, edge_id, radius) {
4535        Ok(cross) => match cross.path {
4536            super::analyze::EdgePath::Straight { .. } => CutterClass::Straight,
4537            super::analyze::EdgePath::Circular { .. } => CutterClass::Circular,
4538        },
4539        Err(_) => CutterClass::Marched,
4540    }
4541}
4542
4543/// The sequential build's rank of every selected edge, from the cutter
4544/// classes meeting at the selection's star corners: `1` for a marched edge
4545/// and `3` for a revolved cutter at a star whose edges MIX classes, `2` for
4546/// everything else (a star of one class, a chain corner, a lone edge).
4547/// Within a rank the input order holds ([`sequential_build_order`]).
4548///
4549/// At such a corner the input order fails in two ways, both measured on the
4550/// 2026-10-13 sprocket report whose slit walls were selected as faces
4551/// (`inbox_20261013_sprocket_keyway_slit_fillet`): a revolved cutter leaves
4552/// a TORUS tangent to the hub's top plane along its rail, and the next
4553/// straight cutter's scaffold face lies in that very plane and ends on that
4554/// rail, so the boolean meets a tangent plane/torus contact along a 0.148
4555/// arc that the imprint traces but the assembly cannot close (`unsupported
4556/// tangent-curve surface intersection`, open edges, a 0.067 curve/vertex
4557/// gap); and the slit's vertical, a straight edge on the hub CYLINDER that
4558/// only the march builds, finds "no single end face across the corner" once
4559/// its star mates have been cut. The marched edge cut first sees the pristine
4560/// corner, and a straight cutter cut before the revolved one meets the
4561/// scaffold plane of a CYLINDER tangent along a line — the ordinary planar
4562/// star's own geometry, which the arrangement has always closed. Every
4563/// selection without a mixed-class star keeps its order, byte for byte.
4564fn mixed_star_class_ranks(
4565    solid: &BrepSolid,
4566    selected_edge_ids: &[u64],
4567    corner_edges: &[Vec<usize>],
4568    radius: f64,
4569    chamfer: bool,
4570) -> Vec<u8> {
4571    let mut ranks = vec![2u8; selected_edge_ids.len()];
4572    if chamfer || corner_edges.is_empty() || !class_order_on() {
4573        return ranks;
4574    }
4575    let classes: Vec<CutterClass> = selected_edge_ids
4576        .iter()
4577        .map(|&edge_id| cutter_class(solid, edge_id, radius))
4578        .collect();
4579    for adjacent in corner_edges {
4580        let Some(&head) = adjacent.first() else {
4581            continue;
4582        };
4583        if adjacent.iter().all(|&index| classes[index] == classes[head]) {
4584            continue;
4585        }
4586        for &index in adjacent {
4587            match classes[index] {
4588                CutterClass::Marched => ranks[index] = 1,
4589                CutterClass::Circular => ranks[index] = 3,
4590                CutterClass::Straight => {}
4591            }
4592        }
4593    }
4594    ranks
4595}
4596
4597/// The order the cutter composition's sequential build blends a selection
4598/// in: the input order, except that the edges in `first` (a star corner's
4599/// concave edges, [`concave_star_edges`]) are moved ahead of every other
4600/// edge and the rest follow by `ranks` ([`mixed_star_class_ranks`], lower
4601/// first), keeping the input order among the moved edges and within each
4602/// rank. With `first` empty and every rank equal this is the input order.
4603pub fn sequential_build_order(count: usize, first: &[usize], ranks: &[u8]) -> Vec<usize> {
4604    let mut order: Vec<usize> = (0..count).collect();
4605    // A stable sort: ties keep the input order.
4606    order.sort_by_key(|&index| if first.contains(&index) { 0 } else { ranks.get(index).copied().unwrap_or(2).max(1) });
4607    order
4608}
4609
4610/// Whether the sequential build ranks a mixed-class star's edges by cutter
4611/// class ([`mixed_star_class_ranks`]); always, outside a test that forces it
4612/// off.
4613fn class_order_on() -> bool {
4614    true
4615}
4616
4617
4618/// `corners` and their `corner_edges` (parallel), with every corner that one
4619/// of the `first` edges ends at moved ahead of the rest, both runs in their
4620/// detection order. With `first` empty both come back as they were.
4621fn corners_concave_first(
4622    corners: Vec<Vec3>,
4623    corner_edges: Vec<Vec<usize>>,
4624    first: &[usize],
4625) -> (Vec<Vec3>, Vec<Vec<usize>>) {
4626    if first.is_empty() {
4627        return (corners, corner_edges);
4628    }
4629    let mut ordered: Vec<(Vec3, Vec<usize>)> = Vec::with_capacity(corners.len());
4630    let pairs: Vec<(Vec3, Vec<usize>)> = corners.into_iter().zip(corner_edges).collect();
4631    let with_concave = |adjacent: &Vec<usize>| adjacent.iter().any(|index| first.contains(index));
4632    ordered.extend(pairs.iter().filter(|(_, adjacent)| with_concave(adjacent)).cloned());
4633    ordered.extend(pairs.iter().filter(|(_, adjacent)| !with_concave(adjacent)).cloned());
4634    ordered.into_iter().unzip()
4635}
4636
4637/// Whether the sequential build moves a star corner's concave edge first
4638/// ([`sequential_build_order`]); always, outside a test that forces it off.
4639fn concave_first_on() -> bool {
4640    true
4641}
4642
4643
4644/// Variable-radius fillet/chamfer of a GROUP of edges (§4.9.5), the app entry
4645/// for tapered blends: each selected edge (resolved by a point on it) is
4646/// blended with the SAME radius profile `radii` — a list of (edge-fraction,
4647/// radius) stops in `[0,1]` — applied along that edge's own parameterization.
4648/// Edges are blended independently (no shared-vertex corner rounding; a
4649/// variable-radius star has no single tangent ball), so this is the tapered
4650/// counterpart of `fillet_edges` for the constant case.
4651pub fn fillet_edges_variable(
4652    solid: &BrepSolid,
4653    edge_points: &[Vec3],
4654    edge_names: Option<&[String]>,
4655    radii: &[(f64, f64)],
4656    chamfer: bool,
4657    name: Option<&str>,
4658) -> Result<BrepSolid, KernelRefusal> {
4659    // One blend operation: the reports of an earlier one, never consumed, are
4660    // dropped as it starts (nested calls keep this operation's).
4661    let _operation = crate::blend::BlendOperation::enter();
4662    if edge_points.is_empty() {
4663        return Err(KernelRefusal::input(
4664            KernelStage::Collect,
4665            "variable_selection",
4666            "fillet_edges_variable: no edges selected",
4667        ));
4668    }
4669    let per_edge_stops: Vec<Vec<(f64, f64)>> = vec![radii.to_vec(); edge_points.len()];
4670    fillet_edges_variable_impl(
4671        solid,
4672        edge_points,
4673        edge_names,
4674        &per_edge_stops,
4675        chamfer,
4676        name,
4677        "fillet_edges_variable",
4678        true,
4679    )
4680}
4681
4682/// The shared variable-radius group core: each selected edge `i` is blended
4683/// with ITS OWN stop list `per_edge_stops[i]` (the legacy entry replicates one
4684/// list; the law entries sample a chain-abscissa [`crate::law::RadiusLaw`] per
4685/// edge).  `allow_tapered_sequential` keeps the legacy entry's sequential
4686/// fallback for tapered chains (whose end state is the honest
4687/// "mismatched radii" validation gate); the law entries pass `false` because
4688/// their stop fractions are computed against the ORIGINAL edges — the
4689/// sequential build re-resolves edges on the evolving solid whose shared
4690/// corners are already TRIMMED by earlier blends, which would silently distort
4691/// the law's abscissa mapping (constant stops are immune, so they may still
4692/// fall back).
4693#[allow(clippy::too_many_arguments)]
4694fn fillet_edges_variable_impl(
4695    solid: &BrepSolid,
4696    edge_points: &[Vec3],
4697    edge_names: Option<&[String]>,
4698    per_edge_stops: &[Vec<(f64, f64)>],
4699    chamfer: bool,
4700    name: Option<&str>,
4701    entry: &str,
4702    allow_tapered_sequential: bool,
4703) -> Result<BrepSolid, KernelRefusal> {
4704    // The translation control (`BREP_TRANSLATION_CONTROL`, `brep/recentre.rs`)
4705    // and the recentre guard, as `fillet_edges_reported` applies them.
4706    let bounds = crate::recentre::solid_bounds(solid);
4707    let translated = match crate::recentre::control_offset_at_entry() {
4708        Some(offset) => Some((offset, crate::recentre::EntryKind::Control)),
4709        None => crate::recentre::guard_offset(bounds).map(|offset| {
4710            crate::recentre::profile_fired(entry, offset, bounds);
4711            (offset, crate::recentre::EntryKind::Guard)
4712        }),
4713    };
4714    if let Some((offset, kind)) = translated {
4715        let _entry = crate::recentre::TranslatedEntry::open(kind);
4716        let translate = |solid: &BrepSolid, offset: Vec3| {
4717            crate::recentre::translate_solid(solid, offset).map_err(|message| {
4718                KernelRefusal::internal(
4719                    KernelStage::Collect,
4720                    "translation_control",
4721                    format!("{entry}: the translation control could not move the solid: {message}"),
4722                )
4723            })
4724        };
4725        let moved = translate(solid, offset)?;
4726        let points: Vec<Vec3> = edge_points.iter().map(|point| point.add(offset)).collect();
4727        let result = fillet_edges_variable_impl(
4728            &moved,
4729            &points,
4730            edge_names,
4731            per_edge_stops,
4732            chamfer,
4733            name,
4734            entry,
4735            allow_tapered_sequential,
4736        )?;
4737        return translate(&result, offset.scale(-1.0));
4738    }
4739    debug_assert_eq!(per_edge_stops.len(), edge_points.len());
4740    // A law that is one constant everywhere IS the constant-radius fillet:
4741    // hand it to the constant group, whose corners are constructed (the
4742    // stripe network) rather than composed by boolean.
4743    if let Some(constant) = per_edge_stops
4744        .first()
4745        .and_then(|stops| stops.first())
4746        .map(|(_, radius)| *radius)
4747    {
4748        let uniform = per_edge_stops.iter().all(|stops| {
4749            stops
4750                .iter()
4751                .all(|(_, radius)| (radius - constant).abs() <= 1e-12 * (1.0 + constant.abs()))
4752        });
4753        if uniform && constant > 0.0 {
4754            return fillet_edges(solid, edge_points, edge_names, constant, chamfer, name);
4755        }
4756    }
4757    let max_radius = per_edge_stops
4758        .iter()
4759        .flat_map(|stops| stops.iter())
4760        .map(|(_, r)| r.abs())
4761        .fold(0.0_f64, f64::max);
4762
4763    // Tried first; whatever the network does not build (an unequal-radius
4764    // corner, a flush join or re-entrant vertex at a varying radius, a
4765    // result its acceptance rejects) falls through to the composition below
4766    // exactly as before.
4767    if edge_points.len() >= 2 {
4768        match fillet_variable_network(
4769            solid, edge_points, edge_names, per_edge_stops, chamfer, name, entry, max_radius,
4770        )? {
4771            Ok(built) => return Ok(built),
4772            // A radius relief's law is the network's to build: the
4773            // composition below took 75 s a plan on report 37e16630 at r 1.0
4774            // and built none, so the relief's next plan is asked instead.
4775            Err(refusal) if crate::blend::relief::relieving() => return Err(refusal),
4776            Err(_) => {}
4777        }
4778    }
4779
4780    // Chain corners miter exactly like the constant-radius group (§6.9.6):
4781    // per-edge blends on the ORIGINAL solid composed by boolean — Intersect
4782    // when every edge is convex, Union when every edge is concave.  Mixed or
4783    // unclassifiable selections keep the sequential build.  Variable blends
4784    // never round star vertices, so unlike the constant group there is no
4785    // sequential-only star path to protect.
4786    let mut chain_corner = false;
4787    {
4788        use rustc_hash::FxHashSet as HashSet;
4789        let mut endpoints: Vec<(Vec3, usize)> = Vec::with_capacity(edge_points.len() * 2);
4790        for (i, point) in edge_points.iter().enumerate() {
4791            if let Ok(edge_id) = resolve_edge_by_point(solid, *point) {
4792                if let Some(edge) = solid.edges.iter().find(|e| e.id == edge_id) {
4793                    if let (Ok(a), Ok(b)) =
4794                        (edge.curve.evaluate(edge.t0), edge.curve.evaluate(edge.t1))
4795                    {
4796                        endpoints.push((a, i));
4797                        endpoints.push((b, i));
4798                    }
4799                }
4800            }
4801        }
4802        let mut used = vec![false; endpoints.len()];
4803        for i in 0..endpoints.len() {
4804            if used[i] {
4805                continue;
4806            }
4807            used[i] = true;
4808            let mut edges_here: HashSet<usize> = HashSet::default();
4809            edges_here.insert(endpoints[i].1);
4810            for j in (i + 1)..endpoints.len() {
4811                if used[j] {
4812                    continue;
4813                }
4814                if endpoints[i].0.sub(endpoints[j].0).length() < 1e-6 {
4815                    used[j] = true;
4816                    edges_here.insert(endpoints[j].1);
4817                }
4818            }
4819            if edges_here.len() == 2 {
4820                chain_corner = true;
4821            }
4822        }
4823    }
4824    let miter_operation = if chain_corner {
4825        let probe_radius = if max_radius > 0.0 { max_radius } else { 1.0 };
4826        let mut any_convex = false;
4827        let mut any_concave = false;
4828        for point in edge_points {
4829            match resolve_edge_by_point(solid, *point)
4830                .and_then(|edge_id| analyze_edge(solid, edge_id, probe_radius))
4831            {
4832                Ok(cross) if cross.convex => any_convex = true,
4833                Ok(_) => any_concave = true,
4834                Err(_) => {
4835                    any_convex = true;
4836                    any_concave = true;
4837                    break;
4838                }
4839            }
4840        }
4841        match (any_convex, any_concave) {
4842            (true, false) => Some(crate::BooleanOperation::Intersect),
4843            (false, true) => Some(crate::BooleanOperation::Union),
4844            _ => None,
4845        }
4846    } else {
4847        None
4848    };
4849
4850    // Try the miter first; the variable blend's FITTED boundary curves are
4851    // only ~1e-3 accurate at blend-blend tangencies (unlike the exact
4852    // constant-radius cylinders), so the composition can fail — fall back to
4853    // the sequential build then, which is never worse than the pre-miter
4854    // behavior.  Tightening the taper surface's endpoint fitting is the
4855    // documented follow-up that would make the miter stick.
4856    let miter_attempt: Option<BrepSolid> = if let Some(operation) = miter_operation {
4857        let options = crate::BooleanOptions::default();
4858        let mut combined: Option<BrepSolid> = None;
4859        let mut failed = false;
4860        for (index, point) in edge_points.iter().enumerate() {
4861            let Ok(edge_id) = resolve_edge_by_point(solid, *point) else {
4862                failed = true;
4863                break;
4864            };
4865            let edge_name = per_edge_name(edge_names, name, index);
4866            let Ok(blended) = crate::blend::blend_edge_variable(
4867                solid,
4868                edge_id,
4869                &per_edge_stops[index],
4870                chamfer,
4871                edge_name,
4872            ) else {
4873                failed = true;
4874                break;
4875            };
4876            let next = match combined.take() {
4877                None => blended,
4878                Some(previous) => {
4879                    match crate::boolean_operation(&previous, &blended, operation, &options) {
4880                        Ok(next) => next,
4881                        Err(_) => {
4882                            failed = true;
4883                            break;
4884                        }
4885                    }
4886                }
4887            };
4888            combined = Some(next);
4889        }
4890        if failed {
4891            None
4892        } else {
4893            combined.filter(|s| s.validate().is_empty())
4894        }
4895    } else {
4896        None
4897    };
4898    let mut result = match miter_attempt {
4899        Some(mitered) => mitered,
4900        None => {
4901            // Any stop list that is NOT radius-uniform (the same 1e-12
4902            // relative criterion `blend_edge_variable` uses for its exact
4903            // constant-radius degeneration) makes the sequential build
4904            // abscissa-distorting on trimmed chain edges; law entries refuse
4905            // instead of silently shifting the law.
4906            let tapered = per_edge_stops.iter().any(|stops| {
4907                stops.first().is_some_and(|(_, first)| {
4908                    stops
4909                        .iter()
4910                        .any(|(_, r)| (r - first).abs() > 1e-12 * (1.0 + first.abs()))
4911                })
4912            });
4913            if chain_corner && tapered && !allow_tapered_sequential {
4914                // The transition patch that would carry a taper through the
4915                // corner is not built: a named deferral.
4916                return Err(KernelRefusal::unsupported(
4917                    KernelStage::Sew,
4918                    "tapered_chain_miter",
4919                    format!(
4920                        "{entry}: the tapered blends across the selected chain's shared corners \
4921                         did not compose to a valid solid (the fitted blend boundaries could not \
4922                         be mitered); fillet fewer edges per operation or reduce the taper"
4923                    ),
4924                ));
4925            }
4926            let mut sequential = solid.clone();
4927            for (index, point) in edge_points.iter().enumerate() {
4928                let edge_id = resolve_edge_by_point(&sequential, *point)?;
4929                let edge_name = per_edge_name(edge_names, name, index);
4930                sequential = crate::blend::blend_edge_variable(
4931                    &sequential,
4932                    edge_id,
4933                    &per_edge_stops[index],
4934                    chamfer,
4935                    edge_name,
4936                )?;
4937            }
4938            sequential
4939        }
4940    };
4941    // Heal §6.9 surgery so re-trimmed edges meet their vertices exactly; scale
4942    // the heal bound by the largest radius stop in the taper profile.
4943    heal_edge_vertex_gaps(&mut result, max_radius)?;
4944    crate::blend::fit_planar_charts_to_trims(solid, &mut result)?;
4945    // Final honesty gate: a genuinely TAPERED chain (different radii at the
4946    // shared corner) has mismatched trim stations there — the blends cannot
4947    // meet without a transition patch (not implemented), and the sequential
4948    // surgery silently left broken topology before this gate existed.
4949    let issues = result.validate();
4950    if !issues.is_empty() {
4951        // Two verdicts share the text's shape: the legacy entry names the
4952        // transition patch it does not build (a deferral); the law entries,
4953        // whose taper is continuous through the corner, report the
4954        // composition failing its own validation (a check that tripped).
4955        let (detail, class) = if allow_tapered_sequential {
4956            (
4957                "tapered blends meet at a shared chain vertex with \
4958                 mismatched radii — the radius-transition corner patch is not implemented; \
4959                 fillet the edges in separate operations or use matching stop radii",
4960                RefusalClass::UnsupportedGeometry {
4961                    what: "taper_transition_patch".into(),
4962                },
4963            )
4964        } else {
4965            (
4966                "the composed radius-law blend produced invalid topology — the blends \
4967                 across a shared chain corner failed to reassemble",
4968                RefusalClass::Internal {
4969                    what: "law_chain_topology".into(),
4970                },
4971            )
4972        };
4973        return Err(KernelRefusal::new(
4974            class,
4975            KernelStage::Validate,
4976            format!(
4977                "{entry}: {detail} ({} validation issues, first: {})",
4978                issues.len(),
4979                issues
4980                    .first()
4981                    .map(|issue| issue.message.clone())
4982                    .unwrap_or_default()
4983            ),
4984        ));
4985    }
4986    // The variable-radius lane's own soundness acceptance, the same one the
4987    // constant-radius group exit takes. `validate()` above is an INCIDENCE
4988    // test: a tapered wall that passes through a neighbour, or through itself,
4989    // satisfies every check it makes and still measures a volume.
4990    crate::soundness::census::profile_operation(&result, &[solid], None, entry);
4991    crate::accept_sound(result, entry)
4992}
4993
4994/// `Ok(None)` is "not this lane" — the network refused, or its result
4995/// failed the same acceptance the constant group holds the network to —
4996/// and the caller composes as before; `Err` is a refusal nothing below
4997/// can answer.
4998#[allow(clippy::too_many_arguments)]
4999fn fillet_variable_network(
5000    solid: &BrepSolid,
5001    edge_points: &[Vec3],
5002    edge_names: Option<&[String]>,
5003    per_edge_stops: &[Vec<(f64, f64)>],
5004    chamfer: bool,
5005    name: Option<&str>,
5006    entry: &str,
5007    max_radius: f64,
5008) -> Result<Result<BrepSolid, KernelRefusal>, KernelRefusal> {
5009    let mut edge_ids = Vec::with_capacity(edge_points.len());
5010    for point in edge_points {
5011        edge_ids.push(resolve_edge_by_point(solid, *point)?);
5012    }
5013    let laws: Vec<crate::blend::StripeRadius> =
5014        per_edge_stops.iter().map(|stops| crate::blend::StripeRadius::from_stops(stops)).collect();
5015    let network_names: Vec<Option<String>> = (0..edge_points.len())
5016        .map(|index| per_edge_name(edge_names, name, index).map(str::to_string))
5017        .collect();
5018    let network_corner_name = |adjacent: &[usize]| corner_face_name(edge_names, name, adjacent);
5019    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
5020    // A support pcurve off the floor is re-run ONCE with the knot-aware
5021    // support fit, as the constant group's network is; a re-run that also
5022    // fails keeps the first refusal. A radius relief's law crowds the
5023    // march's stations into its ramp, and the rail's knot spans there are
5024    // finer than the uniform track can follow (a reported model: r 1.4 on
5025    // the outline of a cut through a sub-D body, its relieved rail spans
5026    // 7.7e-5 against a track spacing of 2.4e-4, 1.5e-6 off at 4097
5027    // samples).
5028    let law_network = || {
5029        crate::blend::blend_star_network_laws(solid, &edge_ids, &laws, chamfer, &network_names, &network_corner_name, true)
5030    };
5031    let network_result = law_network().or_else(|first| {
5032        if crate::blend::is_pcurve_floor_refusal(&first) {
5033            crate::blend::with_pcurve_knot_retry(law_network).map_err(|_| first)
5034        } else {
5035            Err(first)
5036        }
5037    });
5038    let mut network = match network_result {
5039        Ok(network) => network,
5040        Err(refusal) => {
5041            if debug {
5042                eprintln!("law network refused: {refusal}");
5043            }
5044            return Ok(Err(refusal));
5045        }
5046    };
5047    // The constant group's acceptance of a network result, in its order:
5048    // the vertex-gap heal, the planar charts, validation, the interference
5049    // classifier and the bowtie scan; then the soundness acceptance the
5050    // variable lane's exit takes.
5051    let healed = heal_edge_vertex_gaps(&mut network, max_radius);
5052    crate::blend::fit_planar_charts_to_trims(solid, &mut network)?;
5053    let issues = network.validate();
5054    let interference = check_blend_interference(solid, &network, &edge_ids, entry);
5055    let bowtie = check_loop_self_crossings(&network, entry).and_then(|()| check_blend_wall_loops(&network, entry));
5056    if healed.is_ok() && issues.is_empty() && interference.is_ok() && bowtie.is_ok() {
5057        crate::soundness::census::profile_operation(&network, &[solid], None, entry);
5058        match crate::accept_sound(network, entry) {
5059            Ok(sound) => return Ok(Ok(sound)),
5060            Err(refusal) => {
5061                if debug {
5062                    eprintln!("law network result unsound: {refusal}");
5063                }
5064                return Ok(Err(refusal));
5065            }
5066        }
5067    }
5068    if debug {
5069        eprintln!(
5070            "law network result rejected: heal={healed:?} issues={issues:?} \
5071             interference={interference:?} bowtie={bowtie:?}"
5072        );
5073    }
5074    Ok(Err(KernelRefusal::unsupported(
5075        KernelStage::Validate,
5076        "law_network_rejected",
5077        format!(
5078            "{entry}: the tapered network's result was rejected (heal {}, {} validation issues, interference {}, loops {})",
5079            if healed.is_ok() { "ok" } else { "failed" },
5080            issues.len(),
5081            if interference.is_ok() { "ok" } else { "found" },
5082            if bowtie.is_ok() { "ok" } else { "found" },
5083        ),
5084    )))
5085}
5086
5087
5088/// One selected edge placed on the ordered chain, with its arc-length
5089/// parameterization (the caller-side mapping from chain abscissa to the
5090/// `blend_edge_variable` per-edge parameter-fraction stop seam).
5091struct ChainLink {
5092    /// Position of this edge in the caller's `edge_points` selection.
5093    input_index: usize,
5094    /// True when the edge's own t0→t1 parameter direction runs WITH the chain.
5095    forward: bool,
5096    /// Cumulative chord-length table from the edge's t0 end:
5097    /// `(parameter fraction, arc length)`, uniformly spaced in fraction.
5098    arc: Vec<(f64, f64)>,
5099    /// Total arc length of the edge.
5100    length: f64,
5101    /// Chain abscissa at the link's ENTRY vertex (the end reached first when
5102    /// walking the chain from its start).
5103    abscissa: f64,
5104}
5105
5106/// Cumulative chord-length table of one edge, `(parameter fraction, arc
5107/// length)` at uniform fractions.  The sample count doubles until two
5108/// successive total-length estimates agree within `tol` (chord length
5109/// converges O(N⁻²) for smooth curves, so the agreement of the N and 2N
5110/// estimates bounds the remaining error at the same order); straight edges
5111/// converge on the first doubling.  The 16-sample start resolves any
5112/// single-span arc of up to half a turn to sub-percent before refinement; the
5113/// 4096 cap (8 doublings) guards adversarial curves — beyond it the table is
5114/// two orders denser than the blend march's station grid, so finer chords
5115/// cannot move any station's sampled radius meaningfully.
5116fn edge_arc_table(
5117    curve: &NurbsCurve,
5118    t0: f64,
5119    t1: f64,
5120    tol: f64,
5121) -> Result<(Vec<(f64, f64)>, f64), KernelRefusal> {
5122    let evaluate = |t: f64| curve.evaluate(t).or_refuse(KernelStage::Collect, "arc_table");
5123    let build = |n: usize| -> Result<(Vec<(f64, f64)>, f64), KernelRefusal> {
5124        let mut table = Vec::with_capacity(n + 1);
5125        let mut cumulative = 0.0;
5126        let mut previous = evaluate(t0)?;
5127        table.push((0.0, 0.0));
5128        for j in 1..=n {
5129            let fraction = j as f64 / n as f64;
5130            let point = evaluate(t0 + (t1 - t0) * fraction)?;
5131            cumulative += point.sub(previous).length();
5132            previous = point;
5133            table.push((fraction, cumulative));
5134        }
5135        Ok((table, cumulative))
5136    };
5137    let mut n = 16usize;
5138    let (mut table, mut length) = build(n)?;
5139    while n < 4096 {
5140        n *= 2;
5141        let (next_table, next_length) = build(n)?;
5142        let converged = (next_length - length).abs() <= tol;
5143        table = next_table;
5144        length = next_length;
5145        if converged {
5146            break;
5147        }
5148    }
5149    Ok((table, length))
5150}
5151
5152/// Arc length from the edge's t0 end at `fraction` of its parameter span,
5153/// linearly interpolated in the uniform chord table.
5154fn arc_length_at_fraction(table: &[(f64, f64)], fraction: f64) -> f64 {
5155    let fraction = fraction.clamp(0.0, 1.0);
5156    let intervals = table.len() - 1;
5157    let scaled = fraction * intervals as f64;
5158    let index = (scaled.floor() as usize).min(intervals - 1);
5159    let local = scaled - index as f64;
5160    let (_, a) = table[index];
5161    let (_, b) = table[index + 1];
5162    a + (b - a) * local
5163}
5164
5165/// Resolve the selected edges and order them into ONE OPEN CHAIN with
5166/// cumulative arc-length abscissas.  The chain starts at the free endpoint
5167/// belonging to the EARLIEST-selected end edge (so users get the natural
5168/// "first pick carries the law start" orientation); a single selected edge is
5169/// its own chain oriented t0→t1 (which also admits a closed edge — the law's
5170/// end radii must then match, enforced downstream by `blend_edge_variable`).
5171/// Branching (a vertex shared by 3+ selected edges), closed rings of several
5172/// edges, and disconnected selections refuse with named errors.
5173fn resolve_selected_chain(
5174    solid: &BrepSolid,
5175    edge_points: &[Vec3],
5176    entry: &str,
5177    tol: f64,
5178) -> Result<Vec<ChainLink>, KernelRefusal> {
5179    // Endpoint identity uses the kernel-wide COINCIDENCE_DISTANCE_FLOOR — the
5180    // same band the constant-radius group's corner detector applies.
5181    let band = crate::tolerance::COINCIDENCE_DISTANCE_FLOOR;
5182
5183    struct Resolved {
5184        edge_id: u64,
5185        start: Vec3,
5186        end: Vec3,
5187        arc: Vec<(f64, f64)>,
5188        length: f64,
5189    }
5190    let mut resolved: Vec<Resolved> = Vec::with_capacity(edge_points.len());
5191    for point in edge_points {
5192        let edge_id = resolve_edge_by_point(solid, *point)?;
5193        if resolved.iter().any(|r| r.edge_id == edge_id) {
5194            return Err(KernelRefusal::input(
5195                KernelStage::Collect,
5196                "duplicate_edge",
5197                format!("{entry}: the same edge was selected more than once"),
5198            ));
5199        }
5200        let edge = solid
5201            .edges
5202            .iter()
5203            .find(|e| e.id == edge_id)
5204            .ok_or_else(|| {
5205                KernelRefusal::internal(
5206                    KernelStage::Collect,
5207                    "chain_resolved_edge",
5208                    format!("{entry}: resolved edge vanished"),
5209                )
5210            })?;
5211        let (arc, length) = edge_arc_table(&edge.curve, edge.t0, edge.t1, tol)?;
5212        if !(length > 0.0) {
5213            return Err(KernelRefusal::input(
5214                KernelStage::Collect,
5215                "zero_length_edge",
5216                format!("{entry}: selected edge has zero length"),
5217            ));
5218        }
5219        resolved.push(Resolved {
5220            edge_id,
5221            start: edge
5222                .curve
5223                .evaluate(edge.t0)
5224                .or_refuse(KernelStage::Collect, "chain_edge_start")?,
5225            end: edge
5226                .curve
5227                .evaluate(edge.t1)
5228                .or_refuse(KernelStage::Collect, "chain_edge_end")?,
5229            arc,
5230            length,
5231        });
5232    }
5233    let n = resolved.len();
5234    if n == 1 {
5235        let only = resolved.remove(0);
5236        return Ok(vec![ChainLink {
5237            input_index: 0,
5238            forward: true,
5239            arc: only.arc,
5240            length: only.length,
5241            abscissa: 0.0,
5242        }]);
5243    }
5244
5245    // Cluster the 2n endpoints; each entry is (edge index, is_start_end).
5246    let mut clusters: Vec<(Vec3, Vec<(usize, bool)>)> = Vec::new();
5247    for (i, r) in resolved.iter().enumerate() {
5248        for (point, is_start) in [(r.start, true), (r.end, false)] {
5249            match clusters
5250                .iter_mut()
5251                .find(|(anchor, _)| anchor.sub(point).length() < band)
5252            {
5253                Some((_, members)) => members.push((i, is_start)),
5254                None => clusters.push((point, vec![(i, is_start)])),
5255            }
5256        }
5257    }
5258    if clusters.iter().any(|(_, members)| members.len() > 2) {
5259        return Err(KernelRefusal::input(
5260            KernelStage::Collect,
5261            "chain_branching",
5262            format!(
5263                "{entry}: selected edges must form one open chain \
5264                 (a vertex is shared by three or more selected edges)"
5265            ),
5266        ));
5267    }
5268    let free: Vec<usize> = clusters
5269        .iter()
5270        .enumerate()
5271        .filter(|(_, (_, members))| members.len() == 1)
5272        .map(|(c, _)| c)
5273        .collect();
5274    if free.len() != 2 {
5275        return Err(KernelRefusal::input(
5276            KernelStage::Collect,
5277            "chain_open",
5278            format!(
5279                "{entry}: selected edges must form one OPEN chain \
5280                 (closed rings and disconnected selections are not supported)"
5281            ),
5282        ));
5283    }
5284    // Start at the free end whose edge appears EARLIEST in the selection.
5285    let start_cluster = *free
5286        .iter()
5287        .min_by_key(|&&c| clusters[c].1[0].0)
5288        .expect("two free ends");
5289
5290    // Walk the chain.
5291    let mut links: Vec<ChainLink> = Vec::with_capacity(n);
5292    let mut visited = vec![false; n];
5293    let mut abscissa = 0.0_f64;
5294    let mut cluster = start_cluster;
5295    for _ in 0..n {
5296        let Some(&(edge_index, entered_at_start)) = clusters[cluster]
5297            .1
5298            .iter()
5299            .find(|(edge_index, _)| !visited[*edge_index])
5300        else {
5301            return Err(KernelRefusal::input(
5302                KernelStage::Collect,
5303                "chain_walk",
5304                format!(
5305                    "{entry}: selected edges are not connected into one chain"
5306                ),
5307            ));
5308        };
5309        visited[edge_index] = true;
5310        let r = &resolved[edge_index];
5311        links.push(ChainLink {
5312            input_index: edge_index,
5313            forward: entered_at_start,
5314            arc: r.arc.clone(),
5315            length: r.length,
5316            abscissa,
5317        });
5318        abscissa += r.length;
5319        let exit_point = if entered_at_start { r.end } else { r.start };
5320        cluster = clusters
5321            .iter()
5322            .position(|(anchor, _)| anchor.sub(exit_point).length() < band)
5323            .ok_or_else(|| {
5324                KernelRefusal::internal(
5325                    KernelStage::Collect,
5326                    "chain_cluster",
5327                    format!("{entry}: chain walk lost an endpoint cluster"),
5328                )
5329            })?;
5330    }
5331    if visited.iter().any(|v| !v) {
5332        return Err(KernelRefusal::input(
5333            KernelStage::Collect,
5334            "chain_connected",
5335            format!(
5336                "{entry}: selected edges are not connected into one chain"
5337            ),
5338        ));
5339    }
5340    Ok(links)
5341}
5342
5343/// Sample the law into one edge's `(parameter fraction, radius)` stop list —
5344/// the caller-side bridge from chain abscissa into the `radius_at` closure
5345/// seam that `blend_edge_variable` builds over its stops.
5346///
5347/// `scale` maps chain abscissa into the law's own abscissa units
5348/// (`law.total_length() / chain_length` — proportional, so a law built from
5349/// the measured chain lengths maps 1:1).  The base stop count derives from
5350/// the law's curvature: piecewise-linear sampling of a C1, piecewise-C2
5351/// function over step `h` errs at most `h²·max|r''|/8`, so
5352/// `h = sqrt(8·tol/max|r''|)` holds the sampling error under the SSI fit
5353/// tolerance the variable lane is built to.  That bound is exact for
5354/// arc-length-linear (straight) edges; curved edges bend the
5355/// parameter→abscissa map, so each interval is additionally midpoint-checked
5356/// against the law and bisected on violation (up to 8 halvings — a 4⁸ ≈ 6·10⁴
5357/// error reduction, decisive for any C1 law).  The base count is capped at
5358/// 256 intervals: 4× the blend march's 64-station density
5359/// (blend/stations.rs), beyond which denser stops cannot move any station's
5360/// sampled radius by more than the fit tolerance.
5361fn law_stops_for_link(
5362    link: &ChainLink,
5363    law: &crate::law::RadiusLaw,
5364    scale: f64,
5365    tol: f64,
5366) -> Vec<(f64, f64)> {
5367    let radius_at_fraction = |fraction: f64| -> f64 {
5368        let arc = arc_length_at_fraction(&link.arc, fraction);
5369        let chain_s = if link.forward {
5370            link.abscissa + arc
5371        } else {
5372            link.abscissa + (link.length - arc)
5373        };
5374        law.radius_at(chain_s * scale)
5375    };
5376    // Curvature of the law in edge-fraction units: d²r/df² ≤
5377    // max|r''|·(scale·length)² for the arc-length-linear map.
5378    let curvature = law
5379        .max_second_derivative(link.abscissa * scale, (link.abscissa + link.length) * scale)
5380        * (scale * link.length).powi(2);
5381    let base = if curvature * 0.125 <= tol {
5382        1usize
5383    } else {
5384        ((curvature / (8.0 * tol)).sqrt().ceil() as usize).clamp(1, 256)
5385    };
5386    let mut stops: Vec<(f64, f64)> = (0..=base)
5387        .map(|j| {
5388            let fraction = j as f64 / base as f64;
5389            (fraction, radius_at_fraction(fraction))
5390        })
5391        .collect();
5392    // Midpoint refinement for curved parameter→abscissa maps.
5393    let mut depth = 0usize;
5394    while depth < 8 {
5395        let mut refined: Vec<(f64, f64)> = Vec::with_capacity(stops.len());
5396        let mut inserted = false;
5397        for pair in stops.windows(2) {
5398            refined.push(pair[0]);
5399            let mid_fraction = 0.5 * (pair[0].0 + pair[1].0);
5400            let law_mid = radius_at_fraction(mid_fraction);
5401            let linear_mid = 0.5 * (pair[0].1 + pair[1].1);
5402            if (law_mid - linear_mid).abs() > tol {
5403                refined.push((mid_fraction, law_mid));
5404                inserted = true;
5405            }
5406        }
5407        refined.push(*stops.last().expect("at least two stops"));
5408        stops = refined;
5409        if !inserted {
5410            break;
5411        }
5412        depth += 1;
5413    }
5414    stops
5415}
5416
5417/// Fillet (or chamfer) a chain of edges under a composable radius law
5418/// evaluated on the chain's cumulative arc-length abscissa (the OCCT
5419/// `Law_Composite` model; see [`crate::law::RadiusLaw`]).  The selected edges
5420/// must form ONE OPEN CHAIN (or be a single edge); the chain starts at the
5421/// free end of the earliest-selected end edge, and the law's abscissa maps
5422/// proportionally onto the chain's measured arc length (a law built with the
5423/// chain's own lengths — e.g. [`crate::law::RadiusLaw::from_vertex_radii`] —
5424/// maps 1:1).  Endpoint radii are met exactly; radii at shared chain vertices
5425/// match by the law's continuity, so the per-edge blends miter through the
5426/// corners; a chain whose blends cannot be mitered REFUSES rather than
5427/// distorting the law through the sequential rebuild.
5428pub fn fillet_edges_variable_law(
5429    solid: &BrepSolid,
5430    edge_points: &[Vec3],
5431    edge_names: Option<&[String]>,
5432    law: &crate::law::RadiusLaw,
5433    chamfer: bool,
5434    name: Option<&str>,
5435) -> Result<BrepSolid, KernelRefusal> {
5436    // One blend operation: the reports of an earlier one, never consumed, are
5437    // dropped as it starts (nested calls keep this operation's).
5438    let _operation = crate::blend::BlendOperation::enter();
5439    const ENTRY: &str = "fillet_edges_variable_law";
5440    if edge_points.is_empty() {
5441        return Err(KernelRefusal::input(
5442            KernelStage::Collect,
5443            "law_selection",
5444            format!("{ENTRY}: no edges selected"),
5445        ));
5446    }
5447    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
5448    let chain = resolve_selected_chain(solid, edge_points, ENTRY, tolerances.intersection_fit)?;
5449    fillet_variable_law_on_chain(
5450        solid,
5451        edge_points,
5452        edge_names,
5453        &chain,
5454        law,
5455        chamfer,
5456        name,
5457        ENTRY,
5458        tolerances.intersection_fit,
5459    )
5460}
5461
5462/// The natural per-vertex user model: radius `vertex_radii[i]` at chain
5463/// vertex `i` (in CHAIN order, starting at the free end of the
5464/// earliest-selected edge), smoothly interpolated along the chain
5465/// (monotone C1 — every vertex radius met exactly, no overshoot).  Requires
5466/// exactly one radius per chain vertex (`edges + 1`).
5467pub fn fillet_edges_variable_vertex_radii(
5468    solid: &BrepSolid,
5469    edge_points: &[Vec3],
5470    edge_names: Option<&[String]>,
5471    vertex_radii: &[f64],
5472    chamfer: bool,
5473    name: Option<&str>,
5474) -> Result<BrepSolid, KernelRefusal> {
5475    // One blend operation: the reports of an earlier one, never consumed, are
5476    // dropped as it starts (nested calls keep this operation's).
5477    let _operation = crate::blend::BlendOperation::enter();
5478    const ENTRY: &str = "fillet_edges_variable_vertex_radii";
5479    if edge_points.is_empty() {
5480        return Err(KernelRefusal::input(
5481            KernelStage::Collect,
5482            "vertex_radii_selection",
5483            format!("{ENTRY}: no edges selected"),
5484        ));
5485    }
5486    let tolerances = crate::KernelTolerances::for_solid(solid, 1e-7);
5487    let chain = resolve_selected_chain(solid, edge_points, ENTRY, tolerances.intersection_fit)?;
5488    let lengths: Vec<f64> = chain.iter().map(|link| link.length).collect();
5489    let law = crate::law::RadiusLaw::from_vertex_radii(&lengths, vertex_radii)
5490        .map_err(|error| error.with_message(|error| format!("{ENTRY}: {error}")))?;
5491    fillet_variable_law_on_chain(
5492        solid,
5493        edge_points,
5494        edge_names,
5495        &chain,
5496        &law,
5497        chamfer,
5498        name,
5499        ENTRY,
5500        tolerances.intersection_fit,
5501    )
5502}
5503
5504/// Shared law-entry tail: sample per-edge stop lists from the law over the
5505/// resolved chain and run the variable group core (miter-or-refuse: no
5506/// sequential fallback for tapered chains — see `fillet_edges_variable_impl`).
5507#[allow(clippy::too_many_arguments)]
5508fn fillet_variable_law_on_chain(
5509    solid: &BrepSolid,
5510    edge_points: &[Vec3],
5511    edge_names: Option<&[String]>,
5512    chain: &[ChainLink],
5513    law: &crate::law::RadiusLaw,
5514    chamfer: bool,
5515    name: Option<&str>,
5516    entry: &str,
5517    tol: f64,
5518) -> Result<BrepSolid, KernelRefusal> {
5519    let chain_length: f64 = chain.iter().map(|link| link.length).sum();
5520    let scale = law.total_length() / chain_length;
5521    let mut per_edge_stops: Vec<Vec<(f64, f64)>> = vec![Vec::new(); edge_points.len()];
5522    for link in chain {
5523        per_edge_stops[link.input_index] = law_stops_for_link(link, law, scale, tol);
5524    }
5525    fillet_edges_variable_impl(
5526        solid,
5527        edge_points,
5528        edge_names,
5529        &per_edge_stops,
5530        chamfer,
5531        name,
5532        entry,
5533        false,
5534    )
5535}
5536
5537/// Asymmetric (two-distance) chamfer of a GROUP of edges, the app entry: each
5538/// selected edge (resolved by a point on it) gets a `d1 × d2` bevel (§6.11).
5539/// Edges are chamfered independently — asymmetric chamfers keep sharp vertices,
5540/// so there is no shared-corner blending.
5541pub fn chamfer_edges_asymmetric(
5542    solid: &BrepSolid,
5543    edge_points: &[Vec3],
5544    edge_names: Option<&[String]>,
5545    d1: f64,
5546    d2: f64,
5547    name: Option<&str>,
5548) -> Result<BrepSolid, KernelRefusal> {
5549    // One blend operation: the reports of an earlier one, never consumed, are
5550    // dropped as it starts (nested calls keep this operation's).
5551    let _operation = crate::blend::BlendOperation::enter();
5552    if edge_points.is_empty() {
5553        return Err(KernelRefusal::input(
5554            KernelStage::Collect,
5555            "asymmetric_selection",
5556            "chamfer_edges_asymmetric: no edges selected",
5557        ));
5558    }
5559    let mut result = solid.clone();
5560    let mut done = vec![false; edge_points.len()];
5561    // `edge_names[index]` is keyed by INPUT position; the loop resolves each
5562    // point on the EVOLVING `result`, but enumerates the input points in order,
5563    // so the index alignment holds.
5564    for (index, point) in edge_points.iter().enumerate() {
5565        if done[index] {
5566            continue;
5567        }
5568        let edge_id = resolve_edge_by_point(&result, *point)?;
5569        let edge_name = per_edge_name(edge_names, name, index);
5570        // A smooth chain the selection covers whole is chamfered as one unit
5571        // (its setbacks run on through the tangent joins).
5572        if chamfer_asym_curved_on() {
5573            if let Some(members) = selected_chain(&result, edge_id, edge_points, &done)? {
5574                let faces = setback_faces(&result, edge_id)?;
5575                let law = crate::blend::setback::SetbackLaw::Distances { faces, distances: [d1, d2] };
5576                result = chamfer_by_setback_law(&result, edge_id, law, edge_name, "chamfer_edges_asymmetric", true)?;
5577                for member in members {
5578                    done[member] = true;
5579                }
5580                continue;
5581            }
5582        }
5583        result = chamfer_edge_asymmetric(&result, edge_id, d1, d2, edge_name)?;
5584        done[index] = true;
5585    }
5586    refuse_invalid_result(&result, "chamfer_edges_asymmetric")?;
5587    Ok(result)
5588}
5589
5590/// Distance-angle chamfer of a GROUP of edges, the app entry: each selected
5591/// edge (resolved by a point on it) gets a setback `d1` on face 1 and a chamfer
5592/// face at `angle_rad` from face 1 (§6.11); `d2` is constructed per edge.
5593pub fn chamfer_edges_angle(
5594    solid: &BrepSolid,
5595    edge_points: &[Vec3],
5596    edge_names: Option<&[String]>,
5597    d1: f64,
5598    angle_rad: f64,
5599    name: Option<&str>,
5600) -> Result<BrepSolid, KernelRefusal> {
5601    // One blend operation: the reports of an earlier one, never consumed, are
5602    // dropped as it starts (nested calls keep this operation's).
5603    let _operation = crate::blend::BlendOperation::enter();
5604    if edge_points.is_empty() {
5605        return Err(KernelRefusal::input(
5606            KernelStage::Collect,
5607            "angle_selection",
5608            "chamfer_edges_angle: no edges selected",
5609        ));
5610    }
5611    let mut result = solid.clone();
5612    let mut done = vec![false; edge_points.len()];
5613    for (index, point) in edge_points.iter().enumerate() {
5614        if done[index] {
5615            continue;
5616        }
5617        let edge_id = resolve_edge_by_point(&result, *point)?;
5618        let edge_name = per_edge_name(edge_names, name, index);
5619        // A smooth chain the selection covers whole is chamfered as one unit,
5620        // as `chamfer_edges_asymmetric` does.
5621        if chamfer_asym_curved_on() && d1 > 0.0 && d1.is_finite() && angle_rad > 1e-9 && angle_rad < std::f64::consts::PI {
5622            if let Some(members) = selected_chain(&result, edge_id, edge_points, &done)? {
5623                let [first, _] = setback_faces(&result, edge_id)?;
5624                let law = crate::blend::setback::SetbackLaw::Angle { first, distance: d1, angle: angle_rad };
5625                result = chamfer_by_setback_law(&result, edge_id, law, edge_name, "chamfer_edges_angle", true)?;
5626                for member in members {
5627                    done[member] = true;
5628                }
5629                continue;
5630            }
5631        }
5632        result = chamfer_edge_angle(&result, edge_id, d1, angle_rad, edge_name)?;
5633        done[index] = true;
5634    }
5635    refuse_invalid_result(&result, "chamfer_edges_angle")?;
5636    Ok(result)
5637}
5638
5639/// Debug aid (`BREP_DEBUG_NETWORK`): every face loop as its coedge walk, with
5640/// each edge's stored vertices, so a loop the surgery left open can be read
5641/// against the input it was built from.
5642fn dump_loops_debug(label: &str, solid: &BrepSolid) {
5643    for shell in &solid.shells {
5644        for face in &shell.faces {
5645            for (index, loop_record) in face.loops.iter().enumerate() {
5646                let walk: Vec<String> = loop_record
5647                    .coedges
5648                    .iter()
5649                    .map(|coedge| {
5650                        // The pcurve's walk endpoints in the face's (u, v), so a
5651                        // loop that closes in space but not in parameter space
5652                        // (a periodic carrier's seam) is visible in the dump.
5653                        let uv = coedge
5654                            .pcurve
5655                            .domain()
5656                            .ok()
5657                            .and_then(|[q0, q1]| {
5658                                let a = coedge.pcurve.evaluate(q0).ok()?;
5659                                let b = coedge.pcurve.evaluate(q1).ok()?;
5660                                Some(format!("uv[({:.4},{:.4})->({:.4},{:.4})]", a.x, a.y, b.x, b.y))
5661                            })
5662                            .unwrap_or_default();
5663                        match solid.edges.iter().find(|e| e.id == coedge.edge_id) {
5664                            Some(edge) => format!(
5665                                "c{}:e{}{}({}->{}){uv}",
5666                                coedge.id,
5667                                edge.id,
5668                                if coedge.forward { "+" } else { "-" },
5669                                edge.start_vertex_id,
5670                                edge.end_vertex_id
5671                            ),
5672                            None => format!("c{}:e{}?MISSING", coedge.id, coedge.edge_id),
5673                        }
5674                    })
5675                    .collect();
5676                eprintln!(
5677                    "{label} face {} ({:?}) loop {index}: {}",
5678                    face.id,
5679                    face.name,
5680                    walk.join(" ")
5681                );
5682            }
5683        }
5684    }
5685}
5686
5687