Skip to main content

brep_kernel/feature_pipeline/
mod.rs

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