Skip to main content

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