Skip to main content

brep_kernel/feature_pipeline/
mod.rs

1//! Feature-history execution with exact name resolution and stable output names.
2//!
3//! [`execute_history`] updates its live [`SceneMap`] after every feature. Reference
4//! parameters resolve by exact name; misses produce structured `unresolved`
5//! entries in [`FeatureResult`]. Output names must preserve saved-document naming
6//! conventions because later features store those names as references.
7//!
8//! Feature descriptors retain `{type, inputParams, persistentData, timestamp}`.
9//! Numeric parameters accept literals or expressions evaluated against [`Env`].
10//!
11//! Registry borrows stay local to each operation and never span feature execution.
12//! Features call Rust operations directly, preserving names on resident solids.
13//! Removed scene solids and consumed intermediates must release their handles.
14
15pub mod extension;
16
17use serde::{Deserialize, Serialize};
18use std::collections::HashMap;
19use wasm_bindgen::prelude::*;
20
21use crate::{KernelRefusal, NurbsCurve, Vec3};
22
23// The scene component concept (assemblies): component records + per-instance
24// entity-name namespacing at the component boundary. See component.rs.
25pub(crate) mod component;
26pub use component::ComponentRecord;
27// The per-document parts library (assemblies): unique part payloads the ACOMP
28// instance feature references by name; kernel-resident, request-seeded,
29// GC'd at the end of every history run. See parts_library.rs.
30pub(crate) mod parts_library;
31pub use parts_library::{
32    add_part_to_library, add_part_to_library_impl, install_parts_library, missing_library_parts,
33    parts_library_json, parts_library_map, parts_library_revision, refresh_library_entry,
34    refresh_library_entry_impl, same_build,
35    PartsLibraryEntry, PartsLibraryMap, stable_json_hash,
36};
37// Assembly constraint state + lifecycle: the `assembly` history block, the
38// ten constraint schemas, the mate-mapping + solve tail, and the exported
39// constraint-mutation ABI. See assembly.rs.
40pub mod assembly;
41/// Wire-harness routing: the document's `wireHarness` block, the sided port
42/// graph, per-connection routes and the bundle solids — solved at the tail of
43/// every run like `assembly` (see `wire_harness.rs`).
44pub mod wire_harness;
45/// A part's symbol pins ARE its harness ports, bound by label (eCAD plan
46/// decision 8): the pin/port report, following an edit from one side to the
47/// other, and resolving a placed part's pin to its port id (see `part_pins.rs`).
48pub mod part_pins;
49pub mod pmi;
50pub mod ports;
51pub(crate) use features::import3d::imported_solid_names;
52pub use assembly::{AssemblyState, ConstraintEntry};
53mod expression;
54#[path = "features/mod.rs"]
55pub(crate) mod features;
56pub use features::common::{first_reference_name, reference_names};
57/// The NURBS Solid's cage resolver, which the engine's cage editor reads its
58/// handles through (`resolve_cage`, `primitive_cage`, `has_persisted_cage`).
59pub use features::nurbs_solid;
60pub(crate) use features::transform::bbox_center as transform_bbox_center;
61// Transform Face's default pivot over a replayed prefix: the value the app
62// stores into `pivot` when a face selection is committed, computed by the same
63// resolution and centre the feature falls back to for a null pivot.
64pub use features::transform_face::face_transform_pivot;
65// The native IMPORT3D payload encoder: finished solids → an `io/snapshot`
66// payload carrying IMPORT3D's own names, ready to become an
67// `inputParams.nativeBrep` part document. Lives WITH the feature that reads it
68// back (one naming convention, one implementation); exported for the import
69// lanes that build part documents.
70pub use features::import3d::{native_import_payload, native_import_payload_with_appearance};
71pub(crate) mod scene_metadata;
72// The scene-metadata isolation bracket, for out-of-crate producers that encode a
73// payload against a LIVE document (the STEP-assembly import lane).
74pub use scene_metadata::IsolatedSceneMetadata;
75// The colour-only read of the name-keyed store: THREAD-LOCAL, so a caller whose
76// history runs off-thread must read it runner-side (`io/appearance.rs`).
77pub use scene_metadata::scene_metadata_colors_json;
78mod schema;
79// The kernel-owned feature-schema catalogue, reachable by NATIVE Rust consumers
80// (the engine-native egui UI in brep-app, via a brep-render re-export) — the same
81// definitions the wasm `feature_schemas_json` export serves the caller's feature registry.
82pub use schema::feature_schema_catalogue;
83pub use schema::feature_hidden_params;
84pub mod context_offer;
85// Selection-context applicability: the per-feature show/no-show predicates the
86// app's context bar runs against the current selection (schema.rs's sibling —
87// definitions live with each feature, this only aggregates).
88pub use context_offer::{feature_context_applicable, SelectionProbe};
89#[path = "sheet_metal/mod.rs"]
90mod sheet_metal;
91// Flat-pattern (unfold) → 2D vector export, for the native engine's export lane.
92// Keyed by resident handle so `SheetTree` stays private to the pipeline.
93pub use sheet_metal::{flat_pattern_dxf, flat_pattern_svg, is_sheet_metal_handle};
94
95pub use expression::Env;
96// The sketch loop-id write-back (the editor calls it on commit) — the
97// persistence half of the per-loop face-naming scheme. See
98// `features/sketch/loop_ids.rs`.
99pub use features::sketch::assign_sketch_loop_ids;
100
101// ===========================================================================
102// Descriptor — the serialized `{ type, inputParams, persistentData, timestamp }`
103// ===========================================================================
104
105/// One feature as serialized by `PartHistory.toSerializable`. Permissive: unknown
106/// fields are ignored, so an entire saved part file's `features[]` deserializes
107/// as-is. `input_params` stays a `serde_json::Value` (an object) so features read
108/// their own params with their own type knowledge (which params are numeric).
109// `persistent_data` / `timestamp` are contract pass-throughs (round-tripped for
110// features that need them, e.g. hole/pattern persistent state); not read yet.
111#[allow(dead_code)]
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct FeatureDescriptor {
114    #[serde(rename = "type", default)]
115    pub feature_type: String,
116    #[serde(rename = "inputParams", default)]
117    pub input_params: serde_json::Value,
118    #[serde(rename = "persistentData", default)]
119    pub persistent_data: serde_json::Value,
120    /// Opaque pass-through (any shape) so one odd saved file cannot fail the parse.
121    #[serde(default)]
122    pub timestamp: Option<serde_json::Value>,
123}
124
125/// The `execute_history_json` request: the expression source, the configurator
126/// state, and the ordered feature list. Permissive — a whole saved part file
127/// parses as a request (extra top-level fields ignored).
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct HistoryRequest {
130    #[serde(default, skip_serializing_if = "Vec::is_empty")]
131    pub plugins: Vec<extension::PluginPin>,
132    #[serde(default, deserialize_with = "de_string_lenient")]
133    pub expressions: String,
134    #[serde(default)]
135    pub configurator: serde_json::Value,
136    #[serde(default)]
137    pub features: Vec<FeatureDescriptor>,
138    /// One-shot execution directive: rebuild these features even if their inputs
139    /// match the cache (for example, when a dimension drag is finalized). Their
140    /// consumers follow the usual dirty wavefront. Not part of the saved model.
141    #[serde(default, rename = "forceRebuild", skip_serializing_if = "Vec::is_empty")]
142    pub force_rebuild: Vec<String>,
143    /// Stop AFTER executing the feature with this id (the editor's "stop at the
144    /// expanded feature"). The features past the stop stay in the request so the
145    /// incremental cache RETAINS their entries — expanding/collapsing a panel
146    /// must not thrash the cache (marshal-side truncation would free them).
147    #[serde(default, rename = "stopAtId")]
148    pub stop_at_id: Option<String>,
149    /// Stop BEFORE executing the feature with this id.
150    #[serde(default, rename = "stopBeforeId")]
151    pub stop_before_id: Option<String>,
152    /// The assembly constraint block: `{ constraints, idCounter }`. Absent on
153    /// every non-assembly document (and omitted on re-serialize, so
154    /// componentless files persist byte-identically). Solved at the tail of
155    /// every run; see `assembly.rs`.
156    #[serde(default, skip_serializing_if = "Option::is_none")]
157    pub assembly: Option<assembly::AssemblyState>,
158    /// The wire-harness block: `{ connections, idCounter, buildBundles }`.
159    /// Absent on every document without harness connections (and omitted on
160    /// re-serialize). Routed at the tail of every run; see `wire_harness.rs`.
161    #[serde(default, rename = "wireHarness", skip_serializing_if = "Option::is_none")]
162    pub wire_harness: Option<wire_harness::WireHarnessState>,
163    /// The PMI block: `{ views: [{ id, name, camera, display, annotations }],
164    /// idCounter }`. Absent on every document without PMI (and omitted on
165    /// re-serialize). Resolved at the tail of every run; see `pmi.rs`.
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub pmi: Option<pmi::PmiState>,
168    /// Render level-of-detail factor for DISPLAY tessellation (the app's "LOD
169    /// factor" setting). `execute_history` ignores it — it rides on the request
170    /// only because the request is the serialized run boundary the display runner
171    /// receives, and the runner scales its per-solid chord tolerance by it
172    /// (higher = coarser mesh). Defaults to `1.0` (the "Normal" preset) so a saved
173    /// file / seed request with no `displayLod` tessellates exactly as before.
174    #[serde(default = "default_display_lod", rename = "displayLod")]
175    pub display_lod: f64,
176    /// The parts library block: unique part payloads the ACOMP instance
177    /// features reference by name. Ingested into the kernel-resident library
178    /// at the start of every run (this is how a LOADED document seeds it);
179    /// SAVE serializes `parts_library_json()` back out — never this loaded
180    /// block (see parts_library.rs).
181    #[serde(default, rename = "partsLibrary")]
182    pub parts_library: parts_library::PartsLibraryMap,
183    /// The declared-ports block: the part's connection points as DATA, a
184    /// sibling of `features` (see `ports.rs`). Absent on every document that
185    /// declares none (and omitted on re-serialize). Resolved at the tail of
186    /// every run, against the finished scene.
187    #[serde(default, skip_serializing_if = "Vec::is_empty")]
188    pub ports: Vec<ports::PortDeclaration>,
189    /// The EXPLICIT encapsulation mark: `true` hides this document's children
190    /// behind its declared ports, `false` keeps them reachable. Absent means
191    /// derive it — see [`ports::document_is_boundary`].
192    #[serde(default, rename = "portBoundary", skip_serializing_if = "Option::is_none")]
193    pub port_boundary: Option<bool>,
194    /// Whether the document carries a `pcb` block, which makes it a board and
195    /// therefore a port boundary by construction. Presence ONLY: the block
196    /// itself is eCAD's and the kernel neither reads nor rewrites it, so this
197    /// never serializes back out.
198    #[serde(
199        default,
200        rename = "pcb",
201        deserialize_with = "de_present",
202        skip_serializing
203    )]
204    pub pcb_present: bool,
205}
206
207/// Deserialize any value as "it was there" - see [`HistoryRequest::pcb_present`].
208fn de_present<'de, D>(deserializer: D) -> Result<bool, D::Error>
209where
210    D: serde::Deserializer<'de>,
211{
212    serde::Deserialize::deserialize(deserializer).map(|_: serde::de::IgnoredAny| true)
213}
214
215/// The "Normal" render LOD — the [`HistoryRequest::display_lod`] serde default.
216fn default_display_lod() -> f64 {
217    1.0
218}
219
220/// Accept `null`/missing as `""` for a string field (saved files sometimes store
221/// `expressions: null`).
222fn de_string_lenient<'de, D>(deserializer: D) -> Result<String, D::Error>
223where
224    D: serde::Deserializer<'de>,
225{
226    let value = Option::<String>::deserialize(deserializer)?;
227    Ok(value.unwrap_or_default())
228}
229
230// ===========================================================================
231// Result — the per-feature output contract the caller consumes
232// ===========================================================================
233
234/// A solid produced by a feature: its resident handle, its solid name, and its
235/// named faces/edges (`(topology_id, name)`). the caller tessellates/pulls names via the
236/// handle; the scene-map registers the names for downstream reference resolution.
237#[derive(Debug, Clone, Default, Serialize)]
238pub struct AddedSolid {
239    pub handle: u32,
240    pub name: String,
241    pub face_names: Vec<(u64, String)>,
242    /// Edge names propagated/authored on the solid. Present so edge-selecting
243    /// features (fillet/chamfer) can resolve "the edge of the extrude above"
244    /// against the scene-map — the pinned example in contract rule 1.
245    pub edge_names: Vec<(u64, String)>,
246    /// CONTAINER groups: `(container_name, member face NAMES)`. A profile-swept
247    /// feature registers the un-keyed name of each of its per-loop face families
248    /// here (`{cap_base}_START` -> every per-loop START cap), so a reference
249    /// stored before per-loop naming still resolves. See [`SceneMap::face_groups`].
250    ///
251    /// Members are NAMES, not `(handle, id)` refs, and are resolved at lookup
252    /// time. Name fidelity carries a face through a later boolean or dressup, so
253    /// a group registered by the extrude keeps naming the right faces after the
254    /// solid is consumed and re-registered by something downstream — which a
255    /// captured handle would not survive.
256    #[serde(default)]
257    pub face_groups: Vec<(String, Vec<String>)>,
258    /// The same, for the derived edge names that embed those face names.
259    #[serde(default)]
260    pub edge_groups: Vec<(String, Vec<String>)>,
261}
262
263/// The output of one feature execution.
264/// A named world point a feature published (a SKETCH publishes every solved
265/// point as `{sketchId}:P{pid}`; a spline its anchors, a helix its ends).
266/// `construction` carries the sketch point's own flag: a construction point (the
267/// sketcher's ◐ toggle, or a materialized external reference) still resolves by
268/// name — a helix may start at one — but it is NOT model geometry, so a placement
269/// consumer (the hole) skips it exactly as the profile skips construction lines.
270/// Serialized because the render-side build report carries it across the worker
271/// boundary.
272#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
273pub struct ScenePoint {
274    pub position: Vec3,
275    pub construction: bool,
276}
277
278impl ScenePoint {
279    /// A model point (the default for every non-sketch publisher).
280    pub fn model(position: Vec3) -> Self {
281        Self { position, construction: false }
282    }
283}
284
285#[derive(Debug, Clone, Serialize)]
286pub struct FeatureResult {
287    #[serde(default, rename = "persistentData", skip_serializing_if = "Option::is_none")]
288    pub persistent_data: Option<serde_json::Value>,
289    pub id: String,
290    pub feature_type: String,
291    pub added: Vec<AddedSolid>,
292    /// Names of prior solids this feature consumed/superseded (removed from the
293    /// scene-map; their handles are freed by the loop).
294    pub removed: Vec<String>,
295    /// Set on a hard failure. `execute_history` records it and HALTS the
296    /// remaining features (mirrors the abort-on-error loop). Never a panic.
297    pub error: Option<String>,
298    /// The TYPED refusal behind `error`, when the producer that refused minted
299    /// one (`KernelRefusal`: a closed class, the stage, the same text). `error`
300    /// is always that refusal's message verbatim, so a consumer that only
301    /// reads text sees nothing new; one that dispatches on the class reads it
302    /// here. `None` on success and on a refusal from a producer that still
303    /// returns text.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub refusal: Option<KernelRefusal>,
306    /// What a SUCCESSFUL feature did with what it was asked, when that is not
307    /// "everything, exactly": the references it applied and the ones it
308    /// rejected, each with why. `None` on a refusal and on a feature that did
309    /// everything it was asked. A feature that proceeds on the subset of its
310    /// selection that resolved says so HERE, typed, instead of only in
311    /// `unresolved` (which stays populated for the rename hint). This is a
312    /// success stating what it did, not a refusal carrying a partial result —
313    /// the payload the 2026-09-11 survey rejected.
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub fulfilment: Option<Fulfilment>,
316    /// Which named motion STEP of a feature refused: Transform Face records
317    /// `"rotation"` or `"translation"` (`features::transform_face::REFUSED_STEP_*`)
318    /// for a refusal from either motion, alone or in rotate-then-translate.
319    /// `None` for every other result, including a Transform Face refused before
320    /// any motion ran. The refusal's class is the step's own; this says which
321    /// step it was, which no class can. Additive: absent when `None`.
322    #[serde(default, skip_serializing_if = "Option::is_none")]
323    pub refused_step: Option<String>,
324    /// `reference_selection` names this feature could not resolve against the
325    /// scene-map. NOT an error/halt — the caller runs a snapshot-repair pass and
326    /// re-dispatches (migration-plan Stage 5 gate).
327    pub unresolved: Vec<String>,
328    /// What the kernel REPAIRED while building this feature, in the words of the
329    /// repair that made it. A repair changes the answer the lane returns — the
330    /// self-crossing fixer drops material and re-trims its neighbours — so it is
331    /// never silent: the feature that ran it says so here, and the case gate
332    /// records it per case. Empty on every feature that repaired nothing, which
333    /// is nearly all of them.
334    #[serde(default, skip_serializing_if = "Vec::is_empty")]
335    pub notes: Vec<String>,
336    /// MEASURED approximations a SUCCESSFUL result carries
337    /// ([`crate::Approximation`]): the result stands, and each entry says by
338    /// how much and why it is not exact — today, an imported body whose shell
339    /// closes over the pcurve fit bar (`import.shell_closure`), with the bound
340    /// that puts on its volume. Distinct from `notes` (a REPAIR changed the
341    /// answer), from `fulfilment` (what was done of what was asked) and from
342    /// `refusal` (the result does not stand). The case runner records them per
343    /// feature and will not read a volume oracle as `correct` inside the bound.
344    /// Empty on nearly every feature.
345    #[serde(default, skip_serializing_if = "Vec::is_empty")]
346    pub approximations: Vec<crate::Approximation>,
347    /// True when this result was REPLAYED from the incremental history cache (the
348    /// feature and everything it references are unchanged since the last run).
349    /// The handles are the same resident solids — the caller can skip re-tessellation.
350    pub reused: bool,
351    /// Sketch profiles this feature produced (a SKETCH feature emits one under
352    /// its name; solid features emit none). INTERNAL side-channel: `#[serde(skip)]`
353    /// so it never crosses the wasm boundary to the caller — [`SceneMap::apply`] ingests it
354    /// into `scene.profiles` for downstream profile-consumers (extrude/revolve/…).
355    #[serde(skip)]
356    pub profiles: Vec<(String, SketchProfile)>,
357    /// Named plane frames this feature produced (DATUM emits three, PLANE one).
358    /// Same INTERNAL `#[serde(skip)]` side-channel — ingested into `scene.frames`
359    /// so a later SKETCH can resolve its plane by name, fully headless.
360    #[serde(skip)]
361    pub frames: Vec<(String, Frame)>,
362    /// Named axis lines this feature produced (a SKETCH emits one per line
363    /// geometry). Same INTERNAL `#[serde(skip)]` side-channel — ingested into
364    /// `scene.axes` so a later revolve/sweep can resolve its axis by name.
365    #[serde(skip)]
366    pub axes: Vec<(String, Axis)>,
367    /// Named path chains this feature produced (a SKETCH publishes its ordered
368    /// open/closed geometry chain). Same INTERNAL `#[serde(skip)]` side-channel —
369    /// ingested into `scene.paths` for sweep/path_sweep/rib trajectory resolution.
370    #[serde(skip)]
371    pub paths: Vec<(String, Vec<NurbsCurve>)>,
372    /// The SOURCE NAME of each curve in a published path chain, parallel to the
373    /// matching [`Self::paths`] entry (`{sketchId}:G{gid}` for a sketch segment,
374    /// `None` for a curve with no name behind it). Same INTERNAL `#[serde(skip)]`
375    /// side-channel — ingested into `scene.path_segment_names` so a multi-segment
376    /// consumer (the SWEEP) can name the geometry each PATH SEGMENT built after
377    /// that segment, instead of after its position in the chain.
378    #[serde(skip)]
379    pub path_segment_names: Vec<(String, Vec<Option<String>>)>,
380    /// The SCREW AXIS of each curve in a published path chain, parallel to the
381    /// matching [`Self::paths`] entry: `Some` for a curve its builder KNOWS is a
382    /// helix about that axis (the HELIX feature), `None` for everything else.
383    /// Same INTERNAL `#[serde(skip)]` side-channel — ingested into
384    /// `scene.path_segment_axes` so the SWEEP's `pathAlign` can carry a profile by
385    /// the helix's own screw motion rather than by a rotation-minimizing frame,
386    /// which rolls away from it by the helix's integrated torsion.
387    #[serde(skip)]
388    pub path_segment_axes: Vec<(String, Vec<Option<Axis>>)>,
389    /// Named world points this feature produced (a SKETCH publishes every point
390    /// as `{sketchId}:P{pid}`, construction flag included — see [`ScenePoint`]).
391    /// Same side-channel — ingested into `scene.points` for hole-center /
392    /// placement resolution and drawn by the committed-sketch display.
393    #[serde(skip)]
394    pub points: Vec<(String, ScenePoint)>,
395    /// Harness ports this feature produced (a PORT feature emits one under its
396    /// id). Same INTERNAL `#[serde(skip)]` side-channel — ingested into
397    /// `scene.ports` for spline attachments and the wire-harness tail.
398    #[serde(skip)]
399    pub ports: Vec<(String, PortRecord)>,
400    /// Component records this feature produced (an ACOMP feature emits one per
401    /// instance; its members ride `added` like any solids). Same INTERNAL
402    /// `#[serde(skip)]` side-channel — ingested into `scene.components` so the
403    /// component surface (`component.rs`) resolves against the live scene.
404    #[serde(skip)]
405    pub components: Vec<ComponentRecord>,
406}
407
408impl FeatureResult {
409    /// An empty successful result (no solids, no error) — the shape a non-solid
410    /// pass-through feature returns.
411    pub fn empty(id: impl Into<String>, feature_type: impl Into<String>) -> Self {
412        Self {
413            persistent_data: None,
414            id: id.into(),
415            feature_type: feature_type.into(),
416            added: Vec::new(),
417            removed: Vec::new(),
418            error: None,
419            refusal: None,
420            fulfilment: None,
421            refused_step: None,
422            unresolved: Vec::new(),
423            notes: Vec::new(),
424            approximations: Vec::new(),
425            reused: false,
426            profiles: Vec::new(),
427            frames: Vec::new(),
428            axes: Vec::new(),
429            paths: Vec::new(),
430            path_segment_names: Vec::new(),
431            path_segment_axes: Vec::new(),
432            points: Vec::new(),
433            ports: Vec::new(),
434            components: Vec::new(),
435        }
436    }
437
438    /// A hard failure. Halts the history loop.
439    pub fn error(
440        id: impl Into<String>,
441        feature_type: impl Into<String>,
442        message: impl Into<String>,
443    ) -> Self {
444        Self::refuse(id, feature_type, message.into())
445    }
446
447    /// The feature proceeded on the references that resolved and skipped the
448    /// ones in `unresolved`: record that as a typed partial fulfilment.
449    /// `requested` is the selection as the document names it; `applied` is
450    /// what remains after the misses. Nothing is recorded when every reference
451    /// resolved. Call it at the point the feature DECIDES to proceed, not at
452    /// resolution: a feature that no-ops or refuses on a miss has no partial.
453    pub fn note_partial_resolution(&mut self, requested: &[String]) {
454        if self.unresolved.is_empty() {
455            return;
456        }
457        let applied: Vec<String> = requested
458            .iter()
459            .filter(|name| !self.unresolved.contains(name))
460            .cloned()
461            .collect();
462        let rejected = self
463            .unresolved
464            .iter()
465            .map(|name| Rejected {
466                name: name.clone(),
467                kind: RejectedKind::Unresolved,
468                reason: "resolves to nothing on this model".into(),
469            })
470            .collect();
471        self.fulfilment = Some(Fulfilment {
472            requested: requested.to_vec(),
473            applied,
474            rejected,
475            extended: Vec::new(),
476        });
477    }
478
479    /// A hard failure from either kind of producer: `error` carries the text
480    /// (the refusal's own message, verbatim, when it is typed) and `refusal`
481    /// the class and stage when there is one.
482    pub fn refuse(
483        id: impl Into<String>,
484        feature_type: impl Into<String>,
485        refusal: impl Into<FeatureRefusal>,
486    ) -> Self {
487        let mut result = Self::empty(id, feature_type);
488        match refusal.into() {
489            FeatureRefusal::Text(message) => result.error = Some(message),
490            FeatureRefusal::Typed(refusal) => {
491                result.error = Some(refusal.message.clone());
492                result.refusal = Some(refusal);
493            }
494        }
495        result
496    }
497
498    /// A non-solid construction feature (datum/plane/sketch/spline/port/helix):
499    /// a descriptor pass-through with no resident handle. The loop continues.
500    pub fn pass_through(id: impl Into<String>, feature_type: impl Into<String>) -> Self {
501        Self::empty(id, feature_type)
502    }
503
504    /// A solid-producing (or no-kernel) feature not yet ported to Rust. Halts the
505    /// loop with a clear message — replaced when a fan-out agent implements the
506    /// feature's `features/<feat>.rs`.
507    pub fn not_yet_migrated(id: impl Into<String>, feature_type: impl Into<String>) -> Self {
508        let feature_type = feature_type.into();
509        let message = format!("feature type '{feature_type}' is not yet migrated to the Rust pipeline");
510        Self::error(id, feature_type, message)
511    }
512}
513
514/// The whole-history output.
515#[derive(Debug, Clone, Serialize)]
516pub struct HistoryResult {
517    pub results: Vec<FeatureResult>,
518    /// Per-feature wall-clock execution time `(feature id, milliseconds)` in run
519    /// order — the lightweight timing surface the engine-native history tree's
520    /// "N ms" readout consumes. A REUSED (cache-replayed) feature records `0.0`
521    /// (its geometry was not re-executed this run). INTERNAL side-channel:
522    /// `#[serde(skip)]` so it never changes the caller-facing `execute_history_json`
523    /// shape; brep-render reads it natively via the re-exported struct.
524    #[serde(skip)]
525    pub timings: Vec<(String, f64)>,
526    /// The wire-harness tail's routing report (`None` when the request carries
527    /// no `wireHarness` block). INTERNAL side-channel like `timings`: never on
528    /// the JSON ABI; brep-render ships it to the harness panel.
529    #[serde(skip)]
530    pub wire_harness: Option<wire_harness::WireHarnessReport>,
531    /// The PMI tail's resolution of every view's annotations (`None` when the
532    /// request carries no `pmi` block). INTERNAL side-channel like `timings`.
533    #[serde(skip)]
534    pub pmi: Option<pmi::PmiReport>,
535    /// The ports tail's resolution of the declared-ports block (`None` when the
536    /// document declares none). INTERNAL side-channel like `timings`: the tail
537    /// is not a feature, so this is where its unresolved references and refused
538    /// names surface.
539    #[serde(skip)]
540    pub ports: Option<ports::PortsReport>,
541}
542
543// ===========================================================================
544// SceneMap — the live name -> handle/topology index maintained across the loop
545// ===========================================================================
546
547// `handle` + `face_id`/`edge_id` are the contract the caller (and edge-selecting
548// fan-out features) read to resolve a selection to a resident topology entity.
549#[allow(dead_code)]
550#[derive(Debug, Clone, Copy)]
551pub struct FaceRef {
552    pub handle: u32,
553    pub face_id: u64,
554}
555
556#[allow(dead_code)]
557#[derive(Debug, Clone, Copy)]
558pub struct EdgeRef {
559    pub handle: u32,
560    pub edge_id: u64,
561}
562
563/// A solved sketch's extracted profile, placed in 3D. Produced by the SKETCH
564/// pipeline feature and consumed BY NAME by the profile-consumers (extrude,
565/// revolve, loft, sweep, rib, sheet-metal tab/contour-flange) — the exact-BREP
566/// replacement for the old "marshal the resolved curves into `inputParams`".
567///
568/// The closed loops are grouped into disjoint REGIONS by even-odd containment
569/// depth: a depth-EVEN loop is a region's OUTER boundary, a depth-ODD loop is a
570/// hole of the region whose outer directly contains it (so an island inside a
571/// hole is its own region). Each region is `[outer, holes…]`; consumers build
572/// one solid per region and UNION them — the established multi-region behavior.
573/// The plane frame (`origin` + orthonormal `x_axis`/`y_axis`/`z_axis`) is resolved
574/// LIVE in Rust from the sketch's plane reference (DATUM/PLANE feature frame or a
575/// resident face), falling back to the persisted `basis`; the loop curves are
576/// emitted in WORLD space via that frame, so `z_axis` is the natural extrude
577/// direction / a revolve-plane hint.
578#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
579pub struct SketchProfile {
580    pub origin: Vec3,
581    pub x_axis: Vec3,
582    pub y_axis: Vec3,
583    pub z_axis: Vec3,
584    /// Disjoint regions, each `[outer, holes…]` (containment-classified).
585    pub regions: Vec<Vec<ProfileLoop>>,
586}
587
588/// One closed boundary of a [`SketchProfile`]: head-to-tail world-space curves plus
589/// the per-curve source edge name (`{sketchId}:G{gid}`, parallel to `curves`). The
590/// profile-consumers stamp sidewall names from `edge_names` (extrude → `{name}_E`).
591#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
592pub struct ProfileLoop {
593    pub curves: Vec<NurbsCurve>,
594    pub edge_names: Vec<Option<String>>,
595    /// The loop's STABLE identity within its source sketch (see the sketch
596    /// feature's `loop_ids`), persisted per edge in `persistentData.sketch` and
597    /// resilient to adding/removing edges. The profile-swept features embed it in
598    /// their per-loop cap and hole-wall names, so those names no longer move when
599    /// a DIFFERENT loop is added or removed. `None` for a loop with no numeric
600    /// geometry id behind it (a FACE profile, or a hand-built test profile) —
601    /// [`ProfileLoop::key`] then falls back to the loop's own edge names.
602    #[serde(default)]
603    pub loop_id: Option<u64>,
604}
605
606impl ProfileLoop {
607    /// This loop's naming KEY — the token the profile-swept features embed in the
608    /// faces they build from it (`{cap_base}:{key}_START`, `{id}:HOLE:{key}`).
609    ///
610    /// `L{loop_id}` for a sketch loop. `None` when the loop has no identity to key
611    /// on, and the caller keeps its previous un-keyed spelling: a FACE profile
612    /// (always a single region — nothing to disambiguate, and its faces keep the
613    /// names every saved model already stores) or a hand-built profile with no
614    /// numeric geometry ids behind it.
615    pub fn key(&self) -> Option<String> {
616        self.loop_id.map(|id| format!("L{id}"))
617    }
618}
619
620/// Annotate an UNRESOLVED reference with the name that replaced it, when the miss
621/// looks like the per-loop naming change.
622///
623/// Per-loop cap/hole naming keyed names that used to be positional
624/// (`{cap_base}_START` -> `{cap_base}:L4_START`, `{id}:HOLE:1` -> `{id}:HOLE:L9`).
625/// Live models mostly do not need this — the CONTAINER groups keep the old
626/// spelling resolvable — but a reference the containers cannot cover (a positional
627/// `X[1]` disambiguation from before the change, or a `{id}:HOLE:{n}` written
628/// against a since-edited sketch) still misses, and a bare "unresolved" says
629/// nothing about why. This turns the miss into the fix:
630///
631/// ```text
632/// E4:S3:PROFILE_START[1] (renamed: E4:S3:PROFILE:L9_START)
633/// ```
634///
635/// The candidates come from the live scene, so the hint is what the model
636/// ACTUALLY built, not a guess.
637pub fn annotate_rename(scene: &SceneMap, name: &str) -> String {
638    let candidates = rename_candidates(scene, name);
639    if candidates.is_empty() {
640        return name.to_string();
641    }
642    format!("{name} (renamed: {})", candidates.join(", "))
643}
644
645/// The keyed names that plausibly replaced `name`. A stale reference differs from
646/// its replacement only by the inserted loop key, so a candidate is any live face
647/// name that matches once the key is accounted for — `{stem}:{key}_START` for a
648/// cap, `{id}:HOLE:{key}` for a hole wall. A trailing positional `[n]` (the old
649/// duplicate-name disambiguation, the very thing this change removes) is stripped
650/// before matching.
651fn rename_candidates(scene: &SceneMap, name: &str) -> Vec<String> {
652    let stale = name.rsplit_once('[').map_or(name, |(head, tail)| {
653        if tail.ends_with(']') && tail[..tail.len() - 1].chars().all(|c| c.is_ascii_digit()) {
654            head
655        } else {
656            name
657        }
658    });
659    // Cap: `{stem}_START` / `{stem}_END` -> `{stem}:{key}_START` / `_END`.
660    let cap = ["_START", "_END"]
661        .into_iter()
662        .find_map(|suffix| stale.strip_suffix(suffix).map(|stem| (stem.to_string(), suffix)));
663    // Hole wall: `{id}:HOLE:{anything}` -> `{id}:HOLE:{key}`.
664    let hole = stale
665        .rsplit_once(":HOLE:")
666        .map(|(owner, _)| format!("{owner}:HOLE:"));
667
668    let mut candidates: Vec<String> = scene
669        .faces
670        .keys()
671        .filter(|live| {
672            if let Some((stem, suffix)) = &cap {
673                if let Some(rest) = live.strip_prefix(stem.as_str()) {
674                    // Exactly `:{key}` was inserted before the suffix.
675                    return rest.starts_with(':')
676                        && rest.ends_with(suffix)
677                        && rest.len() > suffix.len() + 1
678                        && !rest[1..rest.len() - suffix.len()].contains(':');
679                }
680            }
681            if let Some(prefix) = &hole {
682                return live.starts_with(prefix.as_str()) && live.as_str() != stale;
683            }
684            false
685        })
686        .cloned()
687        .collect();
688    candidates.sort();
689    candidates
690}
691
692/// An orthonormal placement frame — a named plane (DATUM/PLANE feature) or a
693/// resolved sketch plane. `z_axis` is the plane normal.
694#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
695pub struct Frame {
696    pub origin: Vec3,
697    pub x_axis: Vec3,
698    pub y_axis: Vec3,
699    pub z_axis: Vec3,
700}
701
702impl Frame {
703    /// Derive an orthonormal frame from an origin + plane normal via the worldUp
704    /// convention, the
705    /// SINGLE source of truth for how a sketch/plane reference becomes in-plane
706    /// axes: `refUp = |n·(0,1,0)| > 0.9 ? (1,0,0) : (0,1,0)`;
707    /// `x = norm(refUp × n)`; `y = norm(n × x)`; `z = n`. The referenced object's
708    /// own x/y are intentionally ignored — only its (origin, normal) matter.
709    pub fn from_origin_normal(origin: Vec3, normal: Vec3) -> Result<Self, String> {
710        let z_axis = normal.normalized()?;
711        let world_up = Vec3::new(0.0, 1.0, 0.0);
712        let ref_up = if z_axis.dot(world_up).abs() > 0.9 {
713            Vec3::new(1.0, 0.0, 0.0)
714        } else {
715            world_up
716        };
717        let x_axis = ref_up.cross(z_axis).normalized()?;
718        let y_axis = z_axis.cross(x_axis).normalized()?;
719        Ok(Frame {
720            origin,
721            x_axis,
722            y_axis,
723            z_axis,
724        })
725    }
726
727    /// Derive an orthonormal frame whose **x_axis** is `direction` — the frame a
728    /// connection point's placement is an offset in (its seat, `ports::seat_of`).
729    ///
730    /// A connection point's direction is its rotation applied to **+X** (the
731    /// convention every feature transform reads), so the frame that seats one
732    /// must carry the direction on X, not on Z. Rather than invent a second
733    /// worldUp rule this is the CYCLIC RELABEL of [`Self::from_origin_normal`]'s
734    /// triad — x = z', y = x', z = y' — which is still right-handed and keeps
735    /// ONE convention for how a direction becomes a basis. A sketch on the
736    /// point's published frame and the point's own offset axes therefore agree
737    /// by construction: they are the same three vectors, named round.
738    pub fn from_origin_direction(origin: Vec3, direction: Vec3) -> Result<Self, String> {
739        let normal = Self::from_origin_normal(origin, direction)?;
740        Ok(Frame {
741            origin,
742            x_axis: normal.z_axis,
743            y_axis: normal.x_axis,
744            z_axis: normal.y_axis,
745        })
746    }
747
748    /// Map a plane-local `(u, v)` into world space: `origin + u·x + v·y`.
749    pub fn to_3d(&self, u: f64, v: f64) -> Vec3 {
750        self.origin
751            .add(self.x_axis.scale(u))
752            .add(self.y_axis.scale(v))
753    }
754}
755
756/// A named world-space line — a revolve/sweep axis. Published by SKETCH features
757/// (every sketch line geometry, construction included) and resolvable from a
758/// resident solid edge, so an `axis`/path reference resolves fully headless.
759#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
760pub struct Axis {
761    pub point: Vec3,
762    pub direction: Vec3,
763}
764
765/// What a connection point is to the harness router: a cable END, or a
766/// pass-through that joins spline paths into a network. Not a user param any
767/// more - it is decided by WHICH producer made the record (a declared port
768/// point is a termination, a WAYPOINT feature is a waypoint).
769#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
770#[serde(rename_all = "lowercase")]
771pub enum PortKind {
772    Termination,
773    Waypoint,
774}
775
776/// One resolved connection point, keyed in [`SceneMap::ports`] by its ADDRESS
777/// (`J1.VCC`, `ACOMP3:J1.VCC` once placed - see `ports.rs`). Published by the
778/// ports tail, by the WAYPOINT feature (under its own feature id) and by an
779/// ACOMP re-publishing a placed part's points.
780///
781/// `direction` is the unit vector a wire leaves along on side **A**; side **B**
782/// is its negation. `extension` is the straight run a wire keeps from `point`
783/// before it may bend (a spline anchor attached here takes it as its
784/// forward/backward distance) and `display_length` the length of the drawn
785/// line.
786///
787/// `port_name` / `point_name` / `purpose` stay PART-LOCAL through every
788/// namespacing: a placed part's point is still point `VCC` of port `J1`
789/// whatever occurrence chain its address carries. That is what a pin binds to.
790/// A WAYPOINT carries an empty `port_name` and `purpose`, and its own name as
791/// `point_name`.
792#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
793pub struct PortRecord {
794    pub point: Vec3,
795    pub direction: Vec3,
796    pub kind: PortKind,
797    pub extension: f64,
798    pub display_length: f64,
799    #[serde(default, rename = "portName")]
800    pub port_name: String,
801    #[serde(default, rename = "pointName")]
802    pub point_name: String,
803    #[serde(default)]
804    pub purpose: String,
805}
806
807impl PortRecord {
808    /// The PART-LOCAL address of this point (`J1.VCC`), or just the name for a
809    /// WAYPOINT, which belongs to no port. The occurrence chain is the map key's
810    /// business, not the record's.
811    pub fn local_address(&self) -> String {
812        if self.port_name.is_empty() {
813            self.point_name.clone()
814        } else {
815            ports::address(&self.port_name, &self.point_name)
816        }
817    }
818
819    /// The direction a wire leaves this port along on `side` (`A` = the port
820    /// direction, `B` = its negation).
821    pub fn side_direction(&self, side: wire_harness::PortSide) -> Vec3 {
822        match side {
823            wire_harness::PortSide::A => self.direction,
824            wire_harness::PortSide::B => self.direction.scale(-1.0),
825        }
826    }
827}
828
829/// The live scene-map. Exact-match resolution only (contract rule 1).
830#[derive(Debug, Clone, Default)]
831pub struct SceneMap {
832    pub solids: HashMap<String, u32>,
833    pub faces: HashMap<String, FaceRef>,
834    pub edges: HashMap<String, EdgeRef>,
835    /// CONTAINER name -> the faces it stands for. A profile-swept feature names
836    /// each of its per-loop caps individually (`{cap_base}:L{loopId}_START`) and
837    /// registers the un-keyed `{cap_base}_START` here as the name of the whole
838    /// sketch container — every cap the feature made. So the name a model saved
839    /// before per-loop naming still resolves, and still means the right thing:
840    /// the one cap on a single-loop sketch, all of them on a multi-loop one.
841    pub face_groups: HashMap<String, Vec<String>>,
842    /// CONTAINER name -> the edges it stands for. The derived edge-name
843    /// convention embeds face names (`{faceA}|{faceB}[n]`), so keying the caps
844    /// renamed every cap-adjacent edge too; this holds the container-name
845    /// spelling of each such edge for the same reason [`Self::face_groups`] does.
846    pub edge_groups: HashMap<String, Vec<String>>,
847    /// Sketch name -> its extracted profile. Populated by SKETCH features; read by
848    /// profile-consumers via [`SceneMap::resolve_profile`].
849    pub profiles: HashMap<String, SketchProfile>,
850    /// Plane name -> its frame. Populated by DATUM/PLANE features; read by SKETCH
851    /// (and PLANE datum-refs) via [`SceneMap::resolve_frame`] for headless plane
852    /// resolution (fully headless).
853    pub frames: HashMap<String, Frame>,
854    /// Axis name -> its world line. Populated by SKETCH line geometries; read by
855    /// revolve/sweep via [`SceneMap::resolve_axis`].
856    pub axes: HashMap<String, Axis>,
857    /// Path name -> its ordered world curve chain (open or closed). Populated by
858    /// SKETCH features; read by sweep/path_sweep/rib via [`SceneMap::resolve_path`].
859    pub paths: HashMap<String, Vec<NurbsCurve>>,
860    /// Path name -> the SOURCE NAME of each curve in its chain, parallel to the
861    /// [`Self::paths`] entry of the same name. Populated by SKETCH features; read
862    /// by the SWEEP via [`SceneMap::resolve_path_segment_names`] so the faces one
863    /// path SEGMENT builds carry that segment's name rather than its position.
864    pub path_segment_names: HashMap<String, Vec<Option<String>>>,
865    /// Path name -> the SCREW AXIS of each curve in its chain (`Some` for a
866    /// helix), parallel to the [`Self::paths`] entry of the same name. Populated
867    /// by HELIX features; read by the SWEEP via
868    /// [`SceneMap::resolve_path_segment_axes`].
869    pub path_segment_axes: HashMap<String, Vec<Option<Axis>>>,
870    /// Point name -> its world position + construction flag. Populated by SKETCH
871    /// features (`{sketchId}:P{pid}`), splines and helices; read by hole placement
872    /// via [`SceneMap::model_points_with_prefix`] and by name via
873    /// [`SceneMap::resolve_point`].
874    pub points: HashMap<String, ScenePoint>,
875    /// Connection-point ADDRESS -> its record. Populated by the ports tail
876    /// (the document's declared points), by WAYPOINT features and by ACOMP
877    /// (a placed part's points, namespaced and posed); read by SPLINE
878    /// attachments ([`SceneMap::resolve_port`]) and by the wire-harness tail,
879    /// which builds its sided routing graph from it.
880    pub ports: HashMap<String, PortRecord>,
881    /// Owning feature id -> component record (assemblies). Populated by ACOMP
882    /// features via the `components` side-channel; the whole component API
883    /// surface (`resolve_component` / `owning_component` / the fence predicate)
884    /// lives in component.rs. Empty in every componentless scene — nothing in
885    /// the ordinary modeling path reads or writes it.
886    pub components: component::ComponentMap,
887    /// Naming-contract guard (accumulated across [`SceneMap::apply`] calls): one
888    /// message per detected cross-solid name COLLISION — an added solid's face /
889    /// edge name that already maps to a DIFFERENT still-resident solid. Two live
890    /// solids must never share a face/edge name (the SceneMap is a global
891    /// name → one-solid map). `execute_history` surfaces any collision introduced
892    /// by a freshly-run feature as that feature's error, so the offending
893    /// operation trips its own tests + shows an error in the app.
894    pub name_collisions: Vec<String>,
895}
896
897impl SceneMap {
898    /// Resolve a solid name to its resident handle (exact match).
899    pub fn resolve_solid(&self, name: &str) -> Option<u32> {
900        self.solids.get(name).copied()
901    }
902
903    /// Resolve a face name to its `(handle, face_id)` (exact match).
904    pub fn resolve_face(&self, name: &str) -> Option<FaceRef> {
905        if let Some(face) = self.faces.get(name) {
906            return Some(*face);
907        }
908        // A CONTAINER name holding exactly ONE face resolves to it. Not a scoring
909        // heuristic (contract rule 1 stands): the container is a name the feature
910        // registered deliberately, and a single member leaves nothing to choose
911        // between. This is what keeps every reference in a model saved before
912        // per-loop cap naming resolving unchanged — a single-loop sketch has one
913        // cap, so its container has one member. A container with SEVERAL members
914        // is ambiguous for a single-face consumer and stays unresolved; the
915        // multi-face consumers take it through [`Self::resolve_face_group`].
916        match self.resolve_face_group(name).as_slice() {
917            [only] => Some(*only),
918            _ => None,
919        }
920    }
921
922    /// Every face a name stands for: the one exact match, else the members of the
923    /// container by that name (possibly several). The multi-face resolution the
924    /// selection-list consumers use — [`Self::resolve_face`] is its single-face
925    /// sibling.
926    pub fn resolve_face_group(&self, name: &str) -> Vec<FaceRef> {
927        if let Some(face) = self.faces.get(name) {
928            return vec![*face];
929        }
930        // Members are resolved NOW, so a member a later operation consumed simply
931        // drops out instead of leaving a stale handle behind.
932        self.face_groups
933            .get(name)
934            .map(|members| {
935                members
936                    .iter()
937                    .filter_map(|member| self.faces.get(member).copied())
938                    .collect()
939            })
940            .unwrap_or_default()
941    }
942
943    /// Every edge a name stands for — [`Self::resolve_face_group`] for edges.
944    pub fn resolve_edge_group(&self, name: &str) -> Vec<EdgeRef> {
945        if let Some(edge) = self.edges.get(name) {
946            return vec![*edge];
947        }
948        self.edge_groups
949            .get(name)
950            .map(|members| {
951                members
952                    .iter()
953                    .filter_map(|member| self.edges.get(member).copied())
954                    .collect()
955            })
956            .unwrap_or_default()
957    }
958
959    /// Resolve an edge name to its `(handle, edge_id)` (exact match). Contract
960    /// surface for edge-selecting fan-out features (fillet/chamfer); no
961    /// implemented feature consumes it yet.
962    #[allow(dead_code)]
963    pub fn resolve_edge(&self, name: &str) -> Option<EdgeRef> {
964        if let Some(edge) = self.edges.get(name) {
965            return Some(*edge);
966        }
967        // The [`Self::resolve_face`] rule for edges: derived edge names embed face
968        // names, so keying the caps renamed every cap-adjacent edge too, and a
969        // container holding exactly one edge resolves to it. This is what keeps a
970        // stored projected-edge / axis / path reference working.
971        match self.resolve_edge_group(name).as_slice() {
972            [only] => Some(*only),
973            _ => None,
974        }
975    }
976
977    /// Resolve a profile reference name to the sketch profile it names. Tries the
978    /// exact name first, then the name with a trailing `:PROFILE` stripped — a
979    /// sketch is selectable both by its group name (`{id}`) and by its profile
980    /// face name (`{id}:PROFILE`); both must resolve to
981    /// the one profile stored under `{id}`.
982    pub fn resolve_profile(&self, name: &str) -> Option<&SketchProfile> {
983        if let Some(profile) = self.profiles.get(name) {
984            return Some(profile);
985        }
986        name.strip_suffix(":PROFILE")
987            .and_then(|base| self.profiles.get(base))
988    }
989
990    /// Resolve a named plane frame (exact match), for sketch/plane resolution.
991    pub fn resolve_frame(&self, name: &str) -> Option<Frame> {
992        self.frames.get(name).copied()
993    }
994
995    /// Resolve a named axis line (exact match), for revolve/sweep.
996    pub fn resolve_axis(&self, name: &str) -> Option<Axis> {
997        self.axes.get(name).copied()
998    }
999
1000    /// Resolve a named path chain (exact match; also strips a trailing `:PROFILE`),
1001    /// for sweep/path_sweep/rib trajectories.
1002    pub fn resolve_path(&self, name: &str) -> Option<&Vec<NurbsCurve>> {
1003        if let Some(path) = self.paths.get(name) {
1004            return Some(path);
1005        }
1006        name.strip_suffix(":PROFILE")
1007            .and_then(|base| self.paths.get(base))
1008    }
1009
1010    /// The per-segment SOURCE NAMES of a named path chain, resolved exactly as
1011    /// [`SceneMap::resolve_path`] resolves the chain itself (so the two always
1012    /// answer for the same entry). `None` when the publisher named no segments —
1013    /// the caller then falls back to naming by the reference itself.
1014    pub fn resolve_path_segment_names(&self, name: &str) -> Option<&Vec<Option<String>>> {
1015        if let Some(names) = self.path_segment_names.get(name) {
1016            return Some(names);
1017        }
1018        name.strip_suffix(":PROFILE")
1019            .and_then(|base| self.path_segment_names.get(base))
1020    }
1021
1022    /// The per-segment SCREW AXES of a named path chain, resolved exactly as
1023    /// [`SceneMap::resolve_path`] resolves the chain itself. `None` when the
1024    /// publisher recorded none — every segment is then an ordinary curve.
1025    pub fn resolve_path_segment_axes(&self, name: &str) -> Option<&Vec<Option<Axis>>> {
1026        if let Some(axes) = self.path_segment_axes.get(name) {
1027            return Some(axes);
1028        }
1029        name.strip_suffix(":PROFILE")
1030            .and_then(|base| self.path_segment_axes.get(base))
1031    }
1032
1033    /// Resolve a named world point (exact match), for hole/placement centers.
1034    /// Contract surface consumed by the spline/hole placement tests; kept as the
1035    /// documented point-resolution API even where no shipping feature reads it
1036    /// yet (mirrors `resolve_edge`).
1037    #[allow(dead_code)]
1038    pub fn resolve_point(&self, name: &str) -> Option<Vec3> {
1039        self.points.get(name).map(|point| point.position)
1040    }
1041
1042    /// Resolve a connection point by its address (exact match).
1043    pub fn resolve_port(&self, name: &str) -> Option<&PortRecord> {
1044        self.ports.get(name)
1045    }
1046
1047    /// Every MODEL (non-construction) point whose name starts with `prefix`, as
1048    /// `(name, position)` pairs in map order (the caller sorts). The scene-map
1049    /// indexes points by exact name only, so a consumer that wants "all the
1050    /// points of sketch S" prefix-scans `S:P` — safe because the prefix ends in
1051    /// `:P`, which another sketch id cannot spell into (`S1:P` never prefixes
1052    /// `S10:P…`). Construction points (the sketcher's ◐ toggle, materialized
1053    /// external references) are skipped: they constrain, they never model.
1054    pub fn model_points_with_prefix(&self, prefix: &str) -> Vec<(String, Vec3)> {
1055        self.points
1056            .iter()
1057            .filter(|(name, point)| name.starts_with(prefix) && !point.construction)
1058            .map(|(name, point)| (name.clone(), point.position))
1059            .collect()
1060    }
1061
1062    /// Apply a feature's effect: removals first (a boolean result reuses a removed
1063    /// target's name), then additions. Removal only unmaps NAMES — it never frees
1064    /// the handle. Handles are owned by the incremental history cache (each by the
1065    /// entry of the feature that produced it) and die exactly when that entry is
1066    /// invalidated; freeing here would kill a clean upstream feature's cached
1067    /// solid the moment a downstream boolean consumed it.
1068    fn apply(&mut self, result: &FeatureResult) {
1069        for name in &result.removed {
1070            // A removed COMPONENT id drops the record and unmaps every member
1071            // solid (names only — handle ownership stays with the cache, same
1072            // as plain solid removal). Feature ids never collide with solid
1073            // names, so this is a no-op for every ordinary removal.
1074            if let Some(record) = self.components.remove(name) {
1075                for member in &record.solids {
1076                    if let Some(handle) = self.solids.remove(member) {
1077                        self.faces.retain(|_, face| face.handle != handle);
1078                        self.edges.retain(|_, edge| edge.handle != handle);
1079                    }
1080                }
1081                // ...and the ports the part carried, with their entities.
1082                for port in &record.ports {
1083                    self.ports.remove(port);
1084                    self.axes.remove(port);
1085                    self.frames.remove(port);
1086                    self.points.remove(&format!("{port}:Base"));
1087                    self.paths.remove(&format!("{port}:PortLine"));
1088                }
1089            }
1090            if let Some(handle) = self.solids.remove(name) {
1091                // Purge the removed solid's face/edge entries (names only).
1092                self.faces.retain(|_, face| face.handle != handle);
1093                self.edges.retain(|_, edge| edge.handle != handle);
1094            }
1095            // A consumed sketch's PUBLISHED GEOMETRY (profile / axis / path / point)
1096            // is deliberately NOT purged here. Unlike a solid, one sketch can drive
1097            // several features — a later feature legitimately resolves the sketch's
1098            // axis or path even after another feature consumed its profile (see
1099            // `revolve::tests::extruded_face_then_revolve_face_profile`, which
1100            // revolves about a consumed sketch's `Sk:G20` axis). Removing a consumed
1101            // sketch from the SCENE DISPLAY is handled render-side (the committed-
1102            // sketch list honors `removed`); the kernel keeps its geometry resolvable.
1103            // A removed name not in the map is a silent no-op (established semantics).
1104        }
1105        // Ingest any sketch profiles this feature produced (SKETCH features only).
1106        for (name, profile) in &result.profiles {
1107            self.profiles.insert(name.clone(), profile.clone());
1108        }
1109        // Ingest any named plane frames (DATUM/PLANE features).
1110        for (name, frame) in &result.frames {
1111            self.frames.insert(name.clone(), *frame);
1112        }
1113        // Ingest any named axis lines (SKETCH line geometries).
1114        for (name, axis) in &result.axes {
1115            self.axes.insert(name.clone(), *axis);
1116        }
1117        // Ingest any named path chains (SKETCH geometry chains).
1118        for (name, names) in &result.path_segment_names {
1119            self.path_segment_names.insert(name.clone(), names.clone());
1120        }
1121        for (name, axes) in &result.path_segment_axes {
1122            self.path_segment_axes.insert(name.clone(), axes.clone());
1123        }
1124        for (name, path) in &result.paths {
1125            self.paths.insert(name.clone(), path.clone());
1126        }
1127        // Ingest any named world points (SKETCH points).
1128        for (name, point) in &result.points {
1129            self.points.insert(name.clone(), *point);
1130        }
1131        // Ingest any harness ports (PORT features).
1132        for (name, port) in &result.ports {
1133            self.ports.insert(name.clone(), port.clone());
1134        }
1135        // Ingest any component records (ACOMP features).
1136        for record in &result.components {
1137            self.components.insert(record.id.clone(), record.clone());
1138        }
1139        // Insert the added solids' names FIRST so the resident-handle set is
1140        // complete (a name colliding with another solid ADDED in the same result
1141        // is still a collision).
1142        for added in &result.added {
1143            self.solids.insert(added.name.clone(), added.handle);
1144        }
1145        let resident: std::collections::HashSet<u32> = self.solids.values().copied().collect();
1146        for added in &result.added {
1147            for (face_id, name) in &added.face_names {
1148                self.check_name_collision(name, added.handle, &added.name, &resident, true);
1149                self.faces.insert(
1150                    name.clone(),
1151                    FaceRef {
1152                        handle: added.handle,
1153                        face_id: *face_id,
1154                    },
1155                );
1156            }
1157            for (edge_id, name) in &added.edge_names {
1158                self.check_name_collision(name, added.handle, &added.name, &resident, false);
1159                self.edges.insert(
1160                    name.clone(),
1161                    EdgeRef {
1162                        handle: added.handle,
1163                        edge_id: *edge_id,
1164                    },
1165                );
1166            }
1167            // Container groups. NOT collision-checked: a container is a name for
1168            // faces this same solid owns, never a claim on another solid's name,
1169            // and a real face by that name always wins (both resolvers try the
1170            // exact maps first). Stored as member NAMES and resolved on lookup,
1171            // so a group survives the solid being consumed and re-registered by a
1172            // later feature (name fidelity carries the members across).
1173            for (container, members) in &added.face_groups {
1174                self.face_groups.insert(container.clone(), members.clone());
1175            }
1176            for (container, members) in &added.edge_groups {
1177                self.edge_groups.insert(container.clone(), members.clone());
1178            }
1179        }
1180    }
1181
1182    /// Record a naming-contract collision if `name` (a face when `is_face`, else
1183    /// an edge) already maps to a DIFFERENT still-RESIDENT solid — an added
1184    /// solid's name stealing another live solid's. A `prev` handle no longer in
1185    /// `resident` is a stale leftover (rollback / cache eviction), not a
1186    /// violation, so it is ignored. The message names the offender + the resident
1187    /// owner and points at the fix.
1188    fn check_name_collision(
1189        &mut self,
1190        name: &str,
1191        handle: u32,
1192        solid_name: &str,
1193        resident: &std::collections::HashSet<u32>,
1194        is_face: bool,
1195    ) {
1196        let prev = if is_face {
1197            self.faces.get(name).map(|face| face.handle)
1198        } else {
1199            self.edges.get(name).map(|edge| edge.handle)
1200        };
1201        let Some(prev_handle) = prev else { return };
1202        if prev_handle == handle || !resident.contains(&prev_handle) {
1203            return;
1204        }
1205        let owner = self
1206            .solids
1207            .iter()
1208            .find(|(_, resident_handle)| **resident_handle == prev_handle)
1209            .map(|(owner_name, _)| owner_name.as_str())
1210            .unwrap_or("another resident solid");
1211        let kind = if is_face { "face" } else { "edge" };
1212        // One line PER colliding name; the `namespace_copy_names` hint is appended
1213        // ONCE per feature error where these lines are joined (execute_history).
1214        self.name_collisions.push(format!(
1215            "naming-contract violation: solid `{solid_name}` {kind} name `{name}` \
1216             collides with resident solid `{owner}` (two live solids must not share a \
1217             face/edge name)."
1218        ));
1219    }
1220}
1221
1222/// Join a feature's per-name collision lines into ONE error string, appending the
1223/// `namespace_copy_names` fix hint exactly ONCE (a copy-feature can collide on
1224/// dozens of names — repeating the hint per name buried the signal). Shared so the
1225/// surfacing in `execute_history` and its test agree on the wording.
1226pub(crate) fn name_collision_error(lines: &[String]) -> String {
1227    let mut message = lines.join("; ");
1228    message.push_str(
1229        " — an operation that COPIES geometry (mirror / pattern / transform-copy / \
1230         any new one) must call `common::namespace_copy_names(&mut solid, suffix)` \
1231         so the copy's faces and edges get UNIQUE names.",
1232    );
1233    message
1234}
1235
1236// ===========================================================================
1237// FeatureContext — everything a feature's `execute(ctx)` needs
1238// ===========================================================================
1239
1240/// The read-only context handed to each feature's `execute`. Features resolve
1241/// their `reference_selection` params against `scene` and read numeric params via
1242/// [`FeatureContext::number`] (which evaluates expression strings against `env`).
1243pub struct FeatureContext<'a> {
1244    pub id: String,
1245    pub feature_type: String,
1246    pub params: &'a serde_json::Value,
1247    /// The feature's `persistentData` (round-tripped from the saved part file).
1248    /// The SKETCH feature reads its `sketch` + `basis` here (the scene-computed
1249    /// plane frame stays caller-side per directive §1 and is marshaled in via this).
1250    pub persistent: &'a serde_json::Value,
1251    pub env: &'a Env,
1252    pub scene: &'a SceneMap,
1253    /// `Some` when the history walk knows nothing that follows this feature
1254    /// references the solids it consumes, by face name or by persistent data
1255    /// (lane X row 11b): the boolean feature may then re-seat an operand's
1256    /// cylinder seam before imprint. `None` (the walk cannot tell, or a later
1257    /// feature might reference them, or a direct `execute_feature` call)
1258    /// never re-seats.
1259    pub later_inputs: Option<&'a [String]>,
1260}
1261
1262impl<'a> FeatureContext<'a> {
1263    /// The raw param value (an object field of `inputParams`), if present.
1264    pub fn param(&self, key: &str) -> Option<&serde_json::Value> {
1265        self.params.get(key)
1266    }
1267
1268    /// A numeric param: a JSON number passes through; a JSON string is evaluated
1269    /// as an expression against the shared env; anything else is an error. This is
1270    /// how a feature declares which of its params are numeric (the engine has no
1271    /// per-feature schema).
1272    pub fn number(&self, key: &str) -> Result<f64, String> {
1273        match self.param(key) {
1274            Some(serde_json::Value::Number(number)) => number
1275                .as_f64()
1276                .ok_or_else(|| format!("param `{key}` is not a finite number")),
1277            Some(serde_json::Value::String(source)) => self
1278                .env
1279                .eval(source)
1280                .map_err(|error| format!("param `{key}`: {error}")),
1281            Some(other) => Err(format!(
1282                "param `{key}` must be a number or expression string, found {other}"
1283            )),
1284            None => Err(format!("missing required param `{key}`")),
1285        }
1286    }
1287
1288    /// A string param (read verbatim — never expression-evaluated; used for ids
1289    /// and `reference_selection` names). Contract surface for fan-out features;
1290    /// the two implemented features read the id via `ctx.id` directly.
1291    #[allow(dead_code)]
1292    pub fn string(&self, key: &str) -> Option<String> {
1293        match self.param(key) {
1294            Some(serde_json::Value::String(text)) => Some(text.clone()),
1295            _ => None,
1296        }
1297    }
1298
1299    /// A convenience [`FeatureResult::refuse`] carrying this feature's id +
1300    /// type: text from a stringly producer, or a typed [`KernelRefusal`].
1301    pub fn fail(&self, refusal: impl Into<FeatureRefusal>) -> FeatureResult {
1302        FeatureResult::refuse(self.id.clone(), self.feature_type.clone(), refusal)
1303    }
1304}
1305
1306/// What a SUCCESSFUL feature did with what it was asked, when that is not
1307/// "everything, exactly" (plan: typed-refusal-reporting, item 3). Requested and
1308/// applied are reference names as the document wrote them; every rejected one
1309/// says which kind of rejection and why. A partial fulfilment is a different
1310/// answer from the one asked for, so it is reported on the feature that made it
1311/// and displayed by the app beside the feature; it is never a refusal class
1312/// (a partial selection is a separate outcome) and never carries geometry.
1313#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
1314pub struct Fulfilment {
1315    pub requested: Vec<String>,
1316    pub applied: Vec<String>,
1317    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1318    pub rejected: Vec<Rejected>,
1319    /// Edges the feature acted on that were NOT selected: today a fillet
1320    /// whose selection ends inside a tangent chain and refused there, rerun
1321    /// once along the open chain
1322    /// (`common::open_tangent_chain_extension`). Their names, in walk order.
1323    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1324    pub extended: Vec<String>,
1325}
1326
1327impl Fulfilment {
1328    /// Something asked for was not done.
1329    pub fn is_partial(&self) -> bool {
1330        !self.rejected.is_empty()
1331    }
1332
1333    /// One line for a report or a tree leaf: "2 of 3 selected references
1334    /// applied; `ghost` resolves to nothing on this model".
1335    pub fn summary(&self) -> String {
1336        let mut notes: Vec<String> = self
1337            .rejected
1338            .iter()
1339            .map(|rejected| format!("`{}` {}", rejected.name, rejected.reason))
1340            .collect();
1341        if !self.extended.is_empty() {
1342            let names: Vec<String> = self.extended.iter().map(|name| format!("`{name}`")).collect();
1343            notes.push(format!(
1344                "the selection ends inside a tangent chain, so the fillet continued along it onto {}",
1345                names.join(", ")
1346            ));
1347        }
1348        format!(
1349            "{} of {} selected reference{} applied; {}",
1350            self.applied.len(),
1351            self.requested.len(),
1352            if self.requested.len() == 1 { "" } else { "s" },
1353            notes.join("; ")
1354        )
1355    }
1356}
1357
1358/// One reference a successful feature did not act on.
1359#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1360pub struct Rejected {
1361    pub name: String,
1362    pub kind: RejectedKind,
1363    pub reason: String,
1364}
1365
1366/// Why a reference was rejected. Closed; a new kind is a producer that exists.
1367#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
1368#[serde(rename_all = "snake_case")]
1369pub enum RejectedKind {
1370    /// The name resolves to no entity of the scene.
1371    Unresolved,
1372}
1373
1374/// What a feature's `build` hands back when it refuses. A feature that drives
1375/// a typed producer propagates the [`KernelRefusal`] whole (`?` converts it),
1376/// so its class reaches [`FeatureResult::refusal`]; one that drives a stringly
1377/// producer propagates the text. There is no `From<FeatureRefusal> for
1378/// String`: the text of a typed refusal is read through
1379/// [`FeatureRefusal::message`], never by dropping the class.
1380#[derive(Clone, Debug, PartialEq)]
1381pub enum FeatureRefusal {
1382    Text(String),
1383    Typed(KernelRefusal),
1384}
1385
1386impl FeatureRefusal {
1387    /// The human text either way, verbatim.
1388    pub fn message(&self) -> &str {
1389        match self {
1390            Self::Text(message) => message,
1391            Self::Typed(refusal) => &refusal.message,
1392        }
1393    }
1394}
1395
1396impl From<String> for FeatureRefusal {
1397    fn from(message: String) -> Self {
1398        Self::Text(message)
1399    }
1400}
1401
1402impl From<&str> for FeatureRefusal {
1403    fn from(message: &str) -> Self {
1404        Self::Text(message.to_string())
1405    }
1406}
1407
1408impl From<KernelRefusal> for FeatureRefusal {
1409    fn from(refusal: KernelRefusal) -> Self {
1410        Self::Typed(refusal)
1411    }
1412}
1413
1414impl std::fmt::Display for FeatureRefusal {
1415    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1416        f.write_str(self.message())
1417    }
1418}
1419
1420// ===========================================================================
1421// Dispatch — a match on `feature_type` to the owning `features/<feat>.rs`
1422// ===========================================================================
1423
1424/// Extract the feature id from `inputParams` (`id`, falling back to the
1425/// non-enumerable `featureID`). The solid + all face/edge names are prefixed
1426/// with this id, so name fidelity depends on it.
1427pub(crate) fn extract_id(params: &serde_json::Value) -> String {
1428    for key in ["id", "featureID"] {
1429        if let Some(serde_json::Value::String(text)) = params.get(key) {
1430            if !text.is_empty() {
1431                return text.clone();
1432            }
1433        }
1434    }
1435    String::new()
1436}
1437
1438/// Resolve one feature descriptor to a [`FeatureResult`] against the current
1439/// scene. Each stub's arm calls its own `features::<feat>::execute` so a fan-out
1440/// agent implementing a feature touches ONLY that file — never this dispatch.
1441pub fn execute_feature(
1442    descriptor: &FeatureDescriptor,
1443    env: &Env,
1444    scene: &SceneMap,
1445) -> FeatureResult {
1446    execute_feature_with_later(descriptor, env, scene, None)
1447}
1448
1449/// [`execute_feature`] with what the history walk knows about the features
1450/// after this one ([`FeatureContext::later_inputs`]).
1451pub(crate) fn execute_feature_with_later(
1452    descriptor: &FeatureDescriptor,
1453    env: &Env,
1454    scene: &SceneMap,
1455    later_inputs: Option<&[String]>,
1456) -> FeatureResult {
1457    let id = extract_id(&descriptor.input_params);
1458    let feature_type = descriptor.feature_type.clone();
1459    // The feature fence: component geometry is valid input for sketch
1460    // attach/project and assembly constraints ONLY. A modeling feature naming
1461    // it as an operand fails cleanly HERE — the one altitude every feature
1462    // passes through — instead of per-feature checks. Free for componentless
1463    // scenes (the walk is skipped entirely).
1464    if let Err(message) = component::enforce_reference_fence(&feature_type, descriptor, scene) {
1465        return FeatureResult::error(id, feature_type, message);
1466    }
1467    let ctx = FeatureContext {
1468        id: id.clone(),
1469        feature_type: feature_type.clone(),
1470        params: &descriptor.input_params,
1471        persistent: &descriptor.persistent_data,
1472        env,
1473        scene,
1474        later_inputs,
1475    };
1476    // Alias resolution mirrors the caller's feature registry, which matches short name,
1477    // LONG name, and class name (all uppercased) — saved files and tests use
1478    // long-name type strings like "CHAMFER"/"PLANE".
1479    match feature_type.as_str() {
1480        // --- Fully implemented (the exemplary pattern) ---
1481        "P.CU" | "CUBE" => features::cube::execute(&ctx),
1482        "P.S" | "SPHERE" => features::sphere::execute(&ctx),
1483        // --- Solid-producing primitives ---
1484        "P.CY" | "CYLINDER" => features::cylinder::execute(&ctx),
1485        "P.CO" | "CONE" => features::cone::execute(&ctx),
1486        "P.T" | "TORUS" => features::torus::execute(&ctx),
1487        "P.PY" | "PYRAMID" => features::pyramid::execute(&ctx),
1488        "NS" | "NURBS SOLID" | "NURBSSOLID" => features::nurbs_solid::execute(&ctx),
1489        // --- Add-material ---
1490        "E" | "EXTRUDE" => features::extrude::execute(&ctx),
1491        "R" | "REVOLVE" => features::revolve::execute(&ctx),
1492        "LOFT" => features::loft::execute(&ctx),
1493        "SW" | "SWEEP" => features::sweep::execute(&ctx),
1494        "SWP" | "PATH SWEEP" | "PATHSWEEP" => features::path_sweep::execute(&ctx),
1495        "RIB" => features::rib::execute(&ctx),
1496        "TU" | "TUBE" => features::tube::execute(&ctx),
1497        // --- Edit / boolean / transform ---
1498        "B" | "BOOLEAN" => features::boolean::execute(&ctx),
1499        "M" | "MIRROR" => features::mirror::execute(&ctx),
1500        "SPL" | "SPLIT" => features::split::execute(&ctx),
1501        "XFORM" | "TRANSFORM" => features::transform::execute(&ctx),
1502        "PATTERN" => features::pattern::execute(&ctx),
1503        // --- Dressups ---
1504        "F" | "FILLET" => features::fillet::execute(&ctx),
1505        "CH" | "CHAMFER" => features::chamfer::execute(&ctx),
1506        "O.S" | "OFFSET SHELL" | "OFFSETSHELL" => features::offset_shell::execute(&ctx),
1507        "O.F" | "OFFSET FACE" | "OFFSETFACE" => features::offset_face::execute(&ctx),
1508        "PF" | "PUSHFACE" | "PUSH FACE" => features::push_face::execute(&ctx),
1509        "TF" | "TRANSFORMFACE" | "TRANSFORM FACE" => features::transform_face::execute(&ctx),
1510        "DF" | "DELETE FACE" | "DELETEFACE" => features::delete_face::execute(&ctx),
1511        "RFS" | "REFIT FACES" | "REFITFACES" => features::refit_faces::execute(&ctx),
1512        "THK" | "THICKEN" => features::thicken::execute(&ctx),
1513        "H" | "HOLE" => features::hole::execute(&ctx),
1514        // --- No-kernel-op / long tail ---
1515        "IMPORT3D" => features::import3d::execute(&ctx),
1516        "SM.TAB" => features::sheet_metal_tab::execute(&ctx),
1517        "SM.CF" => features::sheet_metal_contour_flange::execute(&ctx),
1518        "SM.F" => features::sheet_metal_flange::execute(&ctx),
1519        "SM.HEM" => features::sheet_metal_hem::execute(&ctx),
1520        "SM.FILLET" => features::sheet_metal_corner::execute_fillet(&ctx),
1521        "SM.CHAMFER" => features::sheet_metal_corner::execute_chamfer(&ctx),
1522        "SM.CUTOUT" => features::sheet_metal_cutout::execute(&ctx),
1523        "SM.UNFOLD" => features::sheet_metal_unfold::execute(&ctx),
1524        // --- Assemblies: one placed parts-library instance. Keep these
1525        //     literals in sync with `parts_library::is_acomp_type` (the
1526        //     fingerprint-mix + GC hooks key on the same strings). ---
1527        "ACOMP" | "ASSEMBLY COMPONENT" => features::assembly_component::execute(&ctx),
1528        // --- Construction geometry that registers named plane frames (headless
1529        //     sketch-plane resolution) ---
1530        "D" | "DATUM" | "DATIUM" => features::datum::execute(&ctx),
1531        "P" | "PLANE" => features::plane::execute(&ctx),
1532        // --- Sketch: solves + extracts a profile the add-material features consume ---
1533        "S" | "SKETCH" => features::sketch::execute(&ctx),
1534        // --- 3D sketch: free-space points/lines/arcs/beziers solved in 3D, published as paths ---
1535        "S3D" | "SKETCH3D" | "3D SKETCH" => features::sketch3d::execute(&ctx),
1536        // --- Non-solid construction geometry: editor-drawn pass-throughs ---
1537        "SP" | "SPLINE" => features::spline::execute(&ctx),
1538        "WP" | "WAYPOINT" => features::waypoint::execute(&ctx),
1539        "HX" | "HELIX" => features::helix::execute(&ctx),
1540        // --- Scoped extensions cannot replace built-ins. ---
1541        _ if feature_type.contains('/') => extension::execute(&ctx),
1542        // --- Genuinely unknown type string ---
1543        _ => FeatureResult::error(id, feature_type.clone(), format!("unknown feature type '{feature_type}'")),
1544    }
1545}
1546
1547// ===========================================================================
1548// The incremental history cache — dependency-driven dirty tracking
1549// ===========================================================================
1550//
1551// A feature is DIRTY when it itself changed (its serialized descriptor hash — or
1552// the expression env — differs) or when a NAME it references was (re)produced,
1553// removed, or re-resolved differently since its cached run. Everything else is
1554// CLEAN: its cached result (resident handles, profiles, frames, axes, paths)
1555// replays into the scene untouched and is flagged `reused` so the caller skips display
1556// rebuild. Dependency edges come from the exact-match name contract itself
1557// (contract rule 1): any string in a feature's params matching a name produced
1558// earlier in the history IS a reference.
1559//
1560// OWNERSHIP: cache entries own the handles their feature produced. A handle (and
1561// its sheet-metal tree) is freed exactly when its producing entry is invalidated
1562// (feature dirty/deleted, or `clear_history_cache`). Nothing else frees scene
1563// handles — not `SceneMap::apply`, and not the caller (display Solids are non-owning
1564// views post-flip). Consumed intermediates therefore stay resident until an edit
1565// invalidates their producer: the accepted memory cost of incremental replay.
1566
1567/// One cached feature execution.
1568struct CachedFeature {
1569    /// A component's resident members were re-posed after feature execution.
1570    /// Its cached pre-solve component record must not replay against those
1571    /// mutated handles, even when authored expressions evaluate identically.
1572    posed_externally: bool,
1573    /// Hash of `type` + `inputParams` + `persistentData` + the env fingerprint.
1574    fingerprint: u64,
1575    /// The successful result (errored results are NEVER cached — an errored
1576    /// feature is unconditionally dirty next run).
1577    result: FeatureResult,
1578    /// The referenced names that RESOLVED against the names available at its
1579    /// position in the history. Compared for equality each run: a reference that
1580    /// starts/stops resolving (producer added/deleted/reordered) flips dirty.
1581    consumed: std::collections::BTreeSet<String>,
1582    /// Every name this feature produced or removed — the invalidation blast
1583    /// radius handed to `changed` when the entry dies.
1584    touched: HashMap<String, ()>,
1585    /// Content hash of this feature's EFFECTIVE inputs: its own `fingerprint`
1586    /// PLUS, for every consumed name, the producing feature's `output_version`
1587    /// (a Merkle hash over the feature DAG). This is what makes reuse correct
1588    /// ACROSS runs — including after a stop-point edit re-caches an upstream
1589    /// feature so it looks "clean" on the next full run. The per-run `changed`
1590    /// wavefront (below) only sees dirtiness WITHIN one run; this sees it across
1591    /// runs by comparing the input content directly. See `feature_output_version`.
1592    output_version: u64,
1593}
1594
1595thread_local! {
1596    /// Feature id -> its cached execution, persisted across `execute_history`
1597    /// calls (same thread = same wasm instance).
1598    static HISTORY_CACHE: std::cell::RefCell<HashMap<String, CachedFeature>> =
1599        std::cell::RefCell::new(HashMap::new());
1600}
1601
1602/// In-place component motion invalidates the cached producer, but must not
1603/// free its handles until the next rebuild (the current scene still uses them).
1604fn mark_component_cache_posed(id: &str) {
1605    HISTORY_CACHE.with(|cache| {
1606        if let Some(entry) = cache.borrow_mut().get_mut(id) {
1607            entry.posed_externally = true;
1608        }
1609    });
1610}
1611
1612/// Free a dead entry's owned resources: each produced handle and its
1613/// sheet-metal tree. The SINGLE place cached handles die.
1614fn free_entry(entry: &CachedFeature) {
1615    for added in &entry.result.added {
1616        sheet_metal::remove_tree(added.handle);
1617        crate::free_registered_solid(added.handle);
1618    }
1619}
1620
1621/// Drop the whole cache, freeing every owned handle + tree. Called by the caller on a
1622/// part/document switch (and by every Rust test for hermeticity).
1623pub fn clear_history_cache() {
1624    HISTORY_CACHE.with(|cache| {
1625        let mut cache = cache.borrow_mut();
1626        for entry in cache.values() {
1627            free_entry(entry);
1628        }
1629        cache.clear();
1630    });
1631    sheet_metal::clear_trees();
1632    // The per-coedge reading memo the boolean's operand preparation keeps.
1633    crate::reading_memo::clear();
1634    // The per-face mesh fragments the soundness scan and the display share.
1635    crate::watertight_tessellation::clear_face_memo();
1636    crate::soundness::pair_memo::clear();
1637    crate::soundness::fold_memo::clear();
1638    crate::pair_classification::clear_classify_memo();
1639    // The wire-harness tail's bundle solids are owned outside the per-feature
1640    // entries; they die with the cache too.
1641    wire_harness::clear_cache();
1642    // Document-switch semantics: the parts library is per-document state and
1643    // resets with the cache (the next run's request block re-seeds it).
1644    parts_library::clear_all();
1645}
1646
1647/// wasm boundary for [`clear_history_cache`].
1648#[wasm_bindgen]
1649pub fn clear_history_cache_json() {
1650    clear_history_cache();
1651}
1652
1653/// Stable-enough fingerprint of one descriptor, with its expression-bearing
1654/// string leaves EVALUATED against `env`. `DefaultHasher` is stable within a
1655/// process, which is exactly the cache's lifetime.
1656///
1657/// This is what makes expression-edit invalidation FINE-GRAINED: an edit to the
1658/// expression sheet (or the configurator) only moves the fingerprint of a feature
1659/// whose parameter VALUES actually change, instead of the old coarse
1660/// `env_fingerprint` that hashed the whole sheet into every feature and thus
1661/// dirtied everything. The env's variable + configurator values reach a feature
1662/// only through the string params it evaluates, so hashing those evaluated values
1663/// captures exactly the feature's dependency on the sheet.
1664fn descriptor_fingerprint(descriptor: &FeatureDescriptor, env: &Env) -> u64 {
1665    use std::hash::{Hash, Hasher};
1666    let mut hasher = std::collections::hash_map::DefaultHasher::new();
1667    descriptor.feature_type.hash(&mut hasher);
1668    extension::identity(&descriptor.feature_type).hash(&mut hasher);
1669    // Both param sources: `persistent_data` (e.g. sketch coordinates) can hold
1670    // expression strings too, so it must be evaluated or an expression-driven
1671    // sketch coord would go stale on a sheet edit.
1672    hash_evaluated(&descriptor.input_params, env, &mut hasher);
1673    hash_evaluated(&descriptor.persistent_data, env, &mut hasher);
1674    hasher.finish()
1675}
1676
1677/// Feed a descriptor value into the hasher with every string leaf contributing
1678/// BOTH its raw text AND, if it parses as an expression, its evaluated value.
1679///
1680/// - Raw-ALWAYS keeps verbatim-read strings (ids, `reference_selection` names,
1681///   enum codes) honest: swapping one for a *different* string that happens to
1682///   evaluate to the same number still moves the hash.
1683/// - The evaluated value is what lets an UNRELATED sheet edit leave a
1684///   numeric-expression field untouched (its raw text `"w"` is unchanged and its
1685///   value only moves when `w` moves).
1686/// - A non-expression string simply fails to `eval` and contributes only its raw
1687///   text. A reference name that collides with a variable evaluates too → at
1688///   worst a harmless FALSE-dirty when that variable is edited (never a stale
1689///   reuse; the reference's real dependency rides the consumed-set /
1690///   `output_version`).
1691///
1692/// Object keys are visited in sorted order so the hash is representation-stable.
1693fn hash_evaluated(value: &serde_json::Value, env: &Env, hasher: &mut impl std::hash::Hasher) {
1694    use std::hash::Hash;
1695    match value {
1696        serde_json::Value::String(text) => {
1697            0u8.hash(hasher);
1698            text.hash(hasher);
1699            // Only attempt the (parsing) eval on strings short enough to be a real
1700            // expression — `persistent_data` can be large, and the raw text above
1701            // already covers everything for correctness.
1702            if text.len() <= 64 {
1703                if let Ok(number) = env.eval(text) {
1704                    1u8.hash(hasher);
1705                    number.to_bits().hash(hasher);
1706                }
1707            }
1708        }
1709        serde_json::Value::Array(items) => {
1710            2u8.hash(hasher);
1711            for item in items {
1712                hash_evaluated(item, env, hasher);
1713            }
1714        }
1715        serde_json::Value::Object(map) => {
1716            3u8.hash(hasher);
1717            let mut keys: Vec<&String> = map.keys().collect();
1718            keys.sort();
1719            for key in keys {
1720                key.hash(hasher);
1721                hash_evaluated(&map[key], env, hasher);
1722            }
1723        }
1724        other => {
1725            // Number / bool / null — canonical serialized form.
1726            4u8.hash(hasher);
1727            other.to_string().hash(hasher);
1728        }
1729    }
1730}
1731
1732/// Every suffix a stored reference can carry that is an ALIAS for the SKETCH it
1733/// names rather than a produced name of its own. The kernel run publishes a
1734/// sketch's profile under the bare sketch id, and each of these spellings
1735/// resolves back to it:
1736///
1737/// - `:PROFILE` — the profile's face-name spelling ([`SceneMap::resolve_profile`]
1738///   and [`SceneMap::resolve_path`] both strip it).
1739/// - `:FACE` — the RENDER-side display sheet a committed sketch is drawn as; its
1740///   one planar face is PICKED as `{sketch}:FACE` (`abi::display`), a name the
1741///   kernel run NEVER materializes, so `available` can only ever hold the base.
1742///   `features::common::normalize_profile_alias` strips it at execute time, and
1743///   real saved models store exactly this spelling for a sketch pick — leaving it
1744///   un-canonicalised here is what kept a sketch edit from re-running its extrude.
1745///
1746/// Field-blind on purpose: a false-dirty from an unrelated string that happens to
1747/// end this way is harmless, a missed edge is stale geometry.
1748const SKETCH_REFERENCE_ALIASES: [&str; 2] = [":PROFILE", ":FACE"];
1749
1750/// Collect every string in the descriptor (inputParams + persistentData,
1751/// recursively) that EXACT-matches a name available earlier in the history
1752/// (directly, or with a selection ALIAS suffix — [`SKETCH_REFERENCE_ALIASES`] —
1753/// stripped) — the feature's resolvable reference set.
1754/// Whether a feature's persistent data holds anything (a later feature's
1755/// id-based references live there).
1756fn has_persistent_data(value: &serde_json::Value) -> bool {
1757    match value {
1758        serde_json::Value::Null => false,
1759        serde_json::Value::Object(map) => !map.is_empty(),
1760        serde_json::Value::Array(items) => !items.is_empty(),
1761        serde_json::Value::String(text) => !text.is_empty(),
1762        _ => true,
1763    }
1764}
1765
1766/// The boolean's seam re-seat gate (lane X row 11b): `None` when a feature
1767/// after it carries persistent data (an id-based reference this walk cannot
1768/// read) or it consumes no resident solid; otherwise every face and edge name
1769/// of the solids it consumes that a later feature's inputParams text spells
1770/// (every derived edge name embeds its faces' names), sorted. The kernel
1771/// re-seats only a wall none of these names touches.
1772fn seam_reseat_references(
1773    consumed: &std::collections::BTreeSet<String>,
1774    scene: &SceneMap,
1775    later_texts: &[String],
1776    later_persistent: bool,
1777) -> Option<Vec<String>> {
1778    if later_persistent {
1779        return None;
1780    }
1781    let handles: Vec<u32> = consumed.iter().filter_map(|name| scene.solids.get(name).copied()).collect();
1782    if handles.is_empty() {
1783        return None;
1784    }
1785    let spelled = |name: &String| later_texts.iter().any(|text| text.contains(name.as_str()));
1786    let mut names: Vec<String> = scene
1787        .faces
1788        .iter()
1789        .filter(|(name, face)| handles.contains(&face.handle) && spelled(name))
1790        .map(|(name, _)| name.clone())
1791        .chain(scene.edges.iter().filter(|(name, edge)| handles.contains(&edge.handle) && spelled(name)).map(|(name, _)| name.clone()))
1792        .collect();
1793    names.sort();
1794    names.dedup();
1795    Some(names)
1796}
1797
1798fn scan_consumed(
1799    descriptor: &FeatureDescriptor,
1800    available: &HashMap<String, ()>,
1801) -> std::collections::BTreeSet<String> {
1802    fn walk(
1803        value: &serde_json::Value,
1804        available: &HashMap<String, ()>,
1805        out: &mut std::collections::BTreeSet<String>,
1806    ) {
1807        match value {
1808            serde_json::Value::String(text) => {
1809                let trimmed = text.trim();
1810                if trimmed.is_empty() {
1811                    return;
1812                }
1813                // Record the CANONICAL produced name, not the alias spelling:
1814                // a `{sketch}:PROFILE` / `{sketch}:FACE` reference resolves
1815                // against the profile published under `{sketch}`, and the dirty
1816                // check intersects this set with produced/changed names —
1817                // recording the alias verbatim made a sketch edit invisible to
1818                // its consumers (changed = {"S1"}, consumed = {"S1:PROFILE"},
1819                // no overlap). EXACT match wins first, so a real produced name
1820                // that happens to end in an alias suffix is never rewritten.
1821                if available.contains_key(trimmed) {
1822                    out.insert(trimmed.to_string());
1823                } else if let Some(base) = SKETCH_REFERENCE_ALIASES
1824                    .iter()
1825                    .find_map(|alias| trimmed.strip_suffix(alias))
1826                    .filter(|base| available.contains_key(*base))
1827                {
1828                    out.insert(base.to_string());
1829                }
1830            }
1831            serde_json::Value::Array(items) => {
1832                for item in items {
1833                    walk(item, available, out);
1834                }
1835            }
1836            serde_json::Value::Object(map) => {
1837                for item in map.values() {
1838                    walk(item, available, out);
1839                }
1840            }
1841            _ => {}
1842        }
1843    }
1844    let mut out = std::collections::BTreeSet::new();
1845    walk(&descriptor.input_params, available, &mut out);
1846    walk(&descriptor.persistent_data, available, &mut out);
1847    out
1848}
1849
1850/// The EFFECTIVE input hash of one feature: its own descriptor `fingerprint`
1851/// combined with the `output_version` of every name it consumes. Because each
1852/// producer's `output_version` is itself computed this way, this is a Merkle hash
1853/// over the whole upstream DAG: it changes iff the feature's own descriptor OR any
1854/// transitive input changed. A feature is reusable iff its cached `output_version`
1855/// still equals this — which is exactly "nothing changed for any of its inputs",
1856/// and is correct across runs (a stop-point edit that re-cached an upstream feature
1857/// bumps that feature's version, so this consumer's version no longer matches).
1858///
1859/// `consumed` is a `BTreeSet`, so the iteration order is deterministic. A consumed
1860/// name should always have a version (it came from an already-walked producer); a
1861/// missing one hashes as `0` rather than panicking.
1862fn feature_output_version(
1863    fingerprint: u64,
1864    consumed: &std::collections::BTreeSet<String>,
1865    name_version: &HashMap<String, u64>,
1866) -> u64 {
1867    use std::hash::{Hash, Hasher};
1868    let mut hasher = std::collections::hash_map::DefaultHasher::new();
1869    fingerprint.hash(&mut hasher);
1870    for name in consumed {
1871        name.hash(&mut hasher);
1872        name_version.get(name).copied().unwrap_or(0).hash(&mut hasher);
1873    }
1874    hasher.finish()
1875}
1876
1877/// Every name a result adds to the scene: solid/face/edge names, the CONTAINER
1878/// group aliases, plus the profile/frame/axis/path names from the side-channels.
1879///
1880/// This must mirror [`SceneMap::apply`] exactly — every map a name can be
1881/// RESOLVED from has to be versioned here, or a consumer referencing that name
1882/// records nothing in its consumed set, its `output_version` never moves, and it
1883/// replays stale geometry across a real upstream edit.
1884fn produced_names(result: &FeatureResult) -> Vec<String> {
1885    let mut names = Vec::new();
1886    for added in &result.added {
1887        names.push(added.name.clone());
1888        names.extend(added.face_names.iter().map(|(_, name)| name.clone()));
1889        names.extend(added.edge_names.iter().map(|(_, name)| name.clone()));
1890        // The un-keyed CONTAINER spellings (`{cap_base}_START` and the edge
1891        // names derived from it) are resolvable scene names — a model saved
1892        // before per-loop cap naming references them, and `resolve_face_group` /
1893        // `resolve_edge_group` answer. They are the name a dressup feature
1894        // actually stores, so they must version like any other produced name.
1895        names.extend(added.face_groups.iter().map(|(name, _)| name.clone()));
1896        names.extend(added.edge_groups.iter().map(|(name, _)| name.clone()));
1897    }
1898    names.extend(result.profiles.iter().map(|(name, _)| name.clone()));
1899    names.extend(result.frames.iter().map(|(name, _)| name.clone()));
1900    names.extend(result.axes.iter().map(|(name, _)| name.clone()));
1901    names.extend(result.paths.iter().map(|(name, _)| name.clone()));
1902    names.extend(result.points.iter().map(|(name, _)| name.clone()));
1903    names.extend(result.ports.iter().map(|(name, _)| name.clone()));
1904    // A component's id is a produced name: a reference to the component (a
1905    // COMPONENT-type selection in a descriptor) versions against its producer.
1906    names.extend(result.components.iter().map(|record| record.id.clone()));
1907    names
1908}
1909
1910// ===========================================================================
1911// The history loop
1912// ===========================================================================
1913
1914/// Run a whole feature history incrementally: build the expression env once,
1915/// then walk the ordered features. A CLEAN feature (see the cache section above)
1916/// replays its cached result; a DIRTY one re-executes (its old outputs are freed
1917/// first). On a feature error, record it and HALT (abort-on-error);
1918/// errored results are never cached. Never panics.
1919pub fn execute_history(request: &HistoryRequest) -> HistoryResult {
1920    execute_history_observed(request, &mut |_| true)
1921}
1922
1923/// A feature about to EXECUTE inside [`execute_history_observed`] — a dirty
1924/// one, not a cached replay (replays are instant and are not reported).
1925#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1926pub struct HistoryProgress<'a> {
1927    /// Zero-based position of the feature in the request.
1928    pub index: usize,
1929    /// The request's feature count.
1930    pub total: usize,
1931    pub id: &'a str,
1932    pub feature_type: &'a str,
1933}
1934
1935/// [`execute_history`] with a progress observer. `observe` is called
1936/// immediately BEFORE each feature the run executes (cached replays are not
1937/// reported); returning `false` stops the run at that boundary — the feature
1938/// is not executed, nothing after it runs, and the result holds what was
1939/// built so far. The boundary is the only cooperative stop the kernel offers:
1940/// nothing inside a feature (a boolean, a blend, a sew) checks anything.
1941///
1942/// The cache bookkeeping is untouched by an early stop: the entries of the
1943/// features that did run are as valid as after a full run, and the entries of
1944/// the ones that did not were retained as parse-only exactly as under a
1945/// `stop_before_id`, so the next full run replays the former and executes the
1946/// latter.
1947pub fn execute_history_observed(
1948    request: &HistoryRequest,
1949    observe: &mut dyn FnMut(HistoryProgress<'_>) -> bool,
1950) -> HistoryResult {
1951    let _plugin_scope = extension::enter(&request.plugins);
1952    let env = Env::build(&request.expressions, &request.configurator)
1953        .unwrap_or_else(Env::poisoned);
1954
1955    // Seed the kernel-resident parts library from the request block (document
1956    // load; resident-wins rules keep a stale block from undoing kernel-side
1957    // heals/refreshes — see parts_library.rs).
1958    parts_library::ingest(&request.parts_library);
1959
1960    // Entries whose feature was DELETED from the history die now. Their
1961    // consumers go dirty via the consumed-set equality check (the vanished names
1962    // drop out of the available set), so no changed-seeding is needed here.
1963    let request_ids: HashMap<String, ()> = request
1964        .features
1965        .iter()
1966        .map(|descriptor| (extract_id(&descriptor.input_params), ()))
1967        .collect();
1968    HISTORY_CACHE.with(|cache| {
1969        let mut cache = cache.borrow_mut();
1970        cache.retain(|id, entry| {
1971            let keep = request_ids.contains_key(id);
1972            if !keep {
1973                free_entry(entry);
1974            }
1975            keep
1976        });
1977    });
1978
1979    let mut scene = SceneMap::default();
1980    let mut results = Vec::with_capacity(request.features.len());
1981    // Per-feature wall-clock timing, in run order (`web_time::Instant` — plain
1982    // `std::time::Instant` traps 'unreachable' on wasm32).
1983    let mut timings: Vec<(String, f64)> = Vec::with_capacity(request.features.len());
1984    // Names whose content changed this run (produced/removed by any re-executed
1985    // or invalidated feature) — the dirty wavefront.
1986    let mut changed: HashMap<String, ()> = HashMap::new();
1987    // Names available for reference so far this run (from clean AND dirty
1988    // features alike).
1989    let mut available: HashMap<String, ()> = HashMap::new();
1990    // Each available name -> the `output_version` of the feature that produced it
1991    // this run (walk order: a boolean that reuses its target name overwrites the
1992    // producer's version, so consumers depend on the boolean's version). Feeds
1993    // `feature_output_version` so cross-run reuse is decided by input CONTENT.
1994    let mut name_version: HashMap<String, u64> = HashMap::new();
1995    let mut seen_ids: HashMap<String, ()> = HashMap::new();
1996
1997    // The declared connection points whose placement nothing the walk builds
1998    // can move, published BEFORE it so a SPLINE in the same document can
1999    // attach to one and a sketch can sit on its frame (`ports.rs` states the
2000    // rule and why this is the one deviation from tail-only resolution). Each
2001    // name carries the CONTENT VERSION of its declaration, so a consumer is
2002    // invalidated when the point moves.
2003    for (name, version) in ports::seed_history_run(request, &mut scene, &env) {
2004        available.insert(name.clone(), ());
2005        name_version.insert(name, version);
2006    }
2007
2008    let total = request.features.len();
2009    // Lane X row 11b: each feature's inputParams text, and whether any feature
2010    // AFTER index i carries persistent data (an id-based reference this walk
2011    // cannot read), for the boolean feature's seam re-seat gate.
2012    let input_texts: Vec<String> = request.features.iter().map(|descriptor| descriptor.input_params.to_string()).collect();
2013    let mut persistent_after = vec![false; total + 1];
2014    for index in (0..total).rev() {
2015        persistent_after[index] = persistent_after[index + 1] || has_persistent_data(&request.features[index].persistent_data);
2016    }
2017    for (index, descriptor) in request.features.iter().enumerate() {
2018        let id = extract_id(&descriptor.input_params);
2019        // Editor stop-point: BEFORE this feature — the rest of the request is
2020        // parse-only (their cache entries were already retained above).
2021        if request.stop_before_id.as_deref() == Some(id.as_str()) {
2022            break;
2023        }
2024        // An empty or duplicated id cannot key a cache entry: execute plainly,
2025        // touching no cached state (a duplicate must not free the entry its
2026        // first occurrence just wrote).
2027        let cacheable = !id.is_empty() && seen_ids.insert(id.clone(), ()).is_none();
2028        let fingerprint = descriptor_fingerprint(descriptor, &env);
2029        // Assemblies: an ACOMP instance's effective input includes its
2030        // parts-library entry's CONTENT (key/signature/document — not the
2031        // snapshot, so a self-heal does not dirty it), and a DIRTY entry
2032        // (refresh_library_entry) forces re-execution outright. A no-op for
2033        // every other feature type.
2034        let (fingerprint, library_dirty) =
2035            parts_library::mix_descriptor_fingerprint(descriptor, fingerprint);
2036        let consumed = scan_consumed(descriptor, &available);
2037        let reseat_references = if matches!(descriptor.feature_type.as_str(), "B" | "BOOLEAN") {
2038            seam_reseat_references(&consumed, &scene, &input_texts[index + 1..], persistent_after[index + 1])
2039        } else {
2040            None
2041        };
2042        // What the boolean may re-seat changes what it builds, so it keys the cache.
2043        let fingerprint = match &reseat_references {
2044            Some(names) => {
2045                use std::hash::{Hash, Hasher};
2046                let mut hasher = std::collections::hash_map::DefaultHasher::new();
2047                (fingerprint, "seam-reseat", names).hash(&mut hasher);
2048                hasher.finish()
2049            }
2050            None => fingerprint,
2051        };
2052        // Merkle input hash over this feature + its consumed producers' versions.
2053        // Computed for EVERY feature (cacheable or not) so its produced names can
2054        // publish a version for downstream consumers.
2055        let output_version = feature_output_version(fingerprint, &consumed, &name_version);
2056
2057        let clean = cacheable
2058            && !library_dirty
2059            && !request.force_rebuild.iter().any(|forced| forced == &id)
2060            && HISTORY_CACHE.with(|cache| {
2061                cache.borrow().get(&id).is_some_and(|entry| {
2062                    !entry.posed_externally
2063                        && entry.fingerprint == fingerprint
2064                        && entry.consumed == consumed
2065                        && consumed.iter().all(|name| !changed.contains_key(name))
2066                        // The cross-run clause: reuse only if the effective input
2067                        // content is byte-identical to what this entry was built
2068                        // from. Subsumes the three clauses above (they are hashed
2069                        // in); kept additively so the diff stays minimal and the
2070                        // handle-ownership / blast-radius paths are untouched.
2071                        && entry.output_version == output_version
2072                })
2073            });
2074
2075        if clean {
2076            let mut result =
2077                HISTORY_CACHE.with(|cache| cache.borrow().get(&id).unwrap().result.clone());
2078            result.reused = true;
2079            scene.apply(&result);
2080            for name in produced_names(&result) {
2081                available.insert(name.clone(), ());
2082                // A clean feature's current version equals its cached one; publish
2083                // it so downstream consumers hash the SAME value they cached against.
2084                name_version.insert(name, output_version);
2085            }
2086            results.push(result);
2087            timings.push((id.clone(), 0.0)); // replayed, not re-executed
2088            // Editor stop-point: AFTER this feature.
2089            if request.stop_at_id.as_deref() == Some(id.as_str()) {
2090                break;
2091            }
2092            continue;
2093        }
2094
2095        // Dirty: the old entry (if any) dies — its blast radius joins `changed`.
2096        if cacheable {
2097            if let Some(old) = HISTORY_CACHE.with(|cache| cache.borrow_mut().remove(&id)) {
2098                free_entry(&old);
2099                changed.extend(old.touched.iter().map(|(name, _)| (name.clone(), ())));
2100            }
2101        }
2102
2103        // The observer's boundary: the feature is dirty and about to execute.
2104        if !observe(HistoryProgress {
2105            index,
2106            total,
2107            id: &id,
2108            feature_type: &descriptor.feature_type,
2109        }) {
2110            break;
2111        }
2112
2113        // Anything left in the ledger by a DIRECT api call on this thread
2114        // (`move_faces_json`, an MCP edit) belongs to that call, not to the
2115        // feature about to run: drop it rather than attribute it wrongly.
2116        let _ = crate::take_crossing_repairs();
2117        let _ = crate::take_blend_notes();
2118        let _ = crate::take_blend_approximations(&[]);
2119        // The feature is ONE blend operation however many blend calls it
2120        // makes: none of them drops another's reports before the consume below.
2121        let blend_operation = crate::blend::BlendOperation::enter();
2122        let feature_profile = crate::boolean::profile::Feature::begin();
2123        let feat_start = web_time::Instant::now();
2124        let mut result = execute_feature_with_later(descriptor, &env, &scene, reseat_references.as_deref());
2125        let feature_ms = feat_start.elapsed().as_secs_f64() * 1000.0;
2126        feature_profile.finish(&id, feature_ms);
2127        timings.push((id.clone(), feature_ms));
2128        // A result the soundness acceptance REPAIRED rather than returned as
2129        // built says so on the feature that built it. Drained here, so a repair
2130        // made by any lane reaches the caller's report by one route instead of
2131        // each lane growing a channel of its own.
2132        result.notes.extend(
2133            crate::take_crossing_repairs()
2134                .into_iter()
2135                .map(|repair| repair.to_string()),
2136        );
2137        // What a blend that shipped says about its own wall (a station ladder
2138        // that ran out with its rails still off their carriers), by the same
2139        // route.
2140        result.notes.extend(crate::take_blend_notes());
2141        // A fillet wall that shipped short of its construction request says so
2142        // TYPED, on the body that carries it: ONE snapshot of the ledger read
2143        // against EVERY body this feature returned. A report whose wall no
2144        // returned body carries (a lane that refused, a body a later step
2145        // discarded) is dropped; a refused feature returns no body, so it
2146        // carries none. Attached before the result is cached, so a replay
2147        // carries the same typed reports.
2148        if crate::blend::blend_approximations_pending() {
2149            let solids: Vec<(String, crate::BrepSolid)> = result
2150                .added
2151                .iter()
2152                .filter_map(|added| crate::registered_solid_clone(added.handle).ok().map(|solid| (added.name.clone(), solid)))
2153                .collect();
2154            let bodies: Vec<(&str, &crate::BrepSolid)> = solids.iter().map(|(name, solid)| (name.as_str(), solid)).collect();
2155            result.approximations.extend(crate::take_blend_approximations(&bodies));
2156        }
2157        drop(blend_operation);
2158        // `halt` reflects the feature's OWN error only — a naming collision flags
2159        // the feature but does NOT truncate the history (the model still renders).
2160        let halt = result.error.is_some();
2161        let collisions_before = scene.name_collisions.len();
2162        scene.apply(&result);
2163        // Naming-contract guard: if applying this feature's output left two RESIDENT
2164        // solids sharing a face/edge name, surface it as the feature's error so the
2165        // operation trips its own tests + shows an error in the app (the hint points
2166        // at `common::namespace_copy_names`). Fresh path only — a cached replay
2167        // carries its collision error, if any, already.
2168        if result.error.is_none() && scene.name_collisions.len() > collisions_before {
2169            result.error = Some(name_collision_error(
2170                &scene.name_collisions[collisions_before..],
2171            ));
2172        }
2173
2174        // Kernel-owned topology metadata: every face/edge this feature produced
2175        // records its producer (the `_seedSourceFeatureMetadata` step, moved here).
2176        // Non-overwriting — faces propagated through a boolean keep their
2177        // original sourceFeatureId, matching the established seed semantics.
2178        if !id.is_empty() {
2179            let mut seed = serde_json::Map::new();
2180            seed.insert("sourceFeatureId".into(), serde_json::Value::String(id.clone()));
2181            for added in &result.added {
2182                for (_, face_name) in &added.face_names {
2183                    scene_metadata::merge_record(face_name, &seed, false);
2184                }
2185                for (_, edge_name) in &added.edge_names {
2186                    scene_metadata::merge_record(edge_name, &seed, false);
2187                }
2188            }
2189        }
2190
2191        // Enrich every miss with the name that replaced it, when the miss looks
2192        // like the per-loop naming change (see `annotate_rename`).
2193        for name in &mut result.unresolved {
2194            *name = annotate_rename(&scene, name);
2195        }
2196        // The same hint on the typed report, in the same pass, so the two
2197        // lists never say different things about one miss.
2198        if let Some(fulfilment) = &mut result.fulfilment {
2199            for rejected in &mut fulfilment.rejected {
2200                rejected.name = annotate_rename(&scene, &rejected.name);
2201            }
2202        }
2203
2204        let produced = produced_names(&result);
2205        for name in &produced {
2206            available.insert(name.clone(), ());
2207            changed.insert(name.clone(), ());
2208            // Publish this run's version for the name. Runs for cacheable AND
2209            // non-cacheable (empty/duplicate id) features alike — a non-cacheable
2210            // feature has no cache entry but its outputs still version their
2211            // downstream consumers correctly.
2212            name_version.insert(name.clone(), output_version);
2213        }
2214        for name in &result.removed {
2215            changed.insert(name.clone(), ());
2216        }
2217
2218        if cacheable && !halt {
2219            let mut touched: HashMap<String, ()> =
2220                produced.into_iter().map(|name| (name, ())).collect();
2221            touched.extend(result.removed.iter().map(|name| (name.clone(), ())));
2222            HISTORY_CACHE.with(|cache| {
2223                cache.borrow_mut().insert(
2224                    id.clone(),
2225                    CachedFeature {
2226                        posed_externally: false,
2227                        fingerprint,
2228                        result: result.clone(),
2229                        consumed,
2230                        touched,
2231                        output_version,
2232                    },
2233                );
2234            });
2235        }
2236
2237        results.push(result);
2238        if halt {
2239            break;
2240        }
2241        // Editor stop-point: AFTER this feature.
2242        if request.stop_at_id.as_deref() == Some(id.as_str()) {
2243            break;
2244        }
2245    }
2246    // Orphan GC: a parts-library entry whose last ACOMP instance is gone from
2247    // the request is dropped now (orphaned payloads never accumulate, the
2248    // request carries the FULL feature list even under a stop point, so
2249    // truncation cannot GC live entries).
2250    parts_library::gc_after_rebuild(request);
2251    // Assembly tail: solve the request's constraints against the just-built
2252    // scene and install the post-solve session the exported assembly ABI
2253    // serves. Unconditional, so a document without an `assembly` block
2254    // resets any stale session.
2255    assembly::finish_history_run(request, &mut scene, &env);
2256    // Wire-harness tail: route the block's connections over the ports and
2257    // spline segments the run published, and build the bundle solids. Its
2258    // solids ride an extra result so the display pipeline shows them through
2259    // the standard solid path. Runs AFTER the assembly solve so the bundles
2260    // are built against the posed scene.
2261    // Ports tail: resolve the declared-ports block against the FINISHED scene
2262    // (a port point may reference any geometry in the part, which is why this
2263    // runs here and not as a history feature) and publish every point. Before
2264    // the harness, which routes over what this published.
2265    let ports = ports::finish_history_run(request, &mut scene, &env);
2266    if let Some(result) = ports.result {
2267        results.push(result);
2268    }
2269    let harness = wire_harness::finish_history_run(request, &mut scene, &env);
2270    if let Some(result) = harness.result {
2271        results.push(result);
2272    }
2273    // PMI tail: resolve every view's annotations against the finished scene
2274    // (bundles and posed components included). Pure reads — never touches
2275    // the cache.
2276    let pmi = pmi::finish_history_run(request, &scene, &env);
2277    HistoryResult {
2278        results,
2279        timings,
2280        wire_harness: harness.report,
2281        pmi,
2282        ports: ports.report,
2283    }
2284}
2285
2286// ===========================================================================
2287// wasm boundary
2288// ===========================================================================
2289
2290/// Deserialize a history request, run it, and serialize the per-feature results.
2291/// The handles in the result are `u32`s the caller tessellates / pulls names
2292/// from via the existing `*_handle` wasm exports.
2293#[wasm_bindgen]
2294pub fn execute_history_json(request_json: &str) -> Result<String, JsValue> {
2295    let request: HistoryRequest = serde_json::from_str(request_json)
2296        .map_err(|error| JsValue::from_str(&format!("execute_history_json: bad request: {error}")))?;
2297    let result = execute_history(&request);
2298    serde_json::to_string(&result).map_err(|error| JsValue::from_str(&error.to_string()))
2299}
2300
2301