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