Skip to main content

brep_kernel/blending/blend/edge/
closed.rs

1use crate::{KernelRefusal, KernelStage, OrRefuse};
2use super::*;
3
4/// General closed-edge rolling-ball fillet or chamfer by direct §6.9 topology
5/// surgery. The refusal class of a concave closed rim whose fill overruns the
6/// plane it stands on (lane L, 2026-10-16).
7pub(crate) const CONCAVE_RIM_OVERRUN_WHAT: &str = "concave_rim_overrun";
8
9/// Lane L (2026-10-16): a CONCAVE closed rim standing on a PLANE — the rim one of
10/// the plane's INNER loops (a boss on a plate) — whose fill reaches past the
11/// plane's OUTER loop is not a face consumed up to one preserved far edge: the
12/// fill overruns the plate, and the body owed is that fill clipped by the plate's
13/// neighbouring faces. The edge-preserving construction found four "far" edges
14/// there and said "ambiguous preserved boundary edge". Read geometrically: the rim
15/// sampled, each sample stepped `radius` into the plane square to the rim (the
16/// fill's contact for a boss standing square to the plane), tested against the
17/// outer loop as a polygon in the plane (the chart clamps; the loop does not).
18/// `BREP_CONCAVE_RIM_TRUE_CONTACTS` (default on; `=0` restores the estimate): the
19/// overrun test reads the march's own contacts on the plate where it has them, not
20/// a point a whole radius from the rim. The radius is the contact's reach only
21/// where the wall stands square to the plate; against a ball (a ball standing on a
22/// plate, its rim rounded by 3) the contact lies nearer, at `√((R + r)² − r²) −
23/// R`, 2.416 against 3, and the fill that fits was refused.
24fn concave_rim_true_contacts_on() -> bool {
25    switch!("BREP_CONCAVE_RIM_TRUE_CONTACTS", true)
26}
27
28fn concave_rim_overrun(
29    solid: &BrepSolid,
30    edge: &EdgeRecord,
31    mates: [(&FaceRecord, usize); 2],
32    radius: f64,
33    contacts: Option<[Vec<Vec3>; 2]>,
34) -> Result<Option<KernelRefusal>, KernelRefusal> {
35    const RIM_SAMPLES: usize = 64;
36    const LOOP_SAMPLES: usize = 256;
37    if edge.start_vertex_id != edge.end_vertex_id {
38        return Ok(None);
39    }
40    for (index, (face, rim_loop)) in mates.iter().copied().enumerate() {
41        if rim_loop == 0 {
42            continue;
43        }
44        let Some(crate::AnalyticSurface::Plane { origin, u_dir, v_dir, .. }) = face.surface.analytic() else { continue };
45        let wall = mates[1 - index].0;
46        let e1 = u_dir.normalized().or_refuse(KernelStage::Classify, "normalized")?;
47        let normal = u_dir.cross(*v_dir).normalized().or_refuse(KernelStage::Classify, "normalized")?;
48        let e2 = normal.cross(e1);
49        let flat = |p: Vec3| -> (f64, f64) { let d = p.sub(*origin); (d.dot(e1), d.dot(e2)) };
50        // The outer loop and the rim's own loop as polygons in the plane.
51        let polygon = |loop_index: usize| -> Result<Vec<(f64, f64)>, KernelRefusal> {
52            let mut points: Vec<(f64, f64)> = Vec::new();
53            for coedge in &face.loops[loop_index].coedges {
54                let Some(boundary) = solid.edges.iter().find(|candidate| candidate.id == coedge.edge_id) else { continue };
55                for k in 0..LOOP_SAMPLES {
56                    let f = k as f64 / LOOP_SAMPLES as f64;
57                    let t = if coedge.forward { boundary.t0 + (boundary.t1 - boundary.t0) * f } else { boundary.t1 - (boundary.t1 - boundary.t0) * f };
58                    points.push(flat(boundary.curve.evaluate(t).or_refuse(KernelStage::Classify, "evaluate")?));
59                }
60            }
61            Ok(points)
62        };
63        let (outer, rim_polygon) = (polygon(0)?, polygon(rim_loop)?);
64        let within = |points: &[(f64, f64)], x: f64, y: f64| -> bool {
65            crate::polygon::parity_inside([x, y], points.len(), |k| [points[k].0, points[k].1])
66        };
67        // The plate's region about the rim: inside the outer loop, outside the
68        // rim's own loop (where the boss stands).
69        let inside = |x: f64, y: f64| -> bool { within(&outer, x, y) && !within(&rim_polygon, x, y) };
70        // Concave: at a rim sample the wall's OUTWARD normal points into the
71        // plate's region (a boss facing out over its plate); a hole's wall
72        // faces its axis (convex) and is not this class.
73        {
74            let derivatives = edge.curve.derivatives(edge.t0, 1).or_refuse(KernelStage::Classify, "derivatives")?;
75            let (point, tangent) = (derivatives[0], derivatives[1]);
76            let side = normal.cross(tangent).normalized().or_refuse(KernelStage::Classify, "normalized")?;
77            // A twentieth of the radius: well past the sampled loops' chord
78            // sag, well inside the fill's own reach.
79            let probe = radius * 0.05;
80            let (px, py) = flat(point.add(side.scale(probe)));
81            let toward = if inside(px, py) { side } else { side.scale(-1.0) };
82            let foot = crate::project_point_to_surface(&wall.surface, point).or_refuse(KernelStage::Classify, "project_point_to_surface")?;
83            let wall_normal = wall.surface.normal(foot.u, foot.v).or_refuse(KernelStage::Classify, "normal")?;
84            let outward = if wall.same_sense { wall_normal } else { wall_normal.scale(-1.0) };
85            if outward.dot(toward) <= 0.0 {
86                continue;
87            }
88        }
89        let mut overruns = false;
90        if let (true, Some(contacts)) = (concave_rim_true_contacts_on(), contacts.as_ref()) {
91            // A contact ON the outer loop (a fill that just touches the
92            // plate's edge, tangent to it) has not overrun it: the parity
93            // test cannot say which side such a point is on, so its distance
94            // to the loop decides.
95            let on_loop = |x: f64, y: f64| -> bool {
96                let band = 1e-7 * (1.0 + x.abs() + y.abs());
97                (0..outer.len()).any(|k| {
98                    let (a, b) = (outer[k], outer[(k + 1) % outer.len()]);
99                    let (dx, dy) = (b.0 - a.0, b.1 - a.1);
100                    let length2 = dx * dx + dy * dy;
101                    let t = if length2 > 0.0 { (((x - a.0) * dx + (y - a.1) * dy) / length2).clamp(0.0, 1.0) } else { 0.0 };
102                    (x - a.0 - t * dx).hypot(y - a.1 - t * dy) <= band
103                })
104            };
105            for contact in &contacts[index] {
106                let (x, y) = flat(*contact);
107                if !within(&outer, x, y) && !on_loop(x, y) {
108                    overruns = true;
109                    break;
110                }
111            }
112        } else {
113        for k in 0..RIM_SAMPLES {
114            let t = edge.t0 + (edge.t1 - edge.t0) * (k as f64 + 0.5) / RIM_SAMPLES as f64;
115            let derivatives = edge.curve.derivatives(t, 1).or_refuse(KernelStage::Classify, "derivatives")?;
116            let (point, tangent) = (derivatives[0], derivatives[1]);
117            let Ok(side) = normal.cross(tangent).normalized() else { continue };
118            // Into the plate: of the two in-plane normals to the rim, the one a
119            // small step along which stays inside the outer loop's region.
120            // A twentieth of the radius: well past the sampled loops' chord
121            // sag, well inside the fill's own reach.
122            let probe = radius * 0.05;
123            let toward = if inside(flat(point.add(side.scale(probe))).0, flat(point.add(side.scale(probe))).1) { side } else { side.scale(-1.0) };
124            let contact = flat(point.add(toward.scale(radius)));
125            if !within(&outer, contact.0, contact.1) {
126                overruns = true;
127                break;
128            }
129        }
130        }
131        if overruns {
132            return Ok(Some(KernelRefusal::unsupported(KernelStage::Classify, CONCAVE_RIM_OVERRUN_WHAT, format!(
133                "blend: the concave rim fill overruns the face's outer boundary — rolling on rim edge {}, the ball's contact on the plane {} it stands on (radius {radius} from the rim) reaches past that plane's outer loop, so the fill must be clipped by the plane's neighbouring faces, which this lane does not build",
134                edge.id,
135                face.name.clone().unwrap_or_else(|| format!("{}", face.id)),
136            ))));
137        }
138    }
139    Ok(None)
140}
141
142pub fn blend_closed_edge(
143    solid: &BrepSolid,
144    edge_id: u64,
145    radius: f64,
146    chamfer: bool,
147    name: Option<&str>,
148) -> Result<BrepSolid, KernelRefusal> {
149    // One blend operation: the reports of an earlier one, never consumed, are
150    // dropped as it starts (nested calls keep this operation's).
151    let _operation = crate::blend::BlendOperation::enter();
152    if !(radius > 0.0) || !radius.is_finite() {
153        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
154    }
155    blend_closed_edge_impl(solid, edge_id, &|_| radius, Some(radius), chamfer, name)
156}
157
158/// [`blend_closed_edge`] with the closed-rim support refit's KNOT-AWARE retry
159/// (lane L, 2026-10-16): where a support pcurve's uniform track misses the floor,
160/// the fit is retried on a track that also samples the rail's own knots
161/// (`project_piece_pcurve_within_knot_retry`). Only for a caller whose refusal is
162/// TERMINAL for the whole operation — the fillet tool's last rung
163/// (`fillet/tool.rs`, `lcount201_knot_aware_last_rung_20261016`) on a refusal
164/// [`is_pcurve_floor_refusal`] reads: roads that call `blend_closed_edge` per
165/// rung and recover a floor miss themselves (the stadium, half-torus and box
166/// ladders) never see it.
167pub fn blend_closed_edge_knot_aware(
168    solid: &BrepSolid,
169    edge_id: u64,
170    radius: f64,
171    chamfer: bool,
172    name: Option<&str>,
173) -> Result<BrepSolid, KernelRefusal> {
174    let _operation = crate::blend::BlendOperation::enter();
175    if !(radius > 0.0) || !radius.is_finite() {
176        return Err(KernelRefusal::input(KernelStage::Collect, "radius", "blend: radius must be positive"));
177    }
178    KNOT_RETRY.with(|flag| flag.set(true));
179    let built = blend_closed_edge_impl(solid, edge_id, &|_| radius, Some(radius), chamfer, name);
180    KNOT_RETRY.with(|flag| flag.set(false));
181    built
182}
183
184/// A refusal for a support pcurve that does not reach the refinement floor —
185/// read off its CLASS and code (`CHAIN_PCURVE_FLOOR_WHAT`,
186/// `CLOSED_SUPPORT_PCURVE_FLOOR_WHAT`), never its wording.
187pub fn is_pcurve_floor_refusal(refusal: &KernelRefusal) -> bool {
188    matches!(&refusal.class, crate::RefusalClass::NonConvergence { what }
189        if what == crate::blend::chain::CHAIN_PCURVE_FLOOR_WHAT || what == CLOSED_SUPPORT_PCURVE_FLOOR_WHAT)
190}
191
192/// The code of a closed-rim support refit that misses the floor as shipped.
193pub(crate) const CLOSED_SUPPORT_PCURVE_FLOOR_WHAT: &str = "closed_support_pcurve_floor";
194
195/// Variable-radius blend (4.9.5): radius stops as (edge fraction, radius)
196/// pairs, linearly interpolated along the edge parameter and clamped at
197/// the ends.  Closed edges must supply matching first/last radii.
198pub fn blend_edge_variable(
199    solid: &BrepSolid,
200    edge_id: u64,
201    radii: &[(f64, f64)],
202    chamfer: bool,
203    name: Option<&str>,
204) -> Result<BrepSolid, KernelRefusal> {
205    // One blend operation: the reports of an earlier one, never consumed, are
206    // dropped as it starts (nested calls keep this operation's).
207    let _operation = crate::blend::BlendOperation::enter();
208    if radii.is_empty() || radii.iter().any(|(_, radius)| !(*radius > 0.0)) {
209        return Err(KernelRefusal::input(KernelStage::Collect, "radius_stop", "blend: every radius stop must be positive"));
210    }
211    let mut stops = radii.to_vec();
212    stops.sort_by(|a, b| a.0.total_cmp(&b.0));
213    let edge = solid
214        .edges
215        .iter()
216        .find(|edge| edge.id == edge_id)
217        .ok_or_else(|| format!("blend: edge {edge_id} not found")).or_refuse(KernelStage::Refine, "ok_or_else")?;
218    let closed = edge.start_vertex_id == edge.end_vertex_id;
219    if closed && (stops[0].1 - stops[stops.len() - 1].1).abs() > 1e-12 {
220        return Err(KernelRefusal::input(KernelStage::Collect, "closed_edge_radii", "blend: closed edges need equal first/last radii"));
221    }
222    // CONSTANT stops must DEGENERATE to the exact constant-radius
223    // machinery (§6.9 exact cylinder cutters where the mates allow them,
224    // the same general march otherwise).  The general march's fitted
225    // NURBS is geometrically exact for a constant radius, but downstream
226    // booleans treat it as a generic surface: marched SSI curves against
227    // a tangent mate drift O(√ε) along the tangency (measured 1.2e-3 on
228    // a 10-box chain miter), while the exact representation intersects
229    // analytically — this is what keeps chain-corner miters composable.
230    let first_radius = stops[0].1;
231    if stops
232        .iter()
233        .all(|(_, radius)| (radius - first_radius).abs() <= 1e-12 * (1.0 + first_radius.abs()))
234    {
235        return if chamfer {
236            crate::fillet::chamfer_edge(solid, edge_id, first_radius, name)
237        } else {
238            crate::fillet::fillet_edge(solid, edge_id, first_radius, name)
239        };
240    }
241    let (t0, t1) = (edge.t0, edge.t1);
242    let radius_at = move |t: f64| -> f64 {
243        let raw = (t - t0) / (t1 - t0);
244        // Closed edges WRAP (the anchored march may start mid-edge and run
245        // past t1 once around — clamping misplaced mid-profile stops
246        // there); open edges CLAMP flat past the ends, which is only the
247        // marched overshoot region beyond the trims.  The blend-end
248        // stations are pinned exactly at t0/t1 by the open march, so the
249        // profile kink the clamp creates sits ON an interpolation node and
250        // the fitted rows still pass through the closed-form end stations.
251        let fraction = if closed {
252            raw.rem_euclid(1.0)
253        } else {
254            raw.clamp(0.0, 1.0)
255        };
256        if fraction <= stops[0].0 {
257            return stops[0].1;
258        }
259        for pair in stops.windows(2) {
260            if fraction <= pair[1].0 {
261                let width = (pair[1].0 - pair[0].0).max(1e-12);
262                let local = (fraction - pair[0].0) / width;
263                return pair[0].1 + (pair[1].1 - pair[0].1) * local;
264            }
265        }
266        stops[stops.len() - 1].1
267    };
268    // A VARIABLE profile (constant stops left above for the constant entry):
269    // no constant-radius provenance, so no rolling-ball wall verdict.
270    if closed {
271        blend_closed_edge_impl(solid, edge_id, &radius_at, None, chamfer, name)
272    } else {
273        blend_open_edge_impl(solid, edge_id, &radius_at, None, chamfer, name)
274    }
275}
276
277/// `constant`: the radius when the blend came in through a CONSTANT-radius
278/// entry point (`blend_closed_edge`), `None` for a variable profile — the
279/// only provenance on which the wall is judged against one rolling ball.
280fn blend_closed_edge_impl(
281    solid: &BrepSolid,
282    edge_id: u64,
283    radius_at: &dyn Fn(f64) -> f64,
284    constant: Option<f64>,
285    chamfer: bool,
286    name: Option<&str>,
287) -> Result<BrepSolid, KernelRefusal> {
288    let _closed_timing = crate::blend::BlendTimer::start("timing.closed_rim_ms");
289    let prepare_timing = crate::blend::BlendTimer::start("timing.closed.prepare_ms");
290    if let Some(separated) = separate_spherical_domain_cut(solid, edge_id)? {
291        return blend_closed_edge_impl(&separated, edge_id, radius_at, constant, chamfer, name);
292    }
293    if let Some(simplified) = remove_retraced_cuts(solid, edge_id)? {
294        return blend_closed_edge_impl(&simplified, edge_id, radius_at, constant, chamfer, name);
295    }
296    let edge = solid
297        .edges
298        .iter()
299        .find(|edge| edge.id == edge_id)
300        .ok_or_else(|| format!("blend: edge {edge_id} not found")).or_refuse(KernelStage::Refine, "ok_or_else")?;
301    if edge.start_vertex_id != edge.end_vertex_id {
302        return Err(KernelRefusal::input(KernelStage::Collect, "closed_edge", "blend: general path currently requires a CLOSED edge"));
303    }
304    let (face_a, loop_a, coedge_a) = locate_mate(solid, edge_id, None)?;
305    let (face_b, loop_b, coedge_b) = locate_mate(solid, edge_id, Some((face_a.id, loop_a)))?;
306    if face_a.id == face_b.id && loop_a == loop_b {
307        return Err(KernelRefusal::unsupported(KernelStage::Classify, "seam_edge", "blend: edge is used twice by one loop (seam edge?)"));
308    }
309
310    // Seam-structured loops force the blend seam onto that carrier's seam
311    // meridian; at most one mate may need it.
312    let seam_a = face_a.loops[loop_a].coedges.len() > 1;
313    let seam_b = face_b.loops[loop_b].coedges.len() > 1;
314    let (first_face, first_loop, first_coedge, second_face, second_loop, second_coedge) =
315        if seam_a || !seam_b {
316            (face_a, loop_a, coedge_a, face_b, loop_b, coedge_b)
317        } else {
318            (face_b, loop_b, coedge_b, face_a, loop_a, coedge_a)
319        };
320    let anchored = first_face.loops[first_loop].coedges.len() > 1;
321    let second_seam = anchored && second_face.loops[second_loop].coedges.len() > 1;
322    let anchor_u = if anchored {
323        // Lock onto the carrier's seam meridian: the u-domain start.
324        Some(first_face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?[0])
325    } else {
326        None
327    };
328
329    // Signed radii from the cross-section seed at the edge midpoint.
330    let mid_radius = radius_at(edge.t0 + (edge.t1 - edge.t0) * 0.5);
331    let (rho1, rho2) = signed_radii(
332        edge,
333        first_face,
334        first_coedge,
335        second_face,
336        second_coedge,
337        mid_radius,
338    )?;
339
340    let first_mate = BlendMate {
341        face: first_face,
342        coedge: first_coedge,
343        loop_index: first_loop,
344        rho: rho1,
345    };
346    let second_mate = BlendMate {
347        face: second_face,
348        coedge: second_coedge,
349        loop_index: second_loop,
350        rho: rho2,
351    };
352    let mid_t = edge.t0 + (edge.t1 - edge.t0) * 0.5;
353    // Anchored FIRST, always — everything that already works takes this rung
354    // and is unchanged.  An anchored march freezes the first carrier's u on
355    // its seam meridian and frees t (`solve_anchored_start`), so it is only
356    // solvable when the edge actually reaches that meridian.  A closed edge
357    // cut by a plane through a surface of revolution's AXIS is one whole
358    // MERIDIAN of that carrier — constant u, a full turn in v — so no station
359    // on it can sit at the seam, and the seam may even have been trimmed off
360    // the face (the 2026-09-01 reported document: the kept torus was
361    // u ∈ [0.1369, 0.8869] while the anchor locked u = 0).  That march reports
362    // "anchored seam start did not converge"; the UNANCHORED march solves the
363    // same edge exactly, because the edge's own endpoints already sit on the
364    // carrier's OTHER (v) seam.  Retrying is what makes this a rung of the
365    // existing ladder rather than a predicate with a tolerance to tune: a
366    // march that needs its anchor still gets one.
367    use crate::blend::chain::FoldPolicy;
368    let march_with = |fold: FoldPolicy, depth_budget: usize| -> Result<Vec<Station>, KernelRefusal> {
369        match march_stations(edge, &first_mate, &second_mate, radius_at, anchor_u, fold, depth_budget) {
370            Ok(stations) => Ok(stations),
371            Err(anchored_error) if anchor_u.is_some() => {
372                march_stations(edge, &first_mate, &second_mate, radius_at, None, fold, depth_budget).map_err(
373                    |retry_error| {
374                        if crate::blend::is_wall_fold(&retry_error)
375                        || crate::blend::is_marched_fit_off_carriers(&retry_error) {
376                            retry_error
377                        } else {
378                            anchored_error
379                        }
380                    },
381                )
382            }
383            Err(anchored_error) => Err(anchored_error),
384        }
385    };
386    let rail_bar = 0.5 * crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
387    // A FILLET of one constant radius is also judged on its wall between the
388    // rails, against that ball's sweep, at the unchanged `intersection_fit`
389    // (`ClosedWallCheck`); a chamfer or a varying radius is not.
390    let wall_check = {
391        // Constant-radius PROVENANCE (the entry point), never sampled
392        // constancy: a variable profile can agree at any finite set of samples.
393        let radius = constant.unwrap_or(f64::NAN);
394        let constant = constant.is_some();
395        // The construction request as on the closed chain's plain fillet
396        // rungs: `KernelTolerances::model` on the wall between the rails.
397        let model = crate::KernelTolerances::for_solid(solid, 1e-7).model;
398        let bar = crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
399        (!chamfer && constant && radius.is_finite() && radius != 0.0).then(|| crate::blend::stations::ClosedWallCheck {
400            radius: radius.abs(),
401            bar,
402            model: model.is_finite().then_some(model),
403        })
404    };
405    crate::blend::stations::CLOSED_MODEL_UNMET.with(|slot| slot.set(None));
406    crate::blend::stations::CLOSED_REQUEST_RAILS.with(|slot| slot.set(None));
407    prepare_timing.stop();
408    let exact_revolution = crate::blend::stations::closed_revolution_axis(&first_mate, &second_mate).is_some();
409    let depth_budget = if exact_revolution { 0 } else { MAX_REFINEMENT_DEPTH };
410    if exact_revolution {
411        crate::blend::record_count("count.closed.exact_lane", 1);
412    }
413    let march_timing = crate::blend::BlendTimer::start("timing.closed.march_ms");
414    let attempt_timing = crate::blend::BlendTimer::start("timing.closed.march.anchored_fallback_ms");
415    // An asymmetric chamfer's stations come from its setback law
416    // (`blend/setback.rs`): no analytic rim (those solve the rolling ball),
417    // and a station that does not solve is the answer, not a cue for the
418    // edge-preserving construction, which builds from the radius.
419    let setback = crate::blend::setback::active();
420    let analytic = if setback.is_some() {
421        None
422    } else {
423        crate::blend::stations::analytic_rim::construct(edge, &first_mate, &second_mate, constant, chamfer, anchor_u)
424    };
425    let setback_stations = match &setback {
426        Some(law) => Some(crate::blend::setback::march_closed(solid, edge, &first_mate, &second_mate, law, anchor_u, rail_bar)?),
427        None => None,
428    };
429    let (analytic_stations, analytic_rows) = match analytic {
430        Some((stations, rows)) => (Some(stations), Some(rows)),
431        None => (None, None),
432    };
433    let analytic_stations = setback_stations.or(analytic_stations);
434    let marched = match analytic_stations.map(Ok).unwrap_or_else(|| march_stations_with_rail_bar(edge, &first_mate, &second_mate, radius_at, anchor_u, FoldPolicy::Refuse, depth_budget, rail_bar, wall_check)) {
435        Ok(stations) => {
436            std::mem::forget(attempt_timing);
437            Ok(stations)
438        }
439        Err(failure) => {
440            // Post-refinement errors return directly, before either the
441            // unanchored retry or the legacy edge-preserving construction.
442            let anchored_error = failure.into_initial()?;
443            if anchor_u.is_some() {
444                attempt_timing.stop();
445                crate::blend::record_count("count.closed.march.anchor_fallback", 1);
446                if std::env::var("BREP_DEBUG_CLOSED_RAILS").is_ok() {
447                    eprintln!("closed initial anchor fallback: edge {}: {anchored_error}", edge.id);
448                }
449                match march_stations_with_rail_bar(edge, &first_mate, &second_mate, radius_at, None, FoldPolicy::Refuse, depth_budget, rail_bar, wall_check) {
450                    Ok(stations) => Ok(stations),
451                    Err(failure) => {
452                        let retry_error = failure.into_initial()?;
453                        if crate::blend::is_wall_fold(&retry_error) { Err(retry_error) }
454                        else { Err(anchored_error) }
455                    }
456                }
457            } else { Err(anchored_error) }
458        }
459    };
460    // A wall that FOLDS through itself: the lens of the envelope inside the
461    // swept ball volume is CARVED (`blend/carve.rs`), the way the closed chain
462    // lane carves it, and the crease sewn as an inner loop of the blend face.
463    // A fold that reaches a RAIL is not a lens (nothing to keep on one side)
464    // and stays the named refusal; so does a chamfer's (a straight section
465    // has no ball centre to read the fold locus against).  The march is
466    // re-run under `FoldPolicy::Carve` so the folding wall is built; the lane
467    // then checks the fitted rows are accurate enough to carve and that the
468    // lens does not straddle the wall's own seam before anything is cut.
469    // The march's unmet construction request (if any), taken before any other
470    // march runs; it is reported only for the plain wall this lane builds
471    // from that march's stations.
472    let model_unmet = crate::blend::stations::CLOSED_MODEL_UNMET.with(|slot| slot.take());
473    let request_rails = crate::blend::stations::CLOSED_REQUEST_RAILS.with(|slot| slot.take());
474    let mut carve_fold = false;
475    // The CARVE LADDER (see below): the stations a folding wall is carved
476    // from, or the refusal that there is no wall accurate enough to carve.
477    // Shared by the march's own fold verdict and by the rows-loop verdict
478    // read after the fit (2026-10-17: `fillet-mouth-over-wall-bore-5p5-r2p2`'s
479    // F2 wall loops at the rim's midpoint without the march's centre-curve
480    // verdict ever firing).
481    let climb_carve_ladder = |error: &KernelRefusal| -> Result<Vec<Station>, KernelRefusal> {
482        let rail_bar = 0.5 * crate::KernelTolerances::for_solid(solid, 1e-7).intersection_fit;
483        let mut climbed: Option<Vec<Station>> = None;
484        let mut last_off = f64::NAN;
485        for depth_budget in MAX_REFINEMENT_DEPTH..=CARVE_MAX_REFINEMENT_DEPTH {
486            let stations = match march_with(FoldPolicy::Carve, depth_budget) {
487                Ok(stations) => stations,
488                // The Carve march did not build: the fold stays the answer.
489                Err(_) => break,
490            };
491            let parameters = crate::blend::stations::closed_station_parameters(&stations, [&first_mate.face.surface, &second_mate.face.surface]);
492            let off = match fit_closed_rows(&stations, &parameters, chamfer) {
493                Ok(rows) => rails_off_closed_carriers(&rows, &stations, &parameters, &first_mate, &second_mate)?,
494                Err(_) => break,
495            };
496            last_off = off;
497            crate::blend::carve::carve_trace(format_args!(
498                "blend closed-edge carve ladder: depth budget {depth_budget} ({} stations) leaves the rails {off:.3e} off their carriers (bar {rail_bar:.3e})",
499                stations.len()
500            ));
501            if off <= rail_bar {
502                climbed = Some(stations);
503                break;
504            }
505        }
506        climbed.ok_or_else(|| {
507            crate::blend::fold::wall_fold_refusal(
508                Vec::new(),
509                format!(
510                    "{} {} fits this edge: the wall folds, and at depth budget {CARVE_MAX_REFINEMENT_DEPTH} — the top of the closed march's carve ladder — its fitted rails still stand {last_off:.3e} off their carriers between stations against a bar of {rail_bar:.3e}, so there is no wall accurate enough to carve ({error})",
511                    crate::blend::WALL_FOLDS,
512                    radius_at(mid_t).abs()
513                ),
514            )
515        })
516    };
517    let marched = match marched {
518        Err(error)
519            if crate::blend::is_wall_fold(&error)
520                && !crate::blend::fold::is_rail_fold(&error)
521                && !chamfer =>
522        {
523            crate::blend::carve::carve_trace(format_args!(
524                "blend closed-edge: the wall folds ({error}); re-marching under Carve"
525            ));
526            match climb_carve_ladder(&error) {
527                Ok(stations) => {
528                    carve_fold = true;
529                    Ok(stations)
530                }
531                Err(refusal) => Err(refusal),
532            }
533        }
534        other => other,
535    };
536    let mut stations = match marched {
537        Ok(stations) => stations,
538        // A wall that FOLDS is refused here for the same reason an escaped
539        // march is: the edge-preserving construction would build a blend on the
540        // same folding centre curve, and if it converged it would return the
541        // very surface this refusal exists to stop.  It is not the fallback's
542        // question to answer, so the geometry is reported as-is.
543        Err(march_error) if crate::blend::is_wall_fold(&march_error)
544            || crate::blend::is_marched_fit_off_carriers(&march_error) => return Err(march_error),
545        Err(march_error) if crate::blend::is_ball_off_carrier(&march_error) => {
546            // An ESCAPED march is not a non-convergence: the tangency system
547            // had no solution at all, so no fallback can build the blend the
548            // rolling ball never made.  Report the escape itself — routing it
549            // to the edge-preserving construction below only reports THAT
550            // lane's complaint about a face it was never meant to consume
551            // ("ambiguous preserved boundary edge" on the 2026-09-10 report).
552            return Err(march_error);
553        }
554        Err(march_error) => {
555            // Lane L (2026-10-16): a concave rim overrunning its plane is
556            // named before the edge-preserving construction misreads it.
557            if let Some(refusal) = concave_rim_overrun(solid, edge, [(first_face, first_loop), (second_face, second_loop)], radius_at(mid_t), None)? {
558                return Err(refusal);
559            }
560            // A non-converging march often means the rolling ball falls off
561            // one face — try the edge-preserving construction (4.9.7).
562            return blend_closed_edge_keep(
563                solid,
564                edge,
565                &first_mate,
566                &second_mate,
567                radius_at(mid_t),
568                rho1,
569                chamfer,
570                name,
571            )
572            .or_else(|_| {
573                blend_closed_edge_keep(
574                    solid,
575                    edge,
576                    &second_mate,
577                    &first_mate,
578                    radius_at(mid_t),
579                    rho2,
580                    chamfer,
581                    name,
582                )
583            })
584            .map_err(|keep_error| {
585                format!("{march_error}; edge-preserving blend also failed: {keep_error}")
586            }).or_refuse(KernelStage::Refine, "map_err");
587        }
588    };
589    // Support-out-of-trim detection (4.9.7 trigger): a tangency track that
590    // leaves its face's trimmed region cannot be trimmed there — the far
591    // boundary must be PRESERVED instead.
592    let support_exits = |face: &FaceRecord, second_side: bool| -> bool {
593        // Adaptive marches vary the station count; keep at least the old fixed
594        // grid's ~16-probe floor while inheriting extra density where the
595        // march refined (which is where an exit would hide).
596        let stride = (stations.len() / 16).max(1);
597        stations.iter().step_by(stride).any(|station| {
598            support_exits_at(face, if second_side { station.uv2 } else { station.uv1 })
599        })
600    };
601    // The edge-preserving construction below cannot answer it (it consumes
602    // the mate up to one preserved far boundary; a rolled track has none) and
603    // on the reported bore mouth it said "ambiguous preserved boundary edge"
604    // about a face it was never meant to consume. The crossings are located
605    // and the lane declines BY NAME; the ladder falls through to the cutter
606    // as before. An exit across a sharp boundary, or onto a tangent neighbour
607    // the ball cannot roll onto, keeps the route below unchanged.
608    let exits_timing = crate::blend::BlendTimer::start("timing.closed.march.exits_ms");
609    // A mate bounded only by parallels of the rim's axis answers for all its
610    // stations with ONE probe (`support_exit_between_parallels`); any other
611    // mate, and any station near a boundary, takes the full probe scan.
612    let revolution = crate::blend::stations::closed_revolution_axis(&first_mate, &second_mate);
613    let exit_of = |face: &FaceRecord, second_side: bool| -> bool {
614        let contacts: Vec<Vec3> = stations.iter().map(|station| if second_side { station.p2 } else { station.p1 }).collect();
615        let probe = |station: usize| -> bool {
616            support_exits_at(face, if second_side { stations[station].uv2 } else { stations[station].uv1 })
617        };
618        match revolution.and_then(|axis| support_exit_between_parallels(solid, face, axis, &contacts, &probe)) {
619            Some(exit) => {
620                crate::blend::record_count("count.closed.exits_by_parallels", 1);
621                exit
622            }
623            None => support_exits(face, second_side),
624        }
625    };
626    let exits = [exit_of(first_face, false), exit_of(second_face, true)];
627    exits_timing.stop();
628    // The rollover and edge-preserving lanes below build from the ball's
629    // radius: a setback rail that leaves its face is refused here by name.
630    if setback.is_some() && (exits[0] || exits[1]) {
631        return Err(crate::blend::setback::unsupported(
632            "setback_rail_leaves_face",
633            format!(
634                "asymmetric chamfer: the rail on face {} runs off that face",
635                if exits[0] { first_face.id } else { second_face.id }
636            ),
637        ));
638    }
639    if exits[0] || exits[1] {
640        let scale = crate::blend::stations::march_model_scale(&edge.curve, edge.t0, edge.t1, radius_at(mid_t))?;
641        match crate::blend::rollover::plan_closed(solid, edge, &stations, [&first_mate, &second_mate], radius_at, scale) {
642            Ok(Some(plan)) => {
643                // The BUILD: every piece marched on its
644                // own carriers and fitted, then sewn on the crossing ribs.
645                let pieces = crate::blend::rollover::march_pieces(
646                    solid, edge, &plan, &stations, [&first_mate, &second_mate], radius_at, scale, rail_bar, chamfer, anchor_u,
647                )?;
648                let built = crate::blend::rollover::build(solid, edge, [&first_mate, &second_mate], &plan, pieces, anchor_u, name)?;
649                march_timing.stop();
650                return Ok(built);
651            }
652            Ok(None) => {}
653            Err(error) => {
654                if std::env::var("BREP_DEBUG_NETWORK").is_ok() {
655                    eprintln!("closed-rim rollover scan did not read the exit: {error}");
656                }
657            }
658        }
659    }
660    if setback.is_none() {
661        let contacts = [
662            stations.iter().map(|station| station.p1).collect::<Vec<_>>(),
663            stations.iter().map(|station| station.p2).collect::<Vec<_>>(),
664        ];
665        if let Some(refusal) = concave_rim_overrun(solid, edge, [(first_face, first_loop), (second_face, second_loop)], radius_at(mid_t), Some(contacts))? {
666            return Err(refusal);
667        }
668    }
669    if exits[1] {
670        return blend_closed_edge_keep(
671            solid,
672            edge,
673            &first_mate,
674            &second_mate,
675            radius_at(mid_t),
676            rho1,
677            chamfer,
678            name,
679        );
680    }
681    if exits[0] {
682        return blend_closed_edge_keep(
683            solid,
684            edge,
685            &second_mate,
686            &first_mate,
687            radius_at(mid_t),
688            rho2,
689            chamfer,
690            name,
691        );
692    }
693    if std::env::var("BREP_DEBUG_BLEND_MARCH").is_ok() {
694        let last = stations.len() - 1;
695        for index in [
696            0usize,
697            1.min(last),
698            2.min(last),
699            last.saturating_sub(1),
700            last,
701        ] {
702            let station = &stations[index];
703            eprintln!(
704                "station {index}: uv1=({:.6},{:.6}) uv2=({:.6},{:.6}) p1=({:.6},{:.6},{:.6}) w={:.6}",
705                station.uv1[0], station.uv1[1], station.uv2[0], station.uv2[1],
706                station.p1.x, station.p1.y, station.p1.z, station.weight,
707            );
708        }
709    }
710    march_timing.stop();
711    crate::blend::record_count("count.closed.stations", stations.len() as u64);
712    let rows_timing = crate::blend::BlendTimer::start("timing.closed.rows_ms");
713    let mut parameters = crate::blend::stations::closed_station_parameters(&stations, [&first_mate.face.surface, &second_mate.face.surface]);
714    let exact_rows = analytic_rows.map(Ok).or_else(|| exact_closed_revolution_rows(&stations, &first_mate, &second_mate, chamfer));
715    crate::blend::record_count(
716        if exact_rows.is_some() { "count.rows.exact_revolution" } else { "count.rows.fitted_closed" },
717        1,
718    );
719    let rows = match exact_rows {
720        Some(rows) => rows?,
721        None => {
722            // The support pcurves interpolate the stations' (u, v) and are
723            // read nowhere between them: on the 20-degree crossing's single
724            // closed exit edge they stood 1.01e-4 (thin carrier) and
725            // 2.6e-5 to 3.8e-5 (fat carrier) off the rails they trim, while the
726            // rails stood on their carriers to 1e-6 — the whole of a 5e-6 to
727            // 1.1e-5 shell vector-area residual and of a seam-placement-
728            // dependent volume (dumps of c5ea8fb80 and 635ef7630, read
729            // input-free). Each is refitted to its rail's own projected track
730            // at the pcurve floor, by the closed chain's support-piece fitter.
731            let fit_timing = crate::blend::BlendTimer::start("timing.closed.rows.fit_ms");
732            let mut rows = fit_closed_rows(&stations, &parameters, chamfer)?;
733            fit_timing.stop();
734            // THE ROWS-LOOP VERDICT (2026-10-17): the fitted wall itself may
735            // pass back through itself along a row where the march's
736            // centre-curve verdict never fired (`fold::check_rows_loop`;
737            // `fillet-mouth-over-wall-bore-5p5-r2p2`'s F2 wall at the rim's
738            // midpoint). Such a wall is a folding wall, and takes the same
739            // road the march's own fold verdict takes: re-marched under
740            // Carve up the ladder, and its lens carved below.
741            if !carve_fold && !chamfer {
742                if let Err(error) = crate::blend::fold::check_rows_loop(
743                    &rows, &stations, &parameters, None, radius_at(mid_t).abs(), vec![first_face.id, second_face.id], crate::solid_scale(solid),
744                ) {
745                    crate::blend::carve::carve_trace(format_args!(
746                        "blend closed-edge: the fitted rows loop ({error}); re-marching under Carve"
747                    ));
748                    stations = climb_carve_ladder(&error)?;
749                    parameters = crate::blend::stations::closed_station_parameters(&stations, [&first_mate.face.surface, &second_mate.face.surface]);
750                    rows = fit_closed_rows(&stations, &parameters, chamfer)?;
751                    carve_fold = true;
752                }
753            }
754            // Lane G row 2 (behind `closed_trim_read_first_on`): each trim
755            // is first read as shipped at the floor and refitted only on a
756            // miss (`closed_support_trim`); off the switch, the refit as before.
757            let read_first = crate::blend::closed_trim_read_first_on();
758            let refit_timing = crate::blend::BlendTimer::start("timing.closed.rows.refit_first_ms");
759            rows.cr_pcurve = if read_first {
760                closed_support_trim(&rows.cr, &rows.cr_pcurve, &first_mate.face.surface)?
761            } else {
762                refit_closed_support_pcurve(&rows.cr, &rows.cr_pcurve, &first_mate.face.surface)?
763            };
764            refit_timing.stop();
765            let refit_timing = crate::blend::BlendTimer::start("timing.closed.rows.refit_second_ms");
766            rows.cs_pcurve = if read_first {
767                closed_support_trim(&rows.cs, &rows.cs_pcurve, &second_mate.face.surface)?
768            } else {
769                refit_closed_support_pcurve(&rows.cs, &rows.cs_pcurve, &second_mate.face.surface)?
770            };
771            refit_timing.stop();
772            rows
773        }
774    };
775    rows_timing.stop();
776    let carve_timing = crate::blend::BlendTimer::start("timing.closed.carve_ms");
777    let crease = if carve_fold {
778        Some(carve_closed_wall(solid, &rows, &stations, &parameters, &first_mate, &second_mate, radius_at(mid_t).abs())?)
779    } else {
780        None
781    };
782    carve_timing.stop();
783    let surgery_timing = crate::blend::BlendTimer::start("timing.closed.surgery_ms");
784
785    // Both mates seam-structured: the second support crosses ITS carrier's
786    // seam meridian somewhere mid-loop; split cs there so face2's loop can
787    // keep its seam-in-one-loop structure.
788    let second_split = if second_seam {
789        let seam2 = second_face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?[0];
790        let period2 = {
791            let [d0, d1] = second_face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
792            d1 - d0
793        };
794        // Bracket: unwrapped uv2 track crossing seam2 + k·period.
795        let u2_first = stations[0].uv2[0];
796        let u2_last = stations[stations.len() - 1].uv2[0];
797        let direction = (u2_last - u2_first).signum();
798        let mut k = ((u2_first - seam2) / period2).ceil();
799        if direction < 0.0 {
800            k = ((u2_first - seam2) / period2).floor();
801        }
802        let target = seam2 + k * period2;
803        let inside =
804            (target - u2_first) * direction > 1e-6 && (u2_last - target) * direction > 1e-6;
805        // ALIGNED seams (both carriers' meridians meet at the shared
806        // vertex — the natural coaxial construction): the crossing sits
807        // at the march boundary and no mid-loop split is needed; the
808        // blend seam vertex already lies on both meridians.
809        let aligned = (target - u2_first).abs() <= 1e-6
810            || (target - u2_last).abs() <= 1e-6
811            || ((u2_first - seam2) / period2).fract().abs() <= 1e-9;
812        if !inside && aligned {
813            None
814        } else if !inside {
815            return Err(KernelRefusal::internal(KernelStage::Refine, "seam_crossing_bracket", "blend: second seam crossing not bracketed by the march"));
816        } else {
817            // Fit-space crossing parameter on the fitted cs (Newton via the
818            // fitted pcurve so the split lands exactly where the FITTED track
819            // crosses the meridian).
820            let [fit_low, fit_high] = rows.u_domain;
821            let mut p = fit_low
822                + (fit_high - fit_low) * {
823                    // Seed from the bracketing stations.
824                    let mut seed = 0.5;
825                    for pair in 0..stations.len() - 1 {
826                        let a = stations[pair].uv2[0];
827                        let b = stations[pair + 1].uv2[0];
828                        if (target - a) * (target - b) <= 0.0 {
829                            let local = (target - a) / (b - a);
830                            seed = (parameters[pair]
831                                + (parameters[pair + 1] - parameters[pair]) * local)
832                                .clamp(0.0, 1.0);
833                            break;
834                        }
835                    }
836                    seed
837                };
838            for _ in 0..NEWTON_ITERATIONS {
839                let value = rows.cs_pcurve.evaluate(p).or_refuse(KernelStage::Refine, "evaluate")?.x - target;
840                if value.abs() <= 1e-12 {
841                    break;
842                }
843                let step = 1e-8;
844                let probed = rows.cs_pcurve.evaluate(p + step).or_refuse(KernelStage::Refine, "evaluate")?.x - target;
845                let derivative = (probed - value) / step;
846                if derivative.abs() <= 1e-14 {
847                    return Err(KernelRefusal::non_convergence(KernelStage::Refine, "seam_crossing_newton", "blend: second seam crossing Newton stalled"));
848                }
849                p -= value / derivative;
850            }
851            let crossing_v = rows.cs_pcurve.evaluate(p).or_refuse(KernelStage::Refine, "evaluate")?.y;
852            Some(SecondSeamSplit {
853                fit_parameter: p,
854                crossing_v,
855                period: period2 * direction,
856            })
857        }
858    } else {
859        None
860    };
861
862    // A wall that SHIPS short of its construction request says so, typed, on
863    // the blend face it built (exact name and surface); a carved wall or a
864    // fallback construction makes no request.
865    let model_unmet = if carve_fold { None } else { model_unmet };
866    let wall_surface = model_unmet.map(|_| rows.surface.clone());
867    let built = build_surgery(
868        solid,
869        edge,
870        &first_mate,
871        &second_mate,
872        rows,
873        second_split,
874        name,
875        crease,
876    )?;
877    surgery_timing.stop();
878    if let (Some((declared, reason, round, stations, ceiling)), Some(surface)) = (model_unmet, wall_surface) {
879        crate::blend::record_wall_model_report(crate::blend::WallModelReport {
880            name: name.map(str::to_string),
881            surface,
882            request: crate::KernelTolerances::for_solid(solid, 1e-7).model,
883            residual: declared,
884            // The request covers the rails (the shipped support curves) and
885            // the wall; the residual is the worse of the two.
886            detail: request_rails.map(|(rails, unread, wall)| {
887                format!("last request read: rails {rails:.3e} off their carriers at j/16 ({unread} interval(s) unread), wall {wall:.3e}")
888            }),
889            budget: crate::ApproximationBudget {
890                reason,
891                rounds_used: round,
892                rounds_limit: crate::blend::stations::REFINE_ROUNDS,
893                stations,
894                station_limit: ceiling,
895                mechanism: crate::BudgetMechanism::LocalRounds,
896                // The request covers rails and wall: which one the residual
897                // reads, and the rail intervals it could not read.
898                measured_component: match request_rails {
899                    Some((rails, _, wall)) if rails > wall => crate::MeasuredComponent::Rails,
900                    _ => crate::MeasuredComponent::Wall,
901                },
902                unread: request_rails.map_or(0, |(_, unread, _)| unread),
903            },
904        });
905    }
906    Ok(built)
907}
908
909/// A closed spherical hole may meet the carrier's full-domain seam at its
910/// loop vertex. The domain rectangle is only a parameter cut, so moving the
911/// hole need not move that cut. Separate the ring from the rectangle and give
912/// it its own coincident vertex before surgery. Unlike a retraced slit, the
913/// opposite seam branches and collapsed pole edges remain in the solid.
914fn separate_spherical_domain_cut(
915    solid: &BrepSolid,
916    edge_id: u64,
917) -> Result<Option<BrepSolid>, KernelRefusal> {
918    let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) else {
919        return Ok(None);
920    };
921    if edge.start_vertex_id != edge.end_vertex_id {
922        return Ok(None);
923    }
924    let mut result = solid.clone();
925    let mut take_id = crate::blend::edge::fresh_id_source(solid);
926    let mut separated = false;
927    for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
928        let Some(atlas) = crate::sphere_chart::SphereAtlas::of_surface(&face.surface) else {
929            continue;
930        };
931        let [u0, u1] = face
932            .surface
933            .domain_u()
934            .or_refuse(KernelStage::Collect, "domain_cut_u")?;
935        let [v0, v1] = face
936            .surface
937            .domain_v()
938            .or_refuse(KernelStage::Collect, "domain_cut_v")?;
939        if [u0, u1, v0, v1] != [0.0, 1.0, 0.0, 1.0] {
940            continue;
941        }
942        if face
943            .surface
944            .closed_directions()
945            .or_refuse(KernelStage::Collect, "domain_cut_closed")?
946            != (true, false)
947        {
948            continue;
949        }
950        let band = 1e-8 * atlas.radius;
951        let bottom = face
952            .surface
953            .evaluate(u0, v0)
954            .or_refuse(KernelStage::Collect, "domain_cut_bottom")?;
955        let top = face
956            .surface
957            .evaluate(u0, v1)
958            .or_refuse(KernelStage::Collect, "domain_cut_top")?;
959        if bottom.add(top).scale(0.5).sub(atlas.centre).length() > band
960            || (bottom.sub(top).length() - 2.0 * atlas.radius).abs() > band
961        {
962            continue;
963        }
964        let mut additions = Vec::new();
965        let mut cut_ids = std::collections::HashSet::new();
966        for rim in &mut face.loops {
967            if rim.coedges.len() < 5 {
968                continue;
969            }
970            let positions: Vec<_> = rim
971                .coedges
972                .iter()
973                .enumerate()
974                .filter_map(|(i, c)| (c.edge_id == edge_id).then_some(i))
975                .collect();
976            if positions.len() != 1 {
977                continue;
978            }
979            let position = positions[0];
980            let ring = &rim.coedges[position];
981            let [a, b] = ring
982                .pcurve
983                .domain()
984                .or_refuse(KernelStage::Collect, "domain_cut_ring")?;
985            if ring
986                .pcurve
987                .evaluate(a)
988                .or_refuse(KernelStage::Collect, "domain_cut_ring_start")?
989                .sub(
990                    ring.pcurve
991                        .evaluate(b)
992                        .or_refuse(KernelStage::Collect, "domain_cut_ring_end")?,
993                )
994                .length()
995                > 1e-7
996            {
997                continue;
998            }
999            let rest: Vec<_> = rim
1000                .coedges
1001                .iter()
1002                .filter(|c| c.edge_id != edge_id)
1003                .collect();
1004            let mut points = Vec::new();
1005            let mut domain_cut = true;
1006            for coedge in &rest {
1007                let [a, b] = coedge
1008                    .pcurve
1009                    .domain()
1010                    .or_refuse(KernelStage::Collect, "domain_cut_trim")?;
1011                let start = coedge
1012                    .pcurve
1013                    .evaluate(a)
1014                    .or_refuse(KernelStage::Collect, "domain_cut_start")?;
1015                let end = coedge
1016                    .pcurve
1017                    .evaluate(b)
1018                    .or_refuse(KernelStage::Collect, "domain_cut_end")?;
1019                points.push(start);
1020                let degenerate = solid
1021                    .edges
1022                    .iter()
1023                    .any(|e| e.id == coedge.edge_id && e.degenerate);
1024                let at = |x: f64, low: f64, high: f64| {
1025                    (x - low).abs() <= 1e-8 || (x - high).abs() <= 1e-8
1026                };
1027                let on_boundary = if degenerate {
1028                    (start.y - end.y).abs() <= 1e-8
1029                        && at(start.y, v0, v1)
1030                        && coedge
1031                            .pcurve
1032                            .control_points
1033                            .iter()
1034                            .all(|p| (p.y / p.w - start.y).abs() <= 1e-8)
1035                } else {
1036                    at(start.x, u0, u1)
1037                        && (start.x - end.x).abs() <= 1e-8
1038                        && coedge
1039                            .pcurve
1040                            .control_points
1041                            .iter()
1042                            .all(|p| (p.x / p.w - start.x).abs() <= 1e-8)
1043                        && rest.iter().filter(|c| c.edge_id == coedge.edge_id).count() == 2
1044                        && rest
1045                            .iter()
1046                            .any(|c| c.edge_id == coedge.edge_id && c.forward != coedge.forward)
1047                };
1048                domain_cut &= on_boundary;
1049            }
1050            let twice_area: f64 = (0..points.len())
1051                .map(|i| {
1052                    let a = points[i];
1053                    let b = points[(i + 1) % points.len()];
1054                    a.x * b.y - a.y * b.x
1055                })
1056                .sum();
1057            let expected = (u1 - u0) * (v1 - v0) * if face.same_sense { 1.0 } else { -1.0 };
1058            if !domain_cut || (0.5 * twice_area - expected).abs() > 1e-7 * expected.abs() {
1059                continue;
1060            }
1061            // A relocated cut must belong only to this sphere. Its vertices
1062            // may touch the selected ring or collapsed poles, but no other
1063            // material edge. Its active parameter must already be sphere v.
1064            let cuts: std::collections::HashSet<_> = rest
1065                .iter()
1066                .filter_map(|c| {
1067                    solid
1068                        .edges
1069                        .iter()
1070                        .find(|e| e.id == c.edge_id && !e.degenerate)
1071                        .map(|e| e.id)
1072                })
1073                .collect();
1074            for cut in solid.edges.iter().filter(|e| cuts.contains(&e.id)) {
1075                let users = solid
1076                    .shells
1077                    .iter()
1078                    .flat_map(|s| &s.faces)
1079                    .flat_map(|f| &f.loops)
1080                    .flat_map(|l| &l.coedges)
1081                    .filter(|c| c.edge_id == cut.id)
1082                    .count();
1083                let exclusive_vertices = solid
1084                    .edges
1085                    .iter()
1086                    .filter(|e| {
1087                        e.start_vertex_id == cut.start_vertex_id
1088                            || e.end_vertex_id == cut.start_vertex_id
1089                            || e.start_vertex_id == cut.end_vertex_id
1090                            || e.end_vertex_id == cut.end_vertex_id
1091                    })
1092                    .all(|e| e.degenerate || cuts.contains(&e.id) || e.id == edge_id);
1093                let mut same_parameter = cut.t0 >= v0 && cut.t1 <= v1 && cut.t0 < cut.t1;
1094                for i in 0..=16 {
1095                    let t = cut.t0 + (cut.t1 - cut.t0) * i as f64 / 16.0;
1096                    let point = cut
1097                        .curve
1098                        .evaluate(t)
1099                        .or_refuse(KernelStage::Collect, "domain_cut_curve")?;
1100                    let carrier = face
1101                        .surface
1102                        .evaluate(u0, t)
1103                        .or_refuse(KernelStage::Collect, "domain_cut_carrier")?;
1104                    same_parameter &= point.sub(carrier).length() <= band;
1105                }
1106                domain_cut &= users == 2 && exclusive_vertices && same_parameter;
1107            }
1108            if !domain_cut {
1109                continue;
1110            }
1111            cut_ids.extend(cuts);
1112            additions.push(LoopRecord {
1113                id: take_id(),
1114                coedges: vec![rim.coedges.remove(position)],
1115            });
1116            separated = true;
1117        }
1118        if !additions.is_empty() {
1119            // The freed contact can cross the old parameter seam. Move the
1120            // artificial cut by a quarter turn, which is an exact shift of
1121            // this rational circle chart, to keep every real trim in-domain.
1122            let real = |id: u64| {
1123                !cut_ids.contains(&id) && !solid.edges.iter().any(|e| e.id == id && e.degenerate)
1124            };
1125            let curves: Vec<_> = face
1126                .loops
1127                .iter()
1128                .flat_map(|l| &l.coedges)
1129                .chain(additions.iter().flat_map(|l| &l.coedges))
1130                .filter(|c| real(c.edge_id) || c.edge_id == edge_id)
1131                .map(|c| &c.pcurve)
1132                .collect();
1133            let mut candidates = Vec::new();
1134            for shift in [0.25, 0.5, 0.75] {
1135                let mut clearance = f64::INFINITY;
1136                let mut fits = true;
1137                for curve in &curves {
1138                    let first = curve.control_points[0].x / curve.control_points[0].w;
1139                    let offset = -(first - shift).floor();
1140                    for p in &curve.control_points {
1141                        let u = p.x / p.w - shift + offset;
1142                        fits &= u >= 0.0 && u <= 1.0;
1143                        clearance = clearance.min(u.min(1.0 - u));
1144                    }
1145                }
1146                if fits {
1147                    candidates.push((clearance, shift));
1148                }
1149            }
1150            let Some((_, shift)) = candidates.into_iter().max_by(|a, b| a.0.total_cmp(&b.0)) else {
1151                return Err(KernelRefusal::unsupported(
1152                    KernelStage::Collect,
1153                    "sphere_domain_cut",
1154                    "blend: no quarter-turn sphere chart keeps the real trims in-domain",
1155                ));
1156            };
1157            let seam_direction = face
1158                .surface
1159                .evaluate(shift, 0.5)
1160                .or_refuse(KernelStage::Collect, "sphere_cut_direction")?
1161                .sub(atlas.centre);
1162            let surface = crate::make_sphere_surface_framed(
1163                atlas.centre,
1164                atlas.radius,
1165                atlas.basis[2],
1166                Some(seam_direction),
1167            )
1168            .or_refuse(KernelStage::Collect, "sphere_cut_surface")?;
1169            // Rebuilding must be only a chart change, including handedness.
1170            for i in 0..=16 {
1171                for v in [0.0, 0.3, 0.5, 0.7, 1.0] {
1172                    let u = i as f64 / 16.0;
1173                    let old = face
1174                        .surface
1175                        .evaluate(u, v)
1176                        .or_refuse(KernelStage::Collect, "sphere_cut_old")?;
1177                    let new = surface
1178                        .evaluate((u - shift).rem_euclid(1.0), v)
1179                        .or_refuse(KernelStage::Collect, "sphere_cut_new")?;
1180                    if old.sub(new).length() > band {
1181                        return Err(KernelRefusal::unsupported(
1182                            KernelStage::Collect,
1183                            "sphere_cut_chart",
1184                            "blend: the sphere quarter turn is not the same carrier",
1185                        ));
1186                    }
1187                }
1188            }
1189            let seam = surface
1190                .iso_curve_u(0.0)
1191                .or_refuse(KernelStage::Collect, "sphere_cut_seam")?;
1192            for coedge in face
1193                .loops
1194                .iter_mut()
1195                .flat_map(|l| &mut l.coedges)
1196                .chain(additions.iter_mut().flat_map(|l| &mut l.coedges))
1197            {
1198                if solid
1199                    .edges
1200                    .iter()
1201                    .any(|e| e.id == coedge.edge_id && e.degenerate)
1202                {
1203                    continue;
1204                }
1205                if !cut_ids.contains(&coedge.edge_id) {
1206                    let first =
1207                        coedge.pcurve.control_points[0].x / coedge.pcurve.control_points[0].w;
1208                    let offset = -(first - shift).floor() - shift;
1209                    for p in &mut coedge.pcurve.control_points {
1210                        p.x += offset * p.w;
1211                    }
1212                }
1213            }
1214            for cut in result.edges.iter_mut().filter(|e| cut_ids.contains(&e.id)) {
1215                for (vertex_id, t) in [(cut.start_vertex_id, cut.t0), (cut.end_vertex_id, cut.t1)] {
1216                    let point = seam
1217                        .evaluate(t)
1218                        .or_refuse(KernelStage::Collect, "sphere_cut_vertex")?;
1219                    let vertex = result
1220                        .vertices
1221                        .iter_mut()
1222                        .find(|v| v.id == vertex_id)
1223                        .ok_or(KernelRefusal::internal(
1224                            KernelStage::Collect,
1225                            "sphere_cut_vertex",
1226                            "blend: sphere seam vertex is missing",
1227                        ))?;
1228                    vertex.point = point;
1229                }
1230                cut.curve = seam.clone();
1231            }
1232            face.surface = surface;
1233        }
1234        face.loops.extend(additions);
1235    }
1236    if !separated {
1237        return Ok(None);
1238    }
1239    let old_vertex = solid
1240        .vertices
1241        .iter()
1242        .find(|v| v.id == edge.start_vertex_id)
1243        .ok_or(KernelRefusal::internal(
1244            KernelStage::Collect,
1245            "domain_cut_vertex",
1246            "blend: closed ring vertex is missing",
1247        ))?;
1248    let vertex_id = take_id();
1249    result.vertices.push(VertexRecord {
1250        id: vertex_id,
1251        point: old_vertex.point,
1252    });
1253    let ring = result
1254        .edges
1255        .iter_mut()
1256        .find(|e| e.id == edge_id)
1257        .ok_or(KernelRefusal::internal(
1258            KernelStage::Collect,
1259            "domain_cut_ring",
1260            "blend: closed ring edge is missing",
1261        ))?;
1262    ring.start_vertex_id = vertex_id;
1263    ring.end_vertex_id = vertex_id;
1264    Ok(Some(result))
1265}
1266
1267/// Imported faces can carry a slit from a closed rim to a pole and straight
1268/// back along the same UV track. It has no area and is not a periodic seam
1269/// (whose two pcurves differ by a period). Moving the rim must not drag this
1270/// artificial cut onto a different meridian. Cancel only adjacent opposite
1271/// uses of an edge with no other users, and prove that their UV tracks agree.
1272fn remove_retraced_cuts(
1273    solid: &BrepSolid,
1274    edge_id: u64,
1275) -> Result<Option<BrepSolid>, KernelRefusal> {
1276    let mut result = solid.clone();
1277    let mut removed = Vec::new();
1278    for face in result.shells.iter_mut().flat_map(|shell| &mut shell.faces) {
1279        for rim in &mut face.loops {
1280            if !rim.coedges.iter().any(|coedge| coedge.edge_id == edge_id) {
1281                continue;
1282            }
1283            loop {
1284                let n = rim.coedges.len();
1285                let mut pair = None;
1286                for i in 0..n {
1287                    let j = (i + 1) % n;
1288                    let (a, b) = (&rim.coedges[i], &rim.coedges[j]);
1289                    if a.edge_id == edge_id || a.edge_id != b.edge_id || a.forward == b.forward {
1290                        continue;
1291                    }
1292                    let users = solid
1293                        .shells
1294                        .iter()
1295                        .flat_map(|s| &s.faces)
1296                        .flat_map(|f| &f.loops)
1297                        .flat_map(|l| &l.coedges)
1298                        .filter(|c| c.edge_id == a.edge_id)
1299                        .count();
1300                    if users != 2 {
1301                        continue;
1302                    }
1303                    let [a0, a1] = a
1304                        .pcurve
1305                        .domain()
1306                        .or_refuse(KernelStage::Collect, "cut_domain")?;
1307                    let [b0, b1] = b
1308                        .pcurve
1309                        .domain()
1310                        .or_refuse(KernelStage::Collect, "cut_domain")?;
1311                    // Compare the complete reversed rational representation,
1312                    // not a few probes that could miss a curved excursion.
1313                    let agrees =
1314                        a.pcurve.degree == b.pcurve.degree
1315                            && a.pcurve.knots.len() == b.pcurve.knots.len()
1316                            && a.pcurve.control_points.len() == b.pcurve.control_points.len()
1317                            && a.pcurve.knots.iter().zip(b.pcurve.knots.iter().rev()).all(
1318                                |(x, y)| {
1319                                    ((x - a0) / (a1 - a0) - (b1 - y) / (b1 - b0)).abs() <= 1e-9
1320                                },
1321                            )
1322                            && a.pcurve
1323                                .control_points
1324                                .iter()
1325                                .zip(b.pcurve.control_points.iter().rev())
1326                                .all(|(p, q)| {
1327                                    p.point()
1328                                        .ok()
1329                                        .zip(q.point().ok())
1330                                        .is_some_and(|(p, q)| p.sub(q).length() <= 1e-9)
1331                                        && (p.w / a.pcurve.control_points[0].w
1332                                            - q.w / b.pcurve.control_points.last().unwrap().w)
1333                                            .abs()
1334                                            <= 1e-9
1335                                });
1336                    if agrees {
1337                        pair = Some((i, j, a.edge_id));
1338                        break;
1339                    }
1340                }
1341                let Some((i, j, id)) = pair else {
1342                    break;
1343                };
1344                rim.coedges.remove(i.max(j));
1345                rim.coedges.remove(i.min(j));
1346                removed.push(id);
1347            }
1348        }
1349    }
1350    if removed.is_empty() {
1351        return Ok(None);
1352    }
1353    result.edges.retain(|edge| !removed.contains(&edge.id));
1354    super::open::prune_orphan_vertices(&mut result);
1355    Ok(Some(result))
1356}
1357
1358/// Where the second support crosses ITS seam-structured carrier's seam
1359/// meridian (both-seam closed edges).
1360struct SecondSeamSplit {
1361    fit_parameter: f64,
1362    crossing_v: f64,
1363    /// Signed carrier period travelled by the unwrapped pcurve track.
1364    period: f64,
1365}
1366
1367/// Replace the blended edge in both mating loops, trim the seam edge of an
1368/// anchored closed carrier, and insert the blend face.
1369/// The carve of a folding closed-edge wall: measure the fitted rows against
1370/// the carriers between the stations they were fitted through (the network's
1371/// own rail bar, half `intersection_fit`), trace the crease on the fitted
1372/// surface and fit it to `pcurve_consistency`, and refuse by name a lens
1373/// that straddles the wall's own seam (the closed rows join at u = 0 ≡ 1, and
1374/// the crease tracer reads one parameter rectangle).
1375/// Top of the closed march's carve ladder: `SEED_INTERVALS << 8` = 4096
1376/// intervals, the station count the chain lane's ladder also tops out near
1377/// (`CHAIN_CARVE_MAX_PER_SEGMENT` per segment).
1378const CARVE_MAX_REFINEMENT_DEPTH: usize = MAX_REFINEMENT_DEPTH + 4;
1379
1380/// How far the closed rows' rails stand off their carriers BETWEEN the
1381/// stations they were fitted through, at 0.25/0.5/0.75 of every span — the
1382/// open march's `rails_off_carriers` reading on closed rows.
1383fn rails_off_closed_carriers(
1384    rows: &FittedRows,
1385    stations: &[Station],
1386    parameters: &[f64],
1387    first: &BlendMate,
1388    second: &BlendMate,
1389) -> Result<f64, KernelRefusal> {
1390    Ok(closed_rail_interval_misses(rows, stations, parameters,
1391        [&first.face.surface, &second.face.surface])?.into_iter().fold(0.0_f64, f64::max))
1392}
1393
1394fn carve_closed_wall(
1395    solid: &BrepSolid,
1396    rows: &FittedRows,
1397    stations: &[Station],
1398    parameters: &[f64],
1399    first: &BlendMate,
1400    second: &BlendMate,
1401    radius: f64,
1402) -> Result<crate::blend::carve::CarvedCrease, KernelRefusal> {
1403    let policy = crate::KernelTolerances::for_solid(solid, 1e-7);
1404    let rail_bar = 0.5 * policy.intersection_fit;
1405    let off = rails_off_closed_carriers(rows, stations, parameters, first, second)?;
1406    crate::blend::carve::carve_trace(format_args!(
1407        "blend closed-edge carve: {} stations, rails {off:.3e} off their carriers between stations (bar {rail_bar:.3e})",
1408        parameters.len()
1409    ));
1410    if off > rail_bar {
1411        return Err(crate::blend::fold::wall_fold_refusal(
1412            Vec::new(),
1413            format!(
1414                "{} {radius} fits this edge: the wall folds, and the closed march's fitted rails stand {off:.3e} off their carriers between stations (bar {rail_bar:.3e}), so there is no wall accurate enough to carve",
1415                crate::blend::WALL_FOLDS
1416            ),
1417        ));
1418    }
1419    let Some(carved) = crate::blend::carve::trace_wall_crease(&rows.surface, radius)? else {
1420        return Err(KernelRefusal::internal(KernelStage::Refine, "carve_no_fold", "blend closed-edge carve: the wall re-marched under Carve carries no fold to carve, but the march refused one"));
1421    };
1422    let [u0, u1] = rows.u_domain;
1423    let margin = 1e-3 * (u1 - u0);
1424    let straddles = carved.ends.iter().any(|end| end[0] <= u0 + margin || end[0] >= u1 - margin);
1425    if straddles {
1426        return Err(crate::blend::fold::wall_fold_refusal(
1427            Vec::new(),
1428            format!(
1429                "{} {radius} fits this edge: the wall folds, and the fold band straddles the wall's own seam (lens ends at u = {:.6} and {:.6} of [{u0:.3}, {u1:.3}]), which the crease tracer reads as two half-lenses; carving across the seam is not built",
1430                crate::blend::WALL_FOLDS, carved.ends[0][0], carved.ends[1][0]
1431            ),
1432        ));
1433    }
1434    crate::blend::carve::fit_crease(&rows.surface, &carved, policy.pcurve_consistency)
1435}
1436
1437/// Lane G row 2 (2026-10-14, `closed_trim_read_first_on`): a closed rail's
1438/// support trim on a PLANE mate is the rail's own control points carried
1439/// through the plane's affine chart (an exact image of the rail, the exact
1440/// revolution lane's rule for a plane mate's rail, `plane_affine_pcurve`),
1441/// read once as shipped at the pcurve floor (`track_fit::read_shipped_pcurve`,
1442/// the read the refit itself is judged on, at the rail's own parameter) and
1443/// kept when it reads within it (8.98e-15 on the half torus's cut plane);
1444/// any other mate, or an image that misses, takes the refit as before. The
1445/// shipped contract (every trim read within the floor) is the refit's own;
1446/// what changes is the bytes of a plane trim (the refit's control points are
1447/// the track fitter's, these are the rail's own), which is why the road is
1448/// behind its switch until its census. The march's own interpolated pcurve
1449/// was measured as a second candidate and dropped: on the half torus it
1450/// reads 8.5e-5 off its rail where the uv track crosses the carrier's knot
1451/// lines (the chart is C1 there, a cubic interpolant through the stations is
1452/// not), the two reads cost 2.8 ms for nothing, and a rational carrier's
1453/// knot lines make that the rule, not the exception.
1454fn closed_support_trim(rail: &NurbsCurve, old: &NurbsCurve, surface: &NurbsSurface) -> Result<NurbsCurve, KernelRefusal> {
1455    let floor = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
1456    let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1457    let within_floor = |candidate: &NurbsCurve, what: &str| -> bool {
1458        let _read_timing = crate::blend::BlendTimer::start("timing.closed.rows.trim_read_ms");
1459        let read = crate::blend::track_fit::read_shipped_pcurve(surface, &|t| rail.evaluate(t), candidate, d0, d1);
1460        if std::env::var_os("BREP_DEBUG_TRACK_FIT").is_some() {
1461            match &read {
1462                Ok((miss, standoff, samples, worst)) => eprintln!(
1463                    "TRACK_FIT closed-edge support, {what} candidate ({} control points): miss {miss:.3e} at t {worst:.9} ({samples} samples), rail standoff {standoff:.3e}, floor {floor:e}",
1464                    candidate.control_points.len()),
1465                Err(error) => eprintln!("TRACK_FIT closed-edge support, {what} candidate: unreadable: {error}"),
1466            }
1467        }
1468        read.is_ok_and(|(miss, _, _, _)| miss <= floor)
1469    };
1470    if let Some(affine) = plane_affine_pcurve(rail, surface) {
1471        if within_floor(&affine, "affine plane image") {
1472            crate::blend::record_count("count.closed.rows.trim.affine", 1);
1473            return Ok(affine);
1474        }
1475    }
1476    crate::blend::record_count("count.closed.rows.trim.refit", 1);
1477    refit_closed_support_pcurve(rail, old, surface)
1478}
1479
1480/// The rail's own control points through a PLANE mate's affine chart (the
1481/// chart read off the surface's domain corners, as the exact revolution
1482/// lane's `plane_pcurve` reads it), on the rail's knots and weights: the
1483/// exact image of the rail in (u, v). `None` on any other carrier, or on a
1484/// chart too thin to invert.
1485fn plane_affine_pcurve(rail: &NurbsCurve, surface: &NurbsSurface) -> Option<NurbsCurve> {
1486    if !matches!(surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) {
1487        return None;
1488    }
1489    let [u0, u1] = surface.domain_u().ok()?;
1490    let [v0, v1] = surface.domain_v().ok()?;
1491    let origin = surface.evaluate(u0, v0).ok()?;
1492    let du = surface.evaluate(u1, v0).ok()?.sub(origin).scale(1.0 / (u1 - u0));
1493    let dv = surface.evaluate(u0, v1).ok()?.sub(origin).scale(1.0 / (v1 - v0));
1494    let (a, b, c) = (du.dot(du), du.dot(dv), dv.dot(dv));
1495    let det = a * c - b * b;
1496    let chart_scale = origin.length().max(du.length()).max(dv.length()).max(1.0);
1497    if !(det > 1e-24 * chart_scale.powi(4)) {
1498        return None;
1499    }
1500    let mut pcurve = rail.clone();
1501    for control in &mut pcurve.control_points {
1502        let weight = control.w;
1503        let offset = Vec3::new(control.x / weight, control.y / weight, control.z / weight).sub(origin);
1504        let (r, s) = (offset.dot(du), offset.dot(dv));
1505        control.x = (u0 + (c * r - b * s) / det) * weight;
1506        control.y = (v0 + (a * s - b * r) / det) * weight;
1507        control.z = 0.0;
1508    }
1509    Some(pcurve)
1510}
1511
1512/// A support rail's pcurve on its mate `surface` (a closed edge's whole rail,
1513/// or an open edge's rail trimmed to its crossing window), fitted to the
1514/// rail's own projected track at the pcurve floor
1515/// (`chain::project_piece_pcurve`, the closed chain's support-piece fitter,
1516/// which refuses a fit off that floor), on the rail's parameter domain and in
1517/// the same carrier period as the interpolated pcurve `old` it replaces. A
1518/// closed rail around a periodic carrier spans a whole period, so its ends are
1519/// not pinned by the fitter (both would go to one seam); instead an end whose
1520/// `old` coordinate lies exactly on a seam keeps that coordinate, so the loop
1521/// still closes on the seam the surgery built it on.
1522///
1523/// The shipped curve is read again at the floor (`read_shipped_pcurve`). The
1524/// fitter's stencil reads j/16 of each TRACK interval and the shipped read
1525/// j/16 of each span of the fitted curve's own (averaged) knots, so a fit the
1526/// stencil reads just under the floor can read just over it as shipped (the
1527/// 2026-09-27 revolve: 9.923e-8 on the stencil, 1.037e-7 at t 0.4902). Such
1528/// a fit is refitted, at the SAME floor, with its track refined where the
1529/// shipped read found the miss, up to `SHIPPED_READ_REPAIRS` times; the floor
1530/// never moves, and a fit read within it the first time ships as before.
1531///
1532/// Its first fit, whose floor miss is TERMINAL on this road, takes the
1533/// knot-aware retry (lane L, 2026-10-16); the open surgery's own refit
1534/// (`refit_closed_support_pcurve_read`), which answers a miss with its
1535/// fallback, does not.
1536pub(in crate::blend) fn refit_closed_support_pcurve(rail: &NurbsCurve, old: &NurbsCurve, surface: &NurbsSurface) -> Result<NurbsCurve, KernelRefusal> {
1537    let knot_retry = KNOT_RETRY.with(|flag| flag.get());
1538    refit_closed_support_pcurve_read_with(rail, old, surface, &mut crate::blend::track_fit::FootMemo::transient(), knot_retry).map(|(fitted, _)| fitted)
1539}
1540
1541thread_local! {
1542    /// Set only while [`blend_closed_edge_knot_aware`] or
1543    /// [`with_pcurve_knot_retry`] re-runs a blend whose first run was refused
1544    /// for a support pcurve off the floor (lane L, 2026-10-16).
1545    static KNOT_RETRY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1546}
1547
1548/// [`refit_closed_support_pcurve`] handing back the shipped curve's own read
1549/// `(miss, rail standoff, samples, worst parameter)` -- the
1550/// `read_shipped_pcurve` of the curve returned, which a caller that reads
1551/// the shipped trim again would otherwise compute a second time on the same
1552/// inputs -- with the feet of that read left in `memo` (cleared before each
1553/// fit, so it holds the returned curve's feet only) for the caller's
1554/// further reads of the same curve against the same rail.
1555pub(in crate::blend) fn refit_closed_support_pcurve_read(
1556    rail: &NurbsCurve,
1557    old: &NurbsCurve,
1558    surface: &NurbsSurface,
1559    memo: &mut crate::blend::track_fit::FootMemo,
1560) -> Result<(NurbsCurve, (f64, f64, usize, f64)), KernelRefusal> {
1561    // The open surgery's refit takes the knot-aware retry only inside
1562    // `with_pcurve_knot_retry` (lane L, 2026-10-16, lCount_229).
1563    let knot_retry = KNOT_RETRY.with(|flag| flag.get());
1564    refit_closed_support_pcurve_read_with(rail, old, surface, memo, knot_retry)
1565}
1566
1567/// Runs `build` with every support refit taking the knot-aware retry on a
1568/// floor miss, restoring the flag after (lane L, 2026-10-16, lCount_229: the
1569/// fillet group's network re-run on a pcurve-floor refusal).
1570pub fn with_pcurve_knot_retry<T>(build: impl FnOnce() -> T) -> T {
1571    let previous = KNOT_RETRY.with(|flag| flag.replace(true));
1572    let built = build();
1573    KNOT_RETRY.with(|flag| flag.set(previous));
1574    built
1575}
1576
1577/// [`refit_closed_support_pcurve_read`], its first fit taking the knot-aware
1578/// retry when `knot_retry` (see [`refit_closed_support_pcurve`]).
1579fn refit_closed_support_pcurve_read_with(
1580    rail: &NurbsCurve,
1581    old: &NurbsCurve,
1582    surface: &NurbsSurface,
1583    memo: &mut crate::blend::track_fit::FootMemo,
1584    knot_retry: bool,
1585) -> Result<(NurbsCurve, (f64, f64, usize, f64)), KernelRefusal> {
1586    const SHIPPED_READ_REPAIRS: usize = 3;
1587    let floor = crate::pcurve::PCURVE_REFINEMENT_TOLERANCE;
1588    let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1589    let mut near: Vec<f64> = Vec::new();
1590    // The FIRST fit's floor miss is terminal here, so it takes the knot-aware
1591    // retry (lane L, 2026-10-16, lCount_201); a repair round's miss keeps the
1592    // last fit, as before.
1593    let (mut fitted, mut read) = fit_and_read_support(rail, old, surface, &near, memo, knot_retry)?;
1594    for _ in 0..SHIPPED_READ_REPAIRS {
1595        if read.0 <= floor || !(d1 > d0) {
1596            break;
1597        }
1598        near.push((read.3 - d0) / (d1 - d0));
1599        crate::blend::record_count("count.surgery.refit_repairs", 1);
1600        // A repair that fails keeps the last fit AND its feet: a failed
1601        // fit or an unreadable read hands nothing to the memo.
1602        match fit_and_read_support(rail, old, surface, &near, memo, false) {
1603            Ok(repaired) => (fitted, read) = repaired,
1604            Err(_) => break,
1605        }
1606    }
1607    let (miss, _, samples, _) = read;
1608    if !(miss <= floor) {
1609        return Err(KernelRefusal::non_convergence(KernelStage::Refine, CLOSED_SUPPORT_PCURVE_FLOOR_WHAT, format!(
1610            "{} a blend's support pcurve, as shipped, misses its rail's track by {miss:.3e} at {samples} samples, \
1611             against a floor of {floor:.1e}",
1612            crate::blend::PCURVE_OFF_FLOOR,
1613        )));
1614    }
1615    Ok((fitted, read))
1616}
1617
1618/// [`refit_closed_support_pcurve`]'s fit, its track refined near the
1619/// fractions `near` first, and the shipped curve's read (miss, standoff,
1620/// samples, worst rail parameter).
1621fn fit_and_read_support(
1622    rail: &NurbsCurve,
1623    old: &NurbsCurve,
1624    surface: &NurbsSurface,
1625    near: &[f64],
1626    memo: &mut crate::blend::track_fit::FootMemo,
1627    knot_retry: bool,
1628) -> Result<(NurbsCurve, (f64, f64, usize, f64)), KernelRefusal> {
1629    let [d0, d1] = rail.domain().or_refuse(KernelStage::Refine, "domain")?;
1630    // Every foot of the track is sought from the march's own trim `old` at
1631    // the same rail parameter (`pcurve_guide`), on the branch it runs on.
1632    let guide = crate::blend::chain::pcurve_guide(old, surface)?;
1633    let track_timing = crate::blend::BlendTimer::start("timing.support_refit.track_ms");
1634    let mut fitted = if knot_retry {
1635        crate::blend::chain::project_piece_pcurve_within_knot_retry(rail, surface, false, false, Some(&guide), near)?
1636    } else {
1637        crate::blend::chain::project_piece_pcurve_within(rail, surface, false, false, Some(&guide), near)?
1638    };
1639    track_timing.stop();
1640    // The fitter's parameter is the track fraction; the surgery reads the
1641    // pcurve at the rail's own parameter.
1642    let [f0, f1] = fitted.domain().or_refuse(KernelStage::Refine, "domain")?;
1643    for knot in fitted.knots.iter_mut() {
1644        *knot = d0 + (*knot - f0) / (f1 - f0) * (d1 - d0);
1645    }
1646    let debug = std::env::var_os("BREP_DEBUG_TRACK_FIT").is_some();
1647    if debug {
1648        // Diagnostic only: the same read before the period shift and the seam
1649        // ends are set (the shift alone moves no point of the carrier).
1650        match crate::blend::track_fit::read_shipped_pcurve(surface, &|t| rail.evaluate(t), &fitted, d0, d1) {
1651            Ok((miss, standoff, samples, worst)) => eprintln!(
1652                "TRACK_FIT closed-edge support: before the seam ends, miss {miss:.3e} at t {worst:.9} ({samples} samples), standoff {standoff:.3e}"),
1653            Err(error) => eprintln!("TRACK_FIT closed-edge support: before the seam ends, unreadable: {error}"),
1654        }
1655    }
1656    let (closed_u, closed_v) = surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")?;
1657    let [u0, u1] = surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
1658    let [v0, v1] = surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
1659    let old_start = old.evaluate(d0).or_refuse(KernelStage::Refine, "evaluate")?;
1660    let old_end = old.evaluate(d1).or_refuse(KernelStage::Refine, "evaluate")?;
1661    let new_start = fitted.evaluate(d0).or_refuse(KernelStage::Refine, "evaluate")?;
1662    // Whole periods only: the same carrier point, in the old pcurve's period.
1663    let shift = |closed: bool, from: f64, to: f64, period: f64| if closed { ((to - from) / period).round() * period } else { 0.0 };
1664    let (shift_u, shift_v) = (shift(closed_u, new_start.x, old_start.x, u1 - u0), shift(closed_v, new_start.y, old_start.y, v1 - v0));
1665    for point in fitted.control_points.iter_mut() {
1666        point.x += shift_u * point.w;
1667        point.y += shift_v * point.w;
1668    }
1669    let on_seam = |closed: bool, value: f64, low: f64, high: f64| {
1670        let period = high - low;
1671        closed && ((value - low) / period - ((value - low) / period).round()).abs() * period <= 1e-12 * period.max(1.0)
1672    };
1673    let last = fitted.control_points.len() - 1;
1674    for (index, end) in [(0, old_start), (last, old_end)] {
1675        let point = &mut fitted.control_points[index];
1676        if on_seam(closed_u, end.x, u0, u1) {
1677            point.x = end.x * point.w;
1678        }
1679        if on_seam(closed_v, end.y, v0, v1) {
1680            point.y = end.y * point.w;
1681        }
1682    }
1683    // The curve SHIPPED is not the one the fitter checked (its domain, period
1684    // and seam ends were edited), so it is read again, at the rail's own
1685    // parameter, against the fitter's floor; a miss refuses as the fitter's
1686    // own would, and an unreadable sample refuses.
1687    // The feet are the shipped curve's, read into a memo of their own and
1688    // handed over only with a readable curve: a read that refuses (an
1689    // unreadable sample, found after every sample was sought) must leave
1690    // the caller's memo holding the feet of the curve the caller keeps,
1691    // not this curve's.
1692    let mut own = memo.empty_like();
1693    let (miss, standoff, samples, worst) =
1694        crate::blend::track_fit::read_shipped_pcurve_memo(surface, &|t| rail.evaluate(t), &fitted, d0, d1, &mut own)?;
1695    *memo = own;
1696    if debug {
1697        eprintln!("TRACK_FIT closed-edge support: shipped pcurve miss {miss:.3e} at t {worst:.9} of [{d0:.9}, {d1:.9}] ({samples} samples); rail standoff from its carrier {standoff:.3e}");
1698    }
1699    Ok((fitted, (miss, standoff, samples, worst)))
1700}
1701
1702
1703/// One exit probe: whether a support station's `uv` (wrapped into a closed
1704/// carrier's domain) classifies OUTSIDE `face`'s trims, an unreadable class
1705/// counting as outside.
1706fn support_exits_at(face: &FaceRecord, mut uv: [f64; 2]) -> bool {
1707    if let Ok((closed_u, closed_v)) = face.surface.closed_directions() {
1708        if closed_u {
1709            if let Ok([low, high]) = face.surface.domain_u() {
1710                uv[0] = low + (uv[0] - low).rem_euclid(high - low);
1711            }
1712        }
1713        if closed_v {
1714            if let Ok([low, high]) = face.surface.domain_v() {
1715                uv[1] = low + (uv[1] - low).rem_euclid(high - low);
1716            }
1717        }
1718    }
1719    crate::parameter_point_in_face(face, crate::Vec2 { x: uv[0], y: uv[1] }, 1e-6)
1720        .map(|class| class == crate::PolygonClass::Outside)
1721        .unwrap_or(true)
1722}
1723
1724/// The exit question for a mate bounded only by PARALLELS of the rim's axis
1725/// (lane R 2026-10-28, the cylinder rims row: 17 probes per mate were 0.15 ms
1726/// of a two-rim fillet's ~1.5 ms).
1727///
1728/// A plane normal to the axis or a cylinder/cone about it is cut by the
1729/// parallels into cells — annuli of the plane between consecutive radii,
1730/// bands of the cylinder between consecutive heights — and when every
1731/// boundary edge of the face (seams, used twice by one loop, aside) is such a
1732/// parallel, each cell is wholly inside the face or wholly outside it.  The
1733/// support contacts of a rim between coaxial carriers are parallels too, so
1734/// when every station's meridian coordinate (radius on a plane, height on a
1735/// cylinder or cone) lies in ONE open cell, clear of its bounding parallels
1736/// by a margin far above the probe's 1e-6 band, every station classifies the
1737/// same, and the first station's probe is the scan's answer.  `None` — the
1738/// full scan — for any other carrier, any boundary that is not a parallel,
1739/// and any station within the margin of a boundary, so a track that does
1740/// meet a boundary is classified station by station exactly as before.
1741fn support_exit_between_parallels(
1742    solid: &BrepSolid,
1743    face: &FaceRecord,
1744    (origin, axis): (Vec3, Vec3),
1745    contacts: &[Vec3],
1746    probe: &dyn Fn(usize) -> bool,
1747) -> Option<bool> {
1748    let radial = match face.surface.analytic()? {
1749        crate::AnalyticSurface::Plane { .. } => true,
1750        crate::AnalyticSurface::RuledRevolution { .. } => false,
1751        _ => return None,
1752    };
1753    if contacts.is_empty() {
1754        return None;
1755    }
1756    let axis = axis.normalized().ok()?;
1757    let coordinates = |point: Vec3| -> (f64, f64) {
1758        let offset = point.sub(origin);
1759        let height = offset.dot(axis);
1760        (offset.sub(axis.scale(height)).length(), height)
1761    };
1762    let meridian = |point: Vec3| -> f64 {
1763        let (radius, height) = coordinates(point);
1764        if radial { radius } else { height }
1765    };
1766    let scale = contacts.iter().map(|point| point.sub(origin).length()).fold(1.0, f64::max);
1767    let parallel_band = 1e-9 * scale;
1768    let margin = 1e-5 * scale;
1769    // Every boundary edge but the seams must be a parallel: one radius and
1770    // one height along the whole edge, read at nine points.
1771    let mut boundaries: Vec<f64> = Vec::new();
1772    for loop_record in &face.loops {
1773        for coedge in &loop_record.coedges {
1774            if loop_record.coedges.iter().filter(|other| other.edge_id == coedge.edge_id).count() == 2 {
1775                continue;
1776            }
1777            let boundary = solid.edges.iter().find(|candidate| candidate.id == coedge.edge_id)?;
1778            if boundary.degenerate {
1779                continue;
1780            }
1781            let mut read: Option<(f64, f64)> = None;
1782            for step in 0..=8 {
1783                let point = boundary.curve.evaluate(boundary.t0 + (boundary.t1 - boundary.t0) * step as f64 / 8.0).ok()?;
1784                let here = coordinates(point);
1785                match read {
1786                    None => read = Some(here),
1787                    Some(first) => {
1788                        if (here.0 - first.0).abs() > parallel_band || (here.1 - first.1).abs() > parallel_band {
1789                            return None;
1790                        }
1791                    }
1792                }
1793            }
1794            let (radius, height) = read?;
1795            boundaries.push(if radial { radius } else { height });
1796        }
1797    }
1798    // One open cell holds every station, clear of every boundary parallel.
1799    let readings: Vec<f64> = contacts.iter().map(|point| meridian(*point)).collect();
1800    let low = readings.iter().copied().fold(f64::INFINITY, f64::min);
1801    let high = readings.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1802    if !(low.is_finite() && high.is_finite()) {
1803        return None;
1804    }
1805    if boundaries.iter().any(|boundary| *boundary >= low - margin && *boundary <= high + margin) {
1806        return None;
1807    }
1808    Some(probe(0))
1809}
1810
1811fn build_surgery(
1812    solid: &BrepSolid,
1813    edge: &EdgeRecord,
1814    first: &BlendMate,
1815    second: &BlendMate,
1816    rows: FittedRows,
1817    second_split: Option<SecondSeamSplit>,
1818    name: Option<&str>,
1819    crease: Option<crate::blend::carve::CarvedCrease>,
1820) -> Result<BrepSolid, KernelRefusal> {
1821    let mut result = solid.clone();
1822    let mut take_id = crate::blend::edge::fresh_id_source(solid);
1823
1824    let [u_start, u_end] = rows.u_domain;
1825    let cr_start = rows.cr.evaluate(u_start).or_refuse(KernelStage::Refine, "evaluate")?;
1826    let cs_start = rows.cs.evaluate(u_start).or_refuse(KernelStage::Refine, "evaluate")?;
1827    let vertex1_id = take_id();
1828    let vertex2_id = take_id();
1829    result.vertices.push(VertexRecord {
1830        id: vertex1_id,
1831        point: cr_start,
1832    });
1833    result.vertices.push(VertexRecord {
1834        id: vertex2_id,
1835        point: cs_start,
1836    });
1837
1838    let cr_edge_id = take_id();
1839    result.edges.push(EdgeRecord {
1840        id: cr_edge_id,
1841        curve: rows.cr.clone(),
1842        t0: u_start,
1843        t1: u_end,
1844        start_vertex_id: vertex1_id,
1845        end_vertex_id: vertex1_id,
1846        degenerate: false,
1847        name: None,
1848    });
1849    // Second support: whole closed edge, or two pieces split where it
1850    // crosses ITS carrier's seam meridian (both-seam closed edges).  Each
1851    // piece records (edge id, fit-space window, forward pcurve).
1852    let mut cs_pieces: Vec<(u64, [f64; 2], NurbsCurve)> = Vec::new();
1853    let mut second_seam_vertex = vertex2_id;
1854    let mut second_seam_point = cs_start;
1855    let mut second_crossing_v = 0.0;
1856    if let Some(split) = &second_split {
1857        let p = split.fit_parameter;
1858        second_crossing_v = split.crossing_v;
1859        let (cs_a, cs_b) = rows.cs.split(p).or_refuse(KernelStage::Refine, "split")?;
1860        let (pc_a, pc_b) = rows.cs_pcurve.split(p).or_refuse(KernelStage::Refine, "split")?;
1861        // Bring the wrapped second piece back into the carrier's domain.
1862        let mut pc_b = pc_b;
1863        for point in pc_b.control_points.iter_mut() {
1864            point.x -= split.period * point.w;
1865        }
1866        let w2s = take_id();
1867        second_seam_vertex = w2s;
1868        second_seam_point = rows.cs.evaluate(p).or_refuse(KernelStage::Refine, "evaluate")?;
1869        result.vertices.push(VertexRecord {
1870            id: w2s,
1871            point: second_seam_point,
1872        });
1873        let edge_a = take_id();
1874        result.edges.push(EdgeRecord {
1875            id: edge_a,
1876            curve: cs_a,
1877            t0: u_start,
1878            t1: p,
1879            start_vertex_id: vertex2_id,
1880            end_vertex_id: w2s,
1881            degenerate: false,
1882            name: None,
1883        });
1884        cs_pieces.push((edge_a, [u_start, p], pc_a));
1885        let edge_b = take_id();
1886        result.edges.push(EdgeRecord {
1887            id: edge_b,
1888            curve: cs_b,
1889            t0: p,
1890            t1: u_end,
1891            start_vertex_id: w2s,
1892            end_vertex_id: vertex2_id,
1893            degenerate: false,
1894            name: None,
1895        });
1896        cs_pieces.push((edge_b, [p, u_end], pc_b));
1897    } else {
1898        let cs_edge_id = take_id();
1899        result.edges.push(EdgeRecord {
1900            id: cs_edge_id,
1901            curve: rows.cs.clone(),
1902            t0: u_start,
1903            t1: u_end,
1904            start_vertex_id: vertex2_id,
1905            end_vertex_id: vertex2_id,
1906            degenerate: false,
1907            name: None,
1908        });
1909        cs_pieces.push((cs_edge_id, [u_start, u_end], rows.cs_pcurve.clone()));
1910    }
1911    let seam_curve = rows.surface.iso_curve_u(u_start).or_refuse(KernelStage::Refine, "iso_curve_u")?;
1912    let [seam_t0, seam_t1] = seam_curve.domain().or_refuse(KernelStage::Refine, "domain")?;
1913    let blend_seam_id = take_id();
1914    result.edges.push(EdgeRecord {
1915        id: blend_seam_id,
1916        curve: seam_curve,
1917        t0: seam_t0,
1918        t1: seam_t1,
1919        start_vertex_id: vertex1_id,
1920        end_vertex_id: vertex2_id,
1921        degenerate: false,
1922        name: None,
1923    });
1924
1925    let replace_in_face = |result: &mut BrepSolid, mate: &BlendMate, pieces: &[(u64, [f64; 2], NurbsCurve)], uv_new: [f64; 2]| -> Result<bool, KernelRefusal> {
1926        replace_rim_in_face(result, edge, mate, pieces, uv_new)
1927    };
1928    let uv1_new = rows.cr_pcurve.evaluate(u_start).or_refuse(KernelStage::Refine, "evaluate")?;
1929    let v1_new = uv1_new.y;
1930    let cr_pieces = vec![(cr_edge_id, [u_start, u_end], rows.cr_pcurve.clone())];
1931    SEAM_CONSUMED.with(|flag| flag.set(None));
1932    let mut repaired = replace_in_face(&mut result, first, &cr_pieces, [uv1_new.x, v1_new])?;
1933    let uv2_new = rows.cs_pcurve.evaluate(u_start).or_refuse(KernelStage::Refine, "evaluate")?;
1934    let v2_new = if second_split.is_some() {
1935        second_crossing_v
1936    } else {
1937        uv2_new.y
1938    };
1939    repaired |= replace_in_face(&mut result, second, &cs_pieces, [uv2_new.x, v2_new])?;
1940
1941    // A contact circle about an axis oblique to a sphere's stored polar axis
1942    // can wind once around that sphere's U period.  Such a circle is not an
1943    // ordinary hole in the full-domain sphere rectangle: it bounds a cap with
1944    // one of the collapsed pole rims.  Keep that pole as the companion loop so
1945    // containment, integration, and tessellation see the actual cap topology.
1946    let collapse_winding_sphere_cap =
1947        |result: &mut BrepSolid, face_id: u64, support_ids: &[u64]| -> Result<(), KernelRefusal> {
1948            let face = result
1949                .shells
1950                .iter_mut()
1951                .flat_map(|shell| &mut shell.faces)
1952                .find(|face| face.id == face_id)
1953                .ok_or(KernelRefusal::internal(KernelStage::Sew, "sphere_carrier", "blend: sphere carrier lost during cap surgery"))?;
1954            if !matches!(
1955                face.surface.analytic(),
1956                Some(crate::AnalyticSurface::Sphere { .. })
1957            ) || face.surface.closed_directions().or_refuse(KernelStage::Refine, "closed_directions")? != (true, false)
1958            {
1959                return Ok(());
1960            }
1961            let [u0, u1] = face.surface.domain_u().or_refuse(KernelStage::Refine, "domain_u")?;
1962            let [v0, v1] = face.surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?;
1963            let period = u1 - u0;
1964            let support_loop = face.loops.iter().position(|loop_record| {
1965                !loop_record.coedges.is_empty()
1966                    && loop_record
1967                        .coedges
1968                        .iter()
1969                        .all(|coedge| support_ids.contains(&coedge.edge_id))
1970            });
1971            let Some(support_loop) = support_loop else {
1972                return Ok(());
1973            };
1974            if face.loops[support_loop].coedges.len() != 1 {
1975                return Ok(());
1976            }
1977            let support = &face.loops[support_loop].coedges[0];
1978            let [s0, s1] = support.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
1979            let support_start = support.pcurve.evaluate(s0).or_refuse(KernelStage::Refine, "evaluate")?;
1980            let support_end = support.pcurve.evaluate(s1).or_refuse(KernelStage::Refine, "evaluate")?;
1981            let support_winding = support_end.x - support_start.x;
1982            if (support_winding.abs() - period).abs() > 0.05 * period {
1983                return Ok(());
1984            }
1985
1986            let mut pole: Option<(usize, CoedgeRecord)> = None;
1987            for (loop_index, loop_record) in face.loops.iter().enumerate() {
1988                if loop_index == support_loop {
1989                    continue;
1990                }
1991                for coedge in &loop_record.coedges {
1992                    let [p0, p1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
1993                    let start = coedge.pcurve.evaluate(p0).or_refuse(KernelStage::Refine, "evaluate")?;
1994                    let end = coedge.pcurve.evaluate(p1).or_refuse(KernelStage::Refine, "evaluate")?;
1995                    let winding = end.x - start.x;
1996                    let at_pole = (start.y - v0).abs() <= 1e-8 || (start.y - v1).abs() <= 1e-8;
1997                    if at_pole
1998                        && (end.y - start.y).abs() <= 1e-8
1999                        && (winding.abs() - period).abs() <= 0.05 * period
2000                        && winding * support_winding < 0.0
2001                    {
2002                        pole = Some((loop_index, coedge.clone()));
2003                        break;
2004                    }
2005                }
2006                if pole.is_some() {
2007                    break;
2008                }
2009            }
2010            let Some((pole_loop, pole_coedge)) = pole else {
2011                return Ok(());
2012            };
2013            let support_record = face.loops[support_loop].clone();
2014            let pole_id = face.loops[pole_loop].id;
2015            face.loops = vec![
2016                LoopRecord {
2017                    id: pole_id,
2018                    coedges: vec![pole_coedge],
2019                },
2020                support_record,
2021            ];
2022            Ok(())
2023        };
2024    collapse_winding_sphere_cap(&mut result, first.face.id, &[cr_edge_id])?;
2025    let cs_edge_ids: Vec<u64> = cs_pieces.iter().map(|(edge_id, ..)| *edge_id).collect();
2026    collapse_winding_sphere_cap(&mut result, second.face.id, &cs_edge_ids)?;
2027    // Patch the zero coedge ids introduced for extra pieces.
2028    for shell in &mut result.shells {
2029        for face in &mut shell.faces {
2030            for loop_record in &mut face.loops {
2031                for coedge in &mut loop_record.coedges {
2032                    if coedge.id == 0 {
2033                        coedge.id = take_id();
2034                    }
2035                }
2036            }
2037        }
2038    }
2039
2040    // Trim seam EDGES that ended on the removed vertex: their endpoint
2041    // moves onto the support-curve crossing on THEIR carrier (first
2042    // mate's seam -> the blend seam vertex; second mate's -> its own
2043    // seam-crossing vertex).
2044    let new_edge_ids: Vec<u64> = std::iter::once(cr_edge_id)
2045        .chain(cs_pieces.iter().map(|(edge_id, ..)| *edge_id))
2046        .chain(std::iter::once(blend_seam_id))
2047        .collect();
2048    let first_face_edges: Vec<u64> = first
2049        .face
2050        .loops
2051        .iter()
2052        .flat_map(|loop_record| loop_record.coedges.iter().map(|coedge| coedge.edge_id))
2053        .collect();
2054    repaired |= trim_seam_edges(
2055        &mut result,
2056        edge,
2057        &new_edge_ids,
2058        &first_face_edges,
2059        (vertex1_id, v1_new, cr_start),
2060        (second_seam_vertex, v2_new, second_seam_point),
2061    )?;
2062
2063    // Blend face: outward orientation matches F1's outward at the v=0 rim.
2064    let mid_u = (u_start + u_end) * 0.5;
2065    let blend_normal = raw_normal(&rows.surface, mid_u, 0.0)?;
2066    let station_uv = rows.cr_pcurve.evaluate(mid_u).or_refuse(KernelStage::Refine, "evaluate")?;
2067    let n1 = raw_normal(&first.face.surface, station_uv.x, station_uv.y)?;
2068    let out1 = if first.face.same_sense {
2069        n1
2070    } else {
2071        n1.scale(-1.0)
2072    };
2073    // A rolling ball's wall is tangent to F1 at the rim, so F1's outward
2074    // normal settles its side.  An asymmetric chamfer's bevel is not: a steep
2075    // one (a short chord on F1, a long one on F2) turns more than a right
2076    // angle from F1, and F1's normal alone reads it backwards.  The bevel
2077    // always lies between its two faces, so it is read against both.
2078    let same_sense = if crate::blend::setback::active().is_some() {
2079        let uv2 = rows.cs_pcurve.evaluate(mid_u).or_refuse(KernelStage::Refine, "evaluate")?;
2080        let n2 = raw_normal(&second.face.surface, uv2.x, uv2.y)?;
2081        let out2 = if second.face.same_sense { n2 } else { n2.scale(-1.0) };
2082        let v_far = rows.surface.domain_v().or_refuse(KernelStage::Refine, "domain_v")?[1];
2083        let far_normal = raw_normal(&rows.surface, mid_u, v_far)?;
2084        blend_normal.dot(out1) + far_normal.dot(out2) >= 0.0
2085    } else {
2086        blend_normal.dot(out1) >= 0.0
2087    };
2088    let loop_id = take_id();
2089    let mut coedges = vec![
2090        CoedgeRecord {
2091            id: take_id(),
2092            edge_id: cr_edge_id,
2093            forward: true,
2094            pcurve: crate::sweep_topology::parameter_line(u_start, 0.0, u_end, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?,
2095        },
2096        CoedgeRecord {
2097            id: take_id(),
2098            edge_id: blend_seam_id,
2099            forward: true,
2100            pcurve: crate::sweep_topology::parameter_line(u_end, 0.0, u_end, 1.0).or_refuse(KernelStage::Refine, "parameter_line")?,
2101        },
2102    ];
2103    for (edge_id, window, _) in cs_pieces.iter().rev() {
2104        coedges.push(CoedgeRecord {
2105            id: take_id(),
2106            edge_id: *edge_id,
2107            forward: false,
2108            pcurve: crate::sweep_topology::parameter_line(window[1], 1.0, window[0], 1.0).or_refuse(KernelStage::Refine, "parameter_line")?,
2109        });
2110    }
2111    coedges.push(CoedgeRecord {
2112        id: take_id(),
2113        edge_id: blend_seam_id,
2114        forward: false,
2115        pcurve: crate::sweep_topology::parameter_line(u_start, 1.0, u_start, 0.0).or_refuse(KernelStage::Refine, "parameter_line")?,
2116    });
2117    // The coedges above trace the parameter rectangle counter-clockwise in
2118    // (u, v); that traversal is only the outward boundary when the blend
2119    // surface normal already points outward (same_sense).  When it does not
2120    // (a mate whose support rim runs the other way — e.g. the reversed cap
2121    // of a seam carrier), the loop must wind the OTHER way so its coedges
2122    // traverse the shared support edges opposite to the mate, and so the
2123    // classification tangent test (parameter_point_in_face) stays consistent
2124    // with same_sense.  Reversing the coedge order and each coedge (forward
2125    // flag + pcurve) flips the winding without touching same_sense.
2126    if !same_sense {
2127        coedges.reverse();
2128        for coedge in &mut coedges {
2129            coedge.forward = !coedge.forward;
2130            coedge.pcurve = coedge.pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?;
2131        }
2132    }
2133    let mut loops = vec![LoopRecord {
2134        id: loop_id,
2135        coedges,
2136    }];
2137    // The CARVED lens: an INNER loop of two coedges on ONE new edge — the
2138    // crease — both of them this face's own, the slit pattern the closed
2139    // chain lane sews (`chain/closed_surgery.rs`): the two sheets of the wall
2140    // are one surface, so the curve where they meet has one edge and two
2141    // coedges.  The lens between them is the part of the swept envelope
2142    // inside the swept ball volume, and dropping it is what makes the wall
2143    // the blend.  Winding: the inner loop runs AGAINST the outer one, read
2144    // off both loops' signed areas rather than assumed.
2145    if let Some(crease) = crease {
2146        let start_vertex = take_id();
2147        let end_vertex = take_id();
2148        let crease_edge = take_id();
2149        result.vertices.push(VertexRecord { id: start_vertex, point: crease.start });
2150        result.vertices.push(VertexRecord { id: end_vertex, point: crease.end });
2151        let [crease_t0, crease_t1] = crease.curve.domain().or_refuse(KernelStage::Refine, "domain")?;
2152        result.edges.push(EdgeRecord {
2153            id: crease_edge,
2154            curve: crease.curve,
2155            t0: crease_t0,
2156            t1: crease_t1,
2157            start_vertex_id: start_vertex,
2158            end_vertex_id: end_vertex,
2159            degenerate: false,
2160            name: name.map(|value| format!("{value}:CREASE")),
2161        });
2162        let outer = crate::blend::chain::signed_area(&loops[0].coedges)?;
2163        let forward_first = crate::blend::chain::signed_area(&[
2164            CoedgeRecord { id: 0, edge_id: crease_edge, forward: true, pcurve: crease.first.clone() },
2165            CoedgeRecord { id: 0, edge_id: crease_edge, forward: false, pcurve: crease.second.reversed().or_refuse(KernelStage::Refine, "reversed")? },
2166        ])?;
2167        let inner = if outer * forward_first < 0.0 {
2168            vec![
2169                CoedgeRecord { id: take_id(), edge_id: crease_edge, forward: true, pcurve: crease.first },
2170                CoedgeRecord { id: take_id(), edge_id: crease_edge, forward: false, pcurve: crease.second.reversed().or_refuse(KernelStage::Refine, "reversed")? },
2171            ]
2172        } else {
2173            vec![
2174                CoedgeRecord { id: take_id(), edge_id: crease_edge, forward: true, pcurve: crease.second },
2175                CoedgeRecord { id: take_id(), edge_id: crease_edge, forward: false, pcurve: crease.first.reversed().or_refuse(KernelStage::Refine, "reversed")? },
2176            ]
2177        };
2178        loops.push(LoopRecord { id: take_id(), coedges: inner });
2179    }
2180    let blend_face = FaceRecord {
2181        id: take_id(),
2182        surface: rows.surface,
2183        same_sense,
2184        loops,
2185        name: name.map(|value| value.to_string()),
2186    };
2187    let shell_index = result
2188        .shells
2189        .iter()
2190        .position(|shell| shell.faces.iter().any(|face| face.id == first.face.id))
2191        .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_shell", "blend: mate shell lost during surgery"))?;
2192    result.shells[shell_index].faces.push(blend_face);
2193
2194    let used_edges: std::collections::HashSet<u64> = result
2195        .shells
2196        .iter()
2197        .flat_map(|shell| &shell.faces)
2198        .flat_map(|face| &face.loops)
2199        .flat_map(|loop_record| &loop_record.coedges)
2200        .map(|coedge| coedge.edge_id)
2201        .collect();
2202    result
2203        .edges
2204        .retain(|candidate| used_edges.contains(&candidate.id));
2205    let used_vertices: std::collections::HashSet<u64> = result
2206        .edges
2207        .iter()
2208        .flat_map(|candidate| [candidate.start_vertex_id, candidate.end_vertex_id])
2209        .collect();
2210    result
2211        .vertices
2212        .retain(|candidate| used_vertices.contains(&candidate.id));
2213    // A surgery that had to REPAIR a neighbour trim took a branch no existing
2214    // fixture exercises, so it does not get the benefit of the doubt: prove the
2215    // result before returning it.  Paths that never repaired are untouched (the
2216    // check does not run), so this cannot slow or change anything that already
2217    // works — and the new branch can never ship a plausible-looking wrong solid
2218    // the way the un-repaired trim did.
2219    let consumed = SEAM_CONSUMED.with(|flag| flag.take());
2220    if repaired {
2221        let problems = result.validate_memoised();
2222        if !problems.is_empty() {
2223            // A setback that consumed a whole face and left a body that does
2224            // not stand is refused by name.
2225            if let (Some(face_id), true) = (consumed, crate::blend::setback::setback_consumed_face_refusal_on()) {
2226                return Err(crate::blend::setback::unsupported(
2227                    "setback_consumes_face",
2228                    format!(
2229                        "asymmetric chamfer: the setback on face {face_id} reaches that face's far edge, which \
2230                         would consume the whole face — refusing"
2231                    ),
2232                ));
2233            }
2234            return Err(KernelRefusal::internal(KernelStage::Validate, "neighbour_trim_closure", format!(
2235                "blend: the repaired neighbour trim did not close ({} issue(s), first: {})",
2236                problems.len(),
2237                problems
2238                    .first()
2239                    .map(|issue| issue.message.as_str())
2240                    .unwrap_or("unknown")
2241            )));
2242        }
2243    }
2244    Ok(result)
2245}
2246
2247thread_local! {
2248    /// The face whose seam a setback's trim shrank to a point during the
2249    /// surgery in progress (`replace_rim_in_face`), if any.
2250    static SEAM_CONSUMED: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
2251}
2252
2253/// Replace the blended edge's coedge in one mate's loop with the support
2254/// pieces (edge id, fit-space window, forward pcurve) in u order, and pull
2255/// the loop's seam-meridian pcurves that met the removed vertex down to the
2256/// support crossing at `uv_new` on this carrier. `true` when a neighbour trim
2257/// was repaired. The closed lane's own surgery and the rollover's share it.
2258pub(in crate::blend) fn replace_rim_in_face(
2259    result: &mut BrepSolid,
2260    edge: &EdgeRecord,
2261    mate: &BlendMate,
2262    pieces: &[(u64, [f64; 2], NurbsCurve)],
2263    uv_new: [f64; 2],
2264) -> Result<bool, KernelRefusal> {
2265    let old_vertex = edge.start_vertex_id;
2266    let v_new = uv_new[1];
2267    // (edge id, the START vertex is the removed one, the END vertex is).
2268    let seam_edge_ends: Vec<(u64, bool, bool)> = result
2269        .edges
2270        .iter()
2271        .filter(|candidate| {
2272            candidate.id != edge.id
2273                && (candidate.start_vertex_id == old_vertex
2274                    || candidate.end_vertex_id == old_vertex)
2275        })
2276        .map(|candidate| {
2277            (
2278                candidate.id,
2279                candidate.start_vertex_id == old_vertex,
2280                candidate.end_vertex_id == old_vertex,
2281            )
2282        })
2283        .collect();
2284    let seam_edge_ids: Vec<u64> = seam_edge_ends.iter().map(|(id, ..)| *id).collect();
2285    let pcurve_band = crate::KernelTolerances::for_solid(result, 1e-7).pcurve_consistency;
2286    let debug = std::env::var("BREP_DEBUG_NETWORK").is_ok();
2287    let face = result
2288        .shells
2289        .iter_mut()
2290        .flat_map(|shell| &mut shell.faces)
2291        .find(|face| face.id == mate.face.id)
2292        .ok_or(KernelRefusal::internal(KernelStage::Sew, "mate_face", "blend: mate face lost during surgery"))?;
2293    let face_id = face.id;
2294    let FaceRecord { surface, loops, .. } = &mut *face;
2295    let loop_record = &mut loops[mate.loop_index];
2296    let position = loop_record
2297        .coedges
2298        .iter()
2299        .position(|coedge| coedge.edge_id == edge.id)
2300        .ok_or(KernelRefusal::internal(KernelStage::Sew, "edge_coedge", "blend: edge coedge lost during surgery"))?;
2301    let old_forward = loop_record.coedges[position].forward;
2302    let old_seam_v = {
2303        let pcurve = &loop_record.coedges[position].pcurve;
2304        let [d0, _] = pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
2305        pcurve.evaluate(d0).or_refuse(KernelStage::Refine, "evaluate")?.y
2306    };
2307    // Replacement coedges: pieces run in u order; a reversed loop use
2308    // takes them in reverse order, each reversed.
2309    let mut replacements = Vec::new();
2310    let ordered: Vec<&(u64, [f64; 2], NurbsCurve)> = if old_forward {
2311        pieces.iter().collect()
2312    } else {
2313        pieces.iter().rev().collect()
2314    };
2315    for (index, (edge_id, _, pcurve)) in ordered.iter().enumerate() {
2316        replacements.push(CoedgeRecord {
2317            id: if index == 0 {
2318                loop_record.coedges[position].id
2319            } else {
2320                0 // patched by the caller with fresh ids
2321            },
2322            edge_id: *edge_id,
2323            forward: old_forward,
2324            pcurve: if old_forward {
2325                pcurve.clone()
2326            } else {
2327                pcurve.reversed().or_refuse(KernelStage::Refine, "reversed")?
2328            },
2329        });
2330    }
2331    loop_record
2332        .coedges
2333        .splice(position..=position, replacements);
2334    let mut repaired = false;
2335    if loop_record.coedges.len() > 1 {
2336        // Anchored carrier: the loop's other coedges ride the seam
2337        // meridian between the old edge and the rest of the trim.
2338        // Pull the pcurve endpoint that met the old edge down to the
2339        // support crossing.  (The seam EDGE itself is trimmed after
2340        // both replacements, outside this borrow.)
2341        for coedge in &mut loop_record.coedges {
2342            if pieces
2343                .iter()
2344                .any(|(edge_id, ..)| *edge_id == coedge.edge_id)
2345                || !seam_edge_ids.contains(&coedge.edge_id)
2346            {
2347                continue;
2348            }
2349            let controls = &coedge.pcurve.control_points;
2350            let last_index = controls.len() - 1;
2351            let first_u = controls[0].x / controls[0].w;
2352            let last_u = controls[last_index].x / controls[last_index].w;
2353            let constant_u = (first_u - last_u).abs()
2354                <= 1e-9 * (1.0 + first_u.abs().max(last_u.abs()));
2355            // Which end of the pcurve met the removed vertex, and the uv
2356            // the crossing sits at on this carrier.
2357            let (target, target_uv, fraction) = if constant_u {
2358                // Seam MERIDIAN pcurve: constant u, runs along the v
2359                // direction; the endpoint at the removed edge's v moves
2360                // onto the support crossing.
2361                let first_v = controls[0].y / controls[0].w;
2362                let last_v = controls[last_index].y / controls[last_index].w;
2363                let target = if (first_v - old_seam_v).abs() < (last_v - old_seam_v).abs() {
2364                    0
2365                } else {
2366                    last_index
2367                };
2368                let span = last_v - first_v;
2369                let fraction = if span.abs() > 0.0 { (v_new - first_v) / span } else { 0.0 };
2370                (target, [first_u, v_new], fraction)
2371            } else {
2372                // The adjacent trim runs along U at constant v — the
2373                // carrier's OTHER (v) seam, which is what a closed edge
2374                // lying on one whole MERIDIAN borders (an axial-plane
2375                // collar on a torus).  Its endpoint moves in U, not V,
2376                // and the v-distance rule above cannot pick the end at
2377                // all: both ends share the same v, so it always lands on
2378                // `last_index`, which is wrong for one of the seam PAIR
2379                // (the v-seam edge appears twice in the loop, at v = 0
2380                // and v = 1).  Take the end from the TOPOLOGY.
2381                let Some((_, start_is_old, end_is_old)) = seam_edge_ends
2382                    .iter()
2383                    .find(|(id, ..)| *id == coedge.edge_id)
2384                    .copied()
2385                else {
2386                    continue;
2387                };
2388                if start_is_old == end_is_old {
2389                    return Err(KernelRefusal::ill_posed(KernelStage::Sew, "neighbour_trim_end", format!(
2390                        "blend: neighbour edge {} meets the blended edge at both ends; \
2391                         its trim end is ambiguous",
2392                        coedge.edge_id
2393                    )));
2394                }
2395                // `forward` maps the coedge's pcurve domain start onto the
2396                // edge's t0 (its start vertex).
2397                let target = if start_is_old == coedge.forward { 0 } else { last_index };
2398                let v_end = controls[target].y / controls[target].w;
2399                let span = last_u - first_u;
2400                let fraction = if span.abs() > 0.0 { (uv_new[0] - first_u) / span } else { 0.0 };
2401                (target, [uv_new[0], v_end], fraction)
2402            };
2403            // The trim is a SPLIT of the pcurve at the crossing's own
2404            // parameter, never a moved control point.  Moving the end
2405            // control point of a pcurve with interior knots re-slopes its
2406            // end span alone and breaks the pcurve ↔ edge parameter
2407            // correspondence validate reads (measured 2026-10-03 on the
2408            // torus-box-edge and axial-collar documents: the torus's
2409            // v-seam pcurve, a 3-span polyline, read 0.548 mm off its
2410            // edge at the same parameter while its image was on the edge
2411            // to 1e-10).  The seam-edge pass below projects the same
2412            // physical point onto the edge curve for the edge's own
2413            // parameter, so both sides keep the correspondence they had.
2414            let [q0, q1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
2415            let target_point = surface
2416                .evaluate_extended(target_uv[0], target_uv[1])
2417                .or_refuse(KernelStage::Refine, "evaluate_extended")?;
2418            // Seeded at the AFFINE fraction of the pcurve's extent in the
2419            // moving direction (the seed `trim_edge_at` uses), not at the
2420            // pcurve's end: a crossing deep in a long seam would hand the
2421            // point solver a far seed and turn a blend that built into a
2422            // refusal.  The solver refines the seed to the physical point.
2423            let seed = (q0 + (q1 - q0) * fraction).clamp(q0.min(q1), q0.max(q1));
2424            let q_split = trim_parameter_at_point(
2425                surface, &coedge.pcurve, seed, target_point, pcurve_band,
2426            )?;
2427            let interior = q_split > q0 + 1e-9 * (q1 - q0) && q_split < q1 - 1e-9 * (q1 - q0);
2428            if debug {
2429                eprintln!(
2430                    "closed-edge seam trim: face {face_id} edge {} coedge {} ({}): {} at q {q_split:.9} of [{q0:.6}, {q1:.6}], {} control points",
2431                    coedge.edge_id, coedge.id, if constant_u { "meridian, constant u" } else { "along u" },
2432                    if interior { "SPLIT" } else { "EXTEND" }, controls.len()
2433                );
2434            }
2435            if interior {
2436                let (low, high) = coedge.pcurve.split(q_split).or_refuse(KernelStage::Refine, "split")?;
2437                coedge.pcurve = if target == 0 { high } else { low };
2438            } else {
2439                // The crossing lies at or past the pcurve's end: the seam
2440                // EXTENDS to meet it.  Exact for a two-point linear
2441                // pcurve, whose one span IS the whole parameterisation;
2442                // anything else would need a refit and is refused by name.
2443                if coedge.pcurve.degree != 1 || controls.len() != 2 {
2444                    return Err(KernelRefusal::unsupported(KernelStage::Sew, "neighbour_seam_extend_curved", format!(
2445                        "blend: neighbour seam edge {} would have to extend past its own end to meet the blend's support crossing, and its pcurve is not a single straight span (degree {}, {} control points)",
2446                        coedge.edge_id, coedge.pcurve.degree, controls.len()
2447                    )));
2448                }
2449                let w = coedge.pcurve.control_points[target].w;
2450                coedge.pcurve.control_points[target] = crate::Vec4::from_point(
2451                    Vec3::new(target_uv[0], target_uv[1], 0.0), w,
2452                );
2453            }
2454            // An asymmetric chamfer whose setback reaches the far end of this
2455            // seam consumes the whole face: the seam shrinks to a point. Noted
2456            // here; the surgery's own validation decides whether the body
2457            // stands (a ball's whole bore consumed does), and names the
2458            // refusal where it does not.
2459            if crate::blend::setback::active().is_some() {
2460                let [p0, p1] = coedge.pcurve.domain().or_refuse(KernelStage::Refine, "domain")?;
2461                let (a, b) = (
2462                    coedge.pcurve.evaluate(p0).or_refuse(KernelStage::Refine, "evaluate")?,
2463                    coedge.pcurve.evaluate(p1).or_refuse(KernelStage::Refine, "evaluate")?,
2464                );
2465                if a.sub(b).length() <= 1e-12 * (1.0 + a.length()) {
2466                    SEAM_CONSUMED.with(|flag| flag.set(Some(face_id)));
2467                }
2468            }
2469            repaired = true;
2470        }
2471    }
2472    Ok(repaired)
2473}
2474
2475/// Trim the seam EDGES that ended on the removed vertex: each endpoint moves
2476/// onto the support crossing on ITS carrier — an edge of the first mate's
2477/// face to `first_target`, any other to `second_target`, each a (vertex,
2478/// seam-meridian parameter, point). `new_edge_ids` are the surgery's own
2479/// edges, skipped. `true` when a trim had to be re-projected (repaired).
2480pub(in crate::blend) fn trim_seam_edges(
2481    result: &mut BrepSolid,
2482    edge: &EdgeRecord,
2483    new_edge_ids: &[u64],
2484    first_face_edges: &[u64],
2485    first_target: (u64, f64, Vec3),
2486    second_target: (u64, f64, Vec3),
2487) -> Result<bool, KernelRefusal> {
2488    let old_vertex = edge.start_vertex_id;
2489    let mut repaired = false;
2490    let (vertex1_id, v1_new, cr_start) = first_target;
2491    let (second_seam_vertex, v2_new, second_seam_point) = second_target;
2492    for seam_edge in result.edges.iter_mut() {
2493        if new_edge_ids.contains(&seam_edge.id) {
2494            continue;
2495        }
2496        if seam_edge.start_vertex_id != old_vertex && seam_edge.end_vertex_id != old_vertex {
2497            continue;
2498        }
2499        let (target_vertex, target_v, target_point) = if first_face_edges.contains(&seam_edge.id) {
2500            (vertex1_id, v1_new, cr_start)
2501        } else {
2502            (second_seam_vertex, v2_new, second_seam_point)
2503        };
2504        let [c0, c1] = seam_edge.curve.domain().or_refuse(KernelStage::Refine, "domain")?;
2505        let clamped = target_v.clamp(c0.min(c1), c0.max(c1));
2506        // Using the support crossing's V as the neighbour's CURVE parameter is
2507        // only valid when that neighbour is the carrier's seam MERIDIAN, whose
2508        // 3D curve is parameterized by v.  Verify it against the vertex the
2509        // endpoint is moving to; a neighbour running along U instead (the
2510        // carrier's v-seam, bordered by a collar edge that lies on one whole
2511        // meridian) lands nowhere near it — the 2026-09-01 report trimmed the
2512        // torus' equator seam to u = 0, 10.885 away from its own vertex, and
2513        // the solid failed validation with "curve start does not match vertex".
2514        let band = 1e-6 * (1.0 + target_point.length());
2515        let split_parameter = if seam_edge.id == edge.id {
2516            // The BLENDED edge itself still carries the removed vertex at this
2517            // point.  Its coedges have already been replaced in both mates, so
2518            // the used-edge sweep below discards it; leave its (meaningless)
2519            // trim exactly as it was rather than asking a doomed edge to pass
2520            // through the support start.
2521            clamped
2522        } else {
2523            match seam_edge.curve.evaluate(clamped) {
2524                Ok(point) if point.sub(target_point).length() <= band => clamped,
2525                _ => {
2526                    repaired = true;
2527                    let projection =
2528                        crate::project_point_to_curve(&seam_edge.curve, target_point).or_refuse(KernelStage::Refine, "project_point_to_curve")?;
2529                    if projection.distance > band {
2530                        return Err(KernelRefusal::unsupported(KernelStage::Sew, "neighbour_off_support", format!(
2531                            "blend: neighbour edge {} does not pass through the blend's support \
2532                             start (off by {:.9}); the trim has no parameter to move to",
2533                            seam_edge.id, projection.distance
2534                        )));
2535                    }
2536                    projection.u.clamp(c0.min(c1), c0.max(c1))
2537                }
2538            }
2539        };
2540        if seam_edge.start_vertex_id == old_vertex {
2541            seam_edge.t0 = split_parameter;
2542            seam_edge.start_vertex_id = target_vertex;
2543        }
2544        if seam_edge.end_vertex_id == old_vertex {
2545            seam_edge.t1 = split_parameter;
2546            seam_edge.end_vertex_id = target_vertex;
2547        }
2548    }
2549    Ok(repaired)
2550}