Skip to main content

brep_kernel/feature_pipeline/
mod.rs

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