BREP_render 0.1.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! The Properties-panel DATA layer (UI comes later): a name-keyed metadata
//! store, per-entity measurements, and object provenance — all engine-native,
//! all crossing the R3 boundary as plain JSON/scalars.
//!
//! # Metadata store ([`MetadataStore`])
//!
//! `object name → { attribute → value }`, keyed by the KERNEL OBJECT NAME (a
//! solid / face / edge name), **not** a feature id. This loose coupling is the
//! whole point: a record survives feature edits, rollback and re-tessellation as
//! long as the object's name persists (edge/face names ARE propagated through
//! booleans, splits and welds by the kernel). Values are strings; the well-known
//! `density` attribute (mass units per mm³) drives a solid's weight. The store is
//! persisted WITH the model — [`crate::engine_state::EngineState::history_request_json`]
//! folds it in as a top-level `metadata` field and
//! [`crate::engine_state::EngineState::set_history_json`] lifts it back out, so it
//! round-trips through save/open.
//!
//! # Measurements + provenance
//!
//! The [`EngineState`] methods below resolve an object NAME to its kind (solid /
//! face / edge, via the scene) and return the right measurements from the
//! kernel's exact integrators (volume, surface area, arc length), plus the
//! feature that produced the object (provenance, via the history's per-feature
//! output solids). Units are millimetres (the kernel length convention).

use crate::engine_state::EngineState;
use crate::runner::{MeasureKind, MeasureQuery};
use serde_json::Value;
use std::collections::BTreeMap;

/// The default density (mass per unit volume) when an object carries no
/// `density` metadata: unit density, so `weight == volume`.
pub const DEFAULT_DENSITY: f64 = 1.0;

/// The name-keyed metadata store: `object name → { attribute → value }`, string
/// values, deterministic iteration (a `BTreeMap` so the persisted JSON is
/// stable). Empty records are never retained (removing the last attribute drops
/// the whole record).
#[derive(Debug, Clone, Default)]
pub struct MetadataStore {
    entries: BTreeMap<String, BTreeMap<String, String>>,
}

impl MetadataStore {
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether the store holds no records at all.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Set (or overwrite) one attribute of `name`'s record. An empty object name
    /// or key is ignored (no phantom records).
    pub fn set_attribute(&mut self, name: &str, key: &str, value: &str) {
        if name.is_empty() || key.is_empty() {
            return;
        }
        self.entries
            .entry(name.to_string())
            .or_default()
            .insert(key.to_string(), value.to_string());
    }

    /// Remove one attribute of `name`'s record, dropping the record if it becomes
    /// empty. Returns whether the attribute existed.
    pub fn remove_attribute(&mut self, name: &str, key: &str) -> bool {
        let Some(record) = self.entries.get_mut(name) else {
            return false;
        };
        let existed = record.remove(key).is_some();
        if record.is_empty() {
            self.entries.remove(name);
        }
        existed
    }

    /// One attribute's value (`None` if the object or key is unknown).
    pub fn attribute(&self, name: &str, key: &str) -> Option<&str> {
        self.entries.get(name)?.get(key).map(String::as_str)
    }

    /// One object's whole record (empty map if the object has no metadata).
    pub fn record(&self, name: &str) -> BTreeMap<String, String> {
        self.entries.get(name).cloned().unwrap_or_default()
    }

    /// The whole store (all records), read-only.
    pub fn all(&self) -> &BTreeMap<String, BTreeMap<String, String>> {
        &self.entries
    }

    /// The resolved density (mass per mm³) for `name`: its `density` attribute
    /// parsed as a positive finite number, else [`DEFAULT_DENSITY`].
    pub fn density(&self, name: &str) -> f64 {
        self.attribute(name, "density")
            .and_then(|value| value.trim().parse::<f64>().ok())
            .filter(|density| density.is_finite() && *density > 0.0)
            .unwrap_or(DEFAULT_DENSITY)
    }

    /// Drop every record (a part load replaces the store wholesale).
    pub fn clear(&mut self) {
        self.entries.clear();
    }

    /// One object's record as a JSON object `{ key: value, ... }` (`{}` when the
    /// object has no metadata).
    pub fn record_json(&self, name: &str) -> String {
        Value::Object(
            self.record(name)
                .into_iter()
                .map(|(key, value)| (key, Value::String(value)))
                .collect(),
        )
        .to_string()
    }

    /// The whole store as a JSON value `{ name: { key: value, ... }, ... }` — the
    /// persisted shape and the whole-store getter.
    pub fn to_json(&self) -> Value {
        Value::Object(
            self.entries
                .iter()
                .map(|(name, record)| {
                    let object = record
                        .iter()
                        .map(|(key, value)| (key.clone(), Value::String(value.clone())))
                        .collect();
                    (name.clone(), Value::Object(object))
                })
                .collect(),
        )
    }

    /// The whole store as a JSON string (the whole-store getter's string form).
    pub fn to_json_string(&self) -> String {
        self.to_json().to_string()
    }

    /// Replace the whole store from a persisted `metadata` value (or `None`, which
    /// clears it — loading a part with no metadata). Non-string leaf values are
    /// coerced to their JSON text so a legacy document never fails the load.
    pub fn load_json(&mut self, value: Option<&Value>) {
        self.entries.clear();
        let Some(Value::Object(objects)) = value else {
            return;
        };
        for (name, record) in objects {
            let Value::Object(attributes) = record else {
                continue;
            };
            let map: BTreeMap<String, String> = attributes
                .iter()
                .map(|(key, value)| (key.clone(), value_to_string(value)))
                .collect();
            if !map.is_empty() {
                self.entries.insert(name.clone(), map);
            }
        }
    }
}

/// Coerce a persisted metadata leaf to a string value (strings verbatim, `null`
/// to empty, everything else to its JSON text).
fn value_to_string(value: &Value) -> String {
    match value {
        Value::String(text) => text.clone(),
        Value::Null => String::new(),
        other => other.to_string(),
    }
}

/// The kind an object NAME resolves to in the current scene.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ObjectKind {
    Solid,
    Face,
    Edge,
}

// --- EngineState: metadata store API (a SEPARATE impl block, appended, so
//     concurrent edits to the primary block don't conflict) -------------------
impl EngineState {
    /// One object's metadata record as JSON `{ key: value, ... }` (`{}` if none).
    pub fn object_metadata_json(&self, name: &str) -> String {
        self.metadata.record_json(name)
    }

    /// Set (or overwrite) one metadata attribute of an object by NAME. String
    /// value; the well-known `density` key drives the object's weight.
    pub fn set_metadata_attribute(&mut self, name: &str, key: &str, value: &str) {
        self.metadata.set_attribute(name, key, value);
        // A metadata edit (notably `density`) feeds the object-info output but does
        // NOT trigger a history rerun, so drop this object's cached info so a
        // re-selection re-measures with the new attribute.
        self.info_cache.remove(name);
    }

    /// Remove one metadata attribute of an object. Returns whether it existed.
    pub fn remove_metadata_attribute(&mut self, name: &str, key: &str) -> bool {
        let existed = self.metadata.remove_attribute(name, key);
        // Same rerun-less invalidation as `set_metadata_attribute`.
        self.info_cache.remove(name);
        existed
    }

    /// The whole metadata store as JSON `{ name: { key: value } }`.
    pub fn metadata_json(&self) -> String {
        self.metadata.to_json_string()
    }
}

// --- EngineState: measurements + provenance (SEPARATE impl block) ------------
impl EngineState {
    /// Resolve an object NAME to `(kind, owning solid name)` via the display
    /// scene: a solid resolves to itself; a face/edge resolves to its owning
    /// solid. `None` for an empty or unknown name (vertices carry no kernel name).
    fn resolve_object(&self, name: &str) -> Option<(ObjectKind, String)> {
        if name.is_empty() {
            return None;
        }
        if self.scene.solid(name).is_some() {
            return Some((ObjectKind::Solid, name.to_string()));
        }
        for solid in self.scene.solids() {
            if solid.faces.iter().any(|face| face.name == name) {
                return Some((ObjectKind::Face, solid.name.clone()));
            }
        }
        for solid in self.scene.solids() {
            if solid.edges.iter().any(|edge| edge.name == name) {
                return Some((ObjectKind::Edge, solid.name.clone()));
            }
        }
        None
    }

    /// The feature that PRODUCED an object, as `(feature id, feature type)`. For a
    /// face/edge the owning solid's producer is reported. `None` if the name is
    /// unknown or has no known producer. Reads the EAGER provenance the last run
    /// shipped (`name → creating-feature id`), so it never re-runs the history — the
    /// freeze side-door `context_bar` hit every selected frame is now O(1).
    pub fn creating_feature(&self, name: &str) -> Option<(String, String)> {
        let (_, owner) = self.resolve_object(name)?;
        let id = self.provenance.get(&owner)?.clone();
        Some((id.clone(), self.feature_type_of(&id)))
    }

    /// A feature's type token by id (empty string if the id is not in the history).
    fn feature_type_of(&self, id: &str) -> String {
        self.history
            .index_of(id)
            .and_then(|index| self.history.feature_type(index))
            .unwrap_or_default()
    }

    /// The `{ id, type }` provenance JSON for a solid `owner` (or `null` if it has
    /// no known producer), read from the eager provenance map.
    fn creating_feature_value(&self, owner: &str) -> Value {
        match self.provenance.get(owner) {
            Some(id) => serde_json::json!({ "id": id, "type": self.feature_type_of(id) }),
            None => Value::Null,
        }
    }

    /// The full Properties-panel info for an object by NAME: its resolved kind,
    /// the right measurements, and provenance. Units are millimetres.
    ///
    /// - **Solid** — `{ ok, name, kind:"solid", volume, surfaceArea,
    ///   edgeLengthTotal, density, weight, creatingFeature }`, where
    ///   `weight = density · volume` and `density` comes from the object's
    ///   metadata (default [`DEFAULT_DENSITY`]).
    /// - **Face** — `{ ok, name, kind:"face", solid, area, edgeLengthTotal,
    ///   creatingFeature }` (`edgeLengthTotal` = its boundary edges).
    /// - **Edge** — `{ ok, name, kind:"edge", solid, length, creatingFeature }`.
    ///
    /// `{ ok:false, name, message }` for an empty/unknown name, a non-resident
    /// solid, or a kernel measurement failure.
    ///
    /// The real solid/face/edge MEASUREMENT is routed to the [`HistoryRunner`] (so
    /// the warm-registry runner answers it, never the potentially-cold main side)
    /// and CACHED here keyed by name — fired once per selection, served from the
    /// cache every subsequent frame. For the synchronous
    /// [`InlineRunner`](crate::runner::InlineRunner) the submit → `pump_queries`
    /// resolves same-call, so this returns the merged JSON immediately and stays
    /// byte-identical to the pre-seam in-process result; a background
    /// [`ThreadRunner`](crate::runner::ThreadRunner) returns a `pending` placeholder
    /// for the frame(s) until its reply lands (drained by `pump_queries`). The cache
    /// is invalidated on any geometry change (`apply_run_output`) or metadata edit
    /// (`set_metadata_attribute`).
    ///
    /// [`HistoryRunner`]: crate::runner::HistoryRunner
    pub fn object_info_json(&mut self, name: &str) -> String {
        let Some((kind, owner)) = self.resolve_object(name) else {
            // A construction datum/plane carries no resident geometry (no volume /
            // area / length), so it never resolves as a solid/face/edge. Return a
            // graceful minimal record — name + kind + creating feature — rather than
            // erroring, so the Properties Info tab renders for a selected datum and
            // its name flows into the (name-keyed) Metadata tab.
            if let Some((feature_id, feature_type)) = self.datum_feature_for_name(name) {
                let kind_label = if feature_type == "P" { "plane" } else { "datum" };
                return serde_json::json!({
                    "ok": true,
                    "name": name,
                    "kind": kind_label,
                    "creatingFeature": { "id": feature_id, "type": feature_type },
                })
                .to_string();
            }
            return serde_json::json!({
                "ok": false, "name": name, "message": "unknown object",
            })
            .to_string();
        };
        // A committed-sketch SHEET is a scene solid with NO kernel handle, so the
        // handle-based measurement path can't serve it. Measure straight off its
        // synthesized display (planar-mesh triangle areas / edge polylines) and
        // report `kind:"sketch"` — no volume. Handle-less ⇒ synchronous, no query.
        if let Some(solid) = self.scene.solid(&owner) {
            if solid.is_sketch {
                return self.sketch_info_json(name, kind, solid);
            }
        }

        // Real geometry: serve from the info cache, else fire a measurement query at
        // the runner (deduped: never submit a second query for a name already in
        // flight), pump, and return the resolved JSON — or a pending placeholder.
        if let Some(cached) = self.info_cache.get(name) {
            return cached.clone();
        }
        if !self.pending_query.values().any(|(pending, _)| pending == name) {
            self.next_query_id += 1;
            let id = self.next_query_id;
            let measure_kind = match kind {
                ObjectKind::Solid => MeasureKind::Solid,
                ObjectKind::Face => MeasureKind::Face,
                ObjectKind::Edge => MeasureKind::Edge,
            };
            let density = self.metadata.density(name);
            self.pending_query.insert(id, (name.to_string(), owner.clone()));
            self.runner.submit_query(MeasureQuery {
                id,
                kind: measure_kind,
                owner,
                entity: name.to_string(),
                density,
            });
        }
        self.pump_queries();
        match self.info_cache.get(name) {
            Some(resolved) => resolved.clone(),
            None => serde_json::json!({ "ok": false, "name": name, "pending": true }).to_string(),
        }
    }

    /// Drain every completed measurement reply from the runner and fold it into the
    /// name-keyed info cache — the query counterpart of [`EngineState::pump`]. Called
    /// once per frame from `pump` AND synchronously from
    /// [`Self::object_info_json`] (so the Inline runner resolves same-call). Each
    /// reply is MERGED with the main-injected `name` + `creatingFeature` (from the
    /// eager provenance) into the final object-info JSON.
    pub fn pump_queries(&mut self) {
        while let Some(reply) = self.runner.poll_query() {
            let Some((name, owner)) = self.pending_query.remove(&reply.id) else {
                // A reply whose request was invalidated (a rerun cleared the pending
                // set) — drop it; the re-selection re-queries against fresh geometry.
                continue;
            };
            let fragment: Value = serde_json::from_str(&reply.result).unwrap_or(Value::Null);
            let merged = self.merge_info(&name, &owner, &fragment);
            self.info_cache.insert(name, merged);
        }
    }

    /// Merge a runner measurement FRAGMENT with the main-side `name` +
    /// `creatingFeature` into the final object-info JSON, preserving the exact field
    /// ORDER the pre-seam `object_info_json` emitted (so the output is
    /// byte-identical): `ok`, then `name`, then the fragment's remaining fields in
    /// order (`kind`, the measurements — or `message` on error), then
    /// `creatingFeature` (only when `ok`, since an error record carries none).
    fn merge_info(&self, name: &str, owner: &str, fragment: &Value) -> String {
        let object = fragment.as_object();
        let ok = object
            .and_then(|map| map.get("ok"))
            .and_then(Value::as_bool)
            .unwrap_or(false);
        let mut merged = serde_json::Map::new();
        merged.insert("ok".to_string(), Value::Bool(ok));
        merged.insert("name".to_string(), Value::String(name.to_string()));
        if let Some(map) = object {
            for (key, value) in map {
                if key == "ok" {
                    continue;
                }
                merged.insert(key.clone(), value.clone());
            }
        }
        if ok {
            merged.insert(
                "creatingFeature".to_string(),
                self.creating_feature_value(owner),
            );
        }
        Value::Object(merged).to_string()
    }

    /// Properties info for a committed-sketch SHEET object (the sheet solid, its
    /// planar face, or a boundary edge), measured off the synthesized display — a
    /// sketch carries no resident kernel geometry. `kind:"sketch"` for the whole
    /// sheet (area + total edge length, NO volume); `"face"` for its planar face;
    /// `"edge"` for a boundary edge. Provenance is the sketch feature itself.
    fn sketch_info_json(
        &self,
        name: &str,
        kind: ObjectKind,
        solid: &crate::scene::SolidDisplay,
    ) -> String {
        let creating = serde_json::json!({
            "id": solid.name,
            "type": self.feature_type_of(&solid.name),
        });
        let edge_total: f64 = solid.edges.iter().map(|e| polyline_length(&e.polyline)).sum();
        match kind {
            ObjectKind::Solid => serde_json::json!({
                "ok": true,
                "name": name,
                "kind": "sketch",
                "area": sheet_mesh_area(solid),
                "edgeLengthTotal": edge_total,
                "creatingFeature": creating,
            })
            .to_string(),
            ObjectKind::Face => serde_json::json!({
                "ok": true,
                "name": name,
                "kind": "face",
                "solid": solid.name,
                "area": sheet_mesh_area(solid),
                "edgeLengthTotal": edge_total,
                "creatingFeature": creating,
            })
            .to_string(),
            ObjectKind::Edge => {
                let length = solid
                    .edges
                    .iter()
                    .find(|e| e.name == name)
                    .map(|e| polyline_length(&e.polyline))
                    .unwrap_or(0.0);
                serde_json::json!({
                    "ok": true,
                    "name": name,
                    "kind": "edge",
                    "solid": solid.name,
                    "length": length,
                    "creatingFeature": creating,
                })
                .to_string()
            }
        }
    }
}

/// Total surface area (mm²) of a synthesized sheet's planar display mesh — the
/// sum of its triangle areas.
fn sheet_mesh_area(solid: &crate::scene::SolidDisplay) -> f64 {
    let p = &solid.mesh.positions;
    solid
        .mesh
        .indices
        .chunks_exact(3)
        .map(|t| {
            let a = p[t[0] as usize];
            let b = p[t[1] as usize];
            let c = p[t[2] as usize];
            let ab = [
                (b[0] - a[0]) as f64,
                (b[1] - a[1]) as f64,
                (b[2] - a[2]) as f64,
            ];
            let ac = [
                (c[0] - a[0]) as f64,
                (c[1] - a[1]) as f64,
                (c[2] - a[2]) as f64,
            ];
            let cross = [
                ab[1] * ac[2] - ab[2] * ac[1],
                ab[2] * ac[0] - ab[0] * ac[2],
                ab[0] * ac[1] - ab[1] * ac[0],
            ];
            (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5
        })
        .sum()
}

/// Arc length (mm) of a sampled edge polyline — the sum of its segment lengths.
fn polyline_length(polyline: &[[f32; 3]]) -> f64 {
    polyline
        .windows(2)
        .map(|w| {
            let d = [
                (w[1][0] - w[0][0]) as f64,
                (w[1][1] - w[0][1]) as f64,
                (w[1][2] - w[0][2]) as f64,
            ];
            (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt()
        })
        .sum()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn cube_history(name: &str, side: f64) -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": name,
                    "sizeX": side, "sizeY": side, "sizeZ": side,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    /// The same 3-feature seed the app boots with: a 20 mm cube `Box`, a cylinder
    /// `Pin`, and `Cut` = SUBTRACT(Box, [Pin]). The SUBTRACT result reuses the
    /// target's name, so the final solid is `Box`, produced by the `Cut` feature.
    fn seed_history() -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [
                {
                    "type": "P.CU",
                    "inputParams": {
                        "id": "Box",
                        "sizeX": 20.0, "sizeY": 20.0, "sizeZ": 20.0,
                        "transform": {
                            "position": [0.0, 0.0, 0.0],
                            "rotationEuler": [0.0, 0.0, 0.0],
                            "scale": [1.0, 1.0, 1.0]
                        },
                        "boolean": { "targets": [], "operation": "NONE" }
                    },
                    "persistentData": {}
                },
                {
                    "type": "P.CY",
                    "inputParams": {
                        "id": "Pin",
                        "radius": 6.0, "height": 30.0,
                        "transform": {
                            "position": [10.0, -5.0, 10.0],
                            "rotationEuler": [0.0, 0.0, 0.0],
                            "scale": [1.0, 1.0, 1.0]
                        },
                        "boolean": { "targets": [], "operation": "NONE" }
                    },
                    "persistentData": {}
                },
                {
                    "type": "B",
                    "inputParams": {
                        "id": "Cut",
                        "targetSolid": "Box",
                        "boolean": { "operation": "SUBTRACT", "targets": ["Pin"] }
                    },
                    "persistentData": {}
                }
            ]
        })
        .to_string()
    }

    /// First named entity of a kind on the resident `Box` (cube entities are all
    /// named; any one works since a cube's edges/faces are congruent).
    fn first_named_face(engine: &EngineState) -> String {
        engine
            .scene
            .solid("Box")
            .unwrap()
            .faces
            .iter()
            .find(|face| !face.name.is_empty())
            .expect("a named face")
            .name
            .clone()
    }

    fn first_named_edge(engine: &EngineState) -> String {
        engine
            .scene
            .solid("Box")
            .unwrap()
            .edges
            .iter()
            .find(|edge| !edge.name.is_empty())
            .expect("a named edge")
            .name
            .clone()
    }

    #[test]
    fn metadata_set_get_remove_and_density() {
        let mut store = MetadataStore::new();
        assert!(store.is_empty());
        // Default density is unit density.
        assert_eq!(store.density("Box"), DEFAULT_DENSITY);

        store.set_attribute("Box", "material", "steel");
        store.set_attribute("Box", "density", "7.85");
        assert_eq!(store.attribute("Box", "material"), Some("steel"));
        assert_eq!(store.density("Box"), 7.85);
        // Record JSON carries both attributes.
        let record: Value = serde_json::from_str(&store.record_json("Box")).unwrap();
        assert_eq!(record["material"], "steel");
        assert_eq!(record["density"], "7.85");

        // Empty name / key are ignored (no phantom records).
        store.set_attribute("", "k", "v");
        store.set_attribute("Box", "", "v");
        assert_eq!(store.all().len(), 1);

        // Remove one attribute; the record survives.
        assert!(store.remove_attribute("Box", "material"));
        assert_eq!(store.attribute("Box", "material"), None);
        assert!(!store.is_empty());
        // Removing an absent attribute reports false.
        assert!(!store.remove_attribute("Box", "material"));
        // Removing the last attribute drops the whole record.
        assert!(store.remove_attribute("Box", "density"));
        assert!(store.is_empty());
    }

    #[test]
    fn metadata_round_trips_through_save_and_load() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_history("Box", 10.0)).unwrap();
        engine.set_metadata_attribute("Box", "material", "aluminium");
        engine.set_metadata_attribute("Box", "density", "2.7");

        // The engine metadata getter reflects the writes.
        let all: Value = serde_json::from_str(&engine.metadata_json()).unwrap();
        assert_eq!(all["Box"]["material"], "aluminium");

        // Persist → the document carries a top-level `metadata` field.
        let saved = engine.history_request_json();
        let document: Value = serde_json::from_str(&saved).unwrap();
        assert_eq!(document["metadata"]["Box"]["density"], "2.7");

        // Load into a FRESH engine → the store is restored.
        let mut reopened = EngineState::new();
        reopened.set_history_json(&saved).unwrap();
        assert_eq!(reopened.object_metadata_json("Box"), engine.object_metadata_json("Box"));
        assert_eq!(reopened.metadata.density("Box"), 2.7);

        // Loading a document with NO metadata clears the store wholesale.
        reopened.set_history_json(&cube_history("Box", 10.0)).unwrap();
        assert!(reopened.metadata.is_empty());
        assert_eq!(reopened.object_metadata_json("Box"), "{}");
    }

    #[test]
    fn unannotated_model_persists_without_metadata_field() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_history("Box", 10.0)).unwrap();
        let document: Value = serde_json::from_str(&engine.history_request_json()).unwrap();
        assert!(document.get("metadata").is_none());
    }

    #[test]
    fn edge_length_of_cube_edge_equals_side() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_history("Box", 10.0)).unwrap();
        let edge = first_named_edge(&engine);
        let info: Value = serde_json::from_str(&engine.object_info_json(&edge)).unwrap();
        assert_eq!(info["ok"], true);
        assert_eq!(info["kind"], "edge");
        assert_eq!(info["solid"], "Box");
        assert!(
            (info["length"].as_f64().unwrap() - 10.0).abs() < 1e-6,
            "edge length {} != side 10",
            info["length"]
        );
    }

    #[test]
    fn face_area_and_boundary_of_cube_face() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_history("Box", 10.0)).unwrap();
        let face = first_named_face(&engine);
        let info: Value = serde_json::from_str(&engine.object_info_json(&face)).unwrap();
        assert_eq!(info["ok"], true);
        assert_eq!(info["kind"], "face");
        // A 10 mm cube face: area 100, boundary = 4 edges · 10 = 40.
        assert!((info["area"].as_f64().unwrap() - 100.0).abs() < 1e-6);
        assert!((info["edgeLengthTotal"].as_f64().unwrap() - 40.0).abs() < 1e-6);
    }

    #[test]
    fn solid_measurements_and_weight_with_density() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_history("Box", 10.0)).unwrap();

        // Default density → weight == volume.
        let info: Value = serde_json::from_str(&engine.object_info_json("Box")).unwrap();
        assert_eq!(info["ok"], true);
        assert_eq!(info["kind"], "solid");
        assert!((info["volume"].as_f64().unwrap() - 1000.0).abs() < 1e-6);
        assert!((info["surfaceArea"].as_f64().unwrap() - 600.0).abs() < 1e-6);
        assert!((info["edgeLengthTotal"].as_f64().unwrap() - 120.0).abs() < 1e-6);
        assert!((info["density"].as_f64().unwrap() - 1.0).abs() < 1e-12);
        assert!((info["weight"].as_f64().unwrap() - 1000.0).abs() < 1e-6);

        // Density 2 → weight == 2 · volume.
        engine.set_metadata_attribute("Box", "density", "2");
        let heavy: Value = serde_json::from_str(&engine.object_info_json("Box")).unwrap();
        assert!((heavy["density"].as_f64().unwrap() - 2.0).abs() < 1e-12);
        assert!((heavy["weight"].as_f64().unwrap() - 2000.0).abs() < 1e-6);
    }

    #[test]
    fn creating_feature_of_seed_box_and_cut() {
        let mut engine = EngineState::new();
        engine.set_history_json(&seed_history()).unwrap();

        // The full seed leaves one solid, `Box`, produced by the `Cut` boolean.
        let info: Value = serde_json::from_str(&engine.object_info_json("Box")).unwrap();
        assert_eq!(info["creatingFeature"]["id"], "Cut");
        assert_eq!(info["creatingFeature"]["type"], "B");
        // The standalone provenance accessor agrees.
        assert_eq!(
            engine.creating_feature("Box"),
            Some(("Cut".to_string(), "B".to_string()))
        );

        // Rolled back to step 0, `Box` is the plain cube produced by its own P.CU.
        engine.roll_to(0);
        let seed: Value = serde_json::from_str(&engine.object_info_json("Box")).unwrap();
        assert_eq!(seed["creatingFeature"]["id"], "Box");
        assert_eq!(seed["creatingFeature"]["type"], "P.CU");
    }

    #[test]
    fn unknown_object_reports_not_ok() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_history("Box", 10.0)).unwrap();
        let info: Value = serde_json::from_str(&engine.object_info_json("Nope")).unwrap();
        assert_eq!(info["ok"], false);
        assert!(engine.creating_feature("Nope").is_none());
    }
}