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