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