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