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