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