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