Skip to main content

brep_kernel/feature_pipeline/
mod.rs

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