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