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