Skip to main content

brep_kernel/feature_pipeline/
mod.rs

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