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