Skip to main content

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