BREP_render 0.4.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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
//! [`History`] — the engine-owned, editable model recipe: the ordered feature
//! history plus the rollback index (the feature the model is currently built up
//! to). This is the SINGLE SOURCE OF TRUTH for the model — the UI keeps NO copy;
//! it mutates and reads the history only through [`crate::engine_state::EngineState`]
//! methods. That keeps one engine-owned history (UI-agnostic) and converges with
//! the in-flight "whole history in Rust" pipeline migration — later this sinks
//! into `brep-kernel-rs` proper without touching the UI.
//!
//! Rolling to a step re-runs `features[0..=rollback]` through the SAME kernel
//! pipeline: the full feature list stays in the request and `stopAtId` (the
//! editor's "stop at the expanded feature") halts execution AFTER the rolled-to
//! feature, so the kernel's incremental history cache is RETAINED across rolls
//! (no thrash) and the viewport shows the model as of that step.

use serde_json::Value;

/// The cap on the undo (and redo) stack depth — old entries fall off the bottom.
const MAX_UNDO: usize = 100;

/// A restorable model state: the whole document PLUS the rolled-to step, captured
/// together so an undo returns both the geometry and the view to the state they
/// were in right before the mutation.
#[derive(Debug, Clone)]
struct Snapshot {
    request: Value,
    rollback: usize,
    /// The parts-library block as it stood before the mutation. An `Rc`, so
    /// capturing it costs a pointer bump however large the library is — undo
    /// and redo still rewind it exactly as they did when it lived inside
    /// `request` (a redo of a component insert must restore the entry its
    /// ACOMP references).
    parts_library: std::rc::Rc<Value>,
}

/// The engine-owned mutable history.
#[derive(Debug, Clone)]
pub struct History {
    /// The whole `HistoryRequest` document
    /// (`{expressions, configurator, features: [...]}`).
    request: Value,
    /// Index into `features` the model is rolled to (clamped to the last).
    rollback: usize,
    /// Undo/redo over the MODEL document. A snapshot is pushed BEFORE each model
    /// mutation (edit / add / delete / reorder); roll-to-step is view state and
    /// is NOT snapshotted. Rapid same-target edits (a slider drag) coalesce into a
    /// single undo entry via `last_edit_key`. The stacks live here in the engine
    /// core — the model is engine-owned, so its undo history is too; the UI only
    /// triggers `undo()` / `redo()`.
    undo_stack: Vec<Snapshot>,
    redo_stack: Vec<Snapshot>,
    /// The coalescing token of the most recently recorded edit (see `checkpoint`).
    last_edit_key: Option<String>,
    /// The persistent GLOBAL feature counter: bumped by one on every new-feature
    /// mint ([`Self::next_feature_id`]), so a new id is `{shortName}{counter}`.
    /// MONOTONIC and NEVER reused — deleting a feature does not free its number,
    /// and (deliberately) undo does NOT rewind it, so re-doing an add can't collide
    /// with a number already handed out. It is kept OFF `self.request` in memory
    /// (so the undo snapshots that clone `request` never rewind it) and folded into
    /// the serialized document under `"featureCounter"` so it round-trips save/load
    /// (see [`Self::request_json`] / [`Self::from_request_json`]).
    feature_counter: u64,
    /// The assemblies PARTS LIBRARY block (`partsLibrary`, spec §2.1), kept OFF
    /// `self.request` for the same reason as `feature_counter`: every per-edit
    /// pass over the document — the undo checkpoint clone, the kernel request
    /// built by [`Self::prefix_request`], the assembly pose fold's serialize →
    /// parse round trip — would otherwise copy the whole library, which for an
    /// imported STEP assembly is megabytes of embedded part payload PER EDIT
    /// and froze the browser UI. Folded back in by [`Self::request_json`] so
    /// the SAVED document is byte-identical to before, and lifted back out by
    /// [`Self::from_request_json`] / the adopt doors.
    ///
    /// `Rc` because undo/redo MUST rewind it (a redo of a component insert has
    /// to restore the entry its ACOMP references) while a checkpoint must stay
    /// a pointer copy — the whole point of moving it off `request`.
    parts_library: std::rc::Rc<Value>,
    /// Whether `parts_library` is known to MIRROR the kernel store — i.e. it
    /// was written by [`Self::set_parts_library`] from `parts_library_json()`.
    /// False after a load, an adopt, or an undo/redo restore, any of which can
    /// install a block that predates the store's heals and GC.
    ///
    /// The engine's assembly sync re-reads the store only when this is false or
    /// the store's revision moved; serializing the store costs the whole
    /// embedded part payload, so doing it once per edit is exactly the cost
    /// this change exists to remove — but skipping it when the block is NOT a
    /// mirror would save a stale library.
    parts_library_mirrors_store: bool,
}

impl Default for History {
    fn default() -> Self {
        Self {
            request: empty_request(),
            rollback: 0,
            undo_stack: Vec::new(),
            redo_stack: Vec::new(),
            last_edit_key: None,
            feature_counter: 0,
            parts_library: std::rc::Rc::new(Value::Null),
            parts_library_mirrors_store: false,
        }
    }
}

fn empty_request() -> Value {
    serde_json::json!({ "expressions": "", "configurator": {}, "features": [] })
}

/// The trailing run of ASCII digits of `id` read as a number (`"P.CU12"` → 12,
/// `"Box"` → 0). Trailing digits are ASCII (one byte each), so the slice boundary
/// is always a valid char boundary; a missing/overflowing run yields 0.
fn trailing_number(id: &str) -> u64 {
    let digit_bytes = id
        .bytes()
        .rev()
        .take_while(u8::is_ascii_digit)
        .count();
    id[id.len() - digit_bytes..].parse().unwrap_or(0)
}

impl History {
    /// Load a whole history document (a saved part file parses as one). Rolls to
    /// the last feature. Ensures a `features` array exists.
    pub fn from_request_json(json: &str) -> Result<Self, String> {
        let mut request: Value =
            serde_json::from_str(json).map_err(|e| format!("history parse: {e}"))?;
        if !request.get("features").map(Value::is_array).unwrap_or(false) {
            if let Some(obj) = request.as_object_mut() {
                obj.insert("features".into(), Value::Array(Vec::new()));
            } else {
                request = empty_request();
            }
        }
        // Lift the persistent feature counter OUT of the document so it lives ONLY
        // in the struct field: kept off `self.request`, the undo snapshots (which
        // clone `request`) can never rewind it, and it can't be double-folded on
        // re-serialize. A document with no stored counter (fresh or saved before
        // this field existed) safe-inits below.
        let stored = request
            .as_object_mut()
            .and_then(|obj| obj.remove("featureCounter"))
            .and_then(|value| value.as_u64());
        // Lift the parts-library block out of the document for the same reason
        // (see the `parts_library` field): every per-edit copy of `request`
        // would otherwise carry megabytes of embedded part payload.
        let parts_library = request
            .as_object_mut()
            .and_then(|obj| obj.remove("partsLibrary"))
            .unwrap_or(Value::Null);
        let mut history = Self {
            request,
            rollback: 0,
            parts_library: std::rc::Rc::new(parts_library),
            ..Self::default()
        };
        history.rollback = history.len().saturating_sub(1);
        // Safe init when unstored: start ABOVE the largest numeric suffix already
        // present among feature ids so the next mint (`{shortName}{counter+1}`)
        // cannot collide with an existing id. This holds because no shortName ends
        // in a digit (verified — even `IMPORT3D` ends in `D`), so an id's trailing
        // digits ARE its numeric suffix and `counter+1` strictly exceeds them all.
        history.feature_counter = stored.unwrap_or_else(|| history.max_id_suffix());
        Ok(history)
    }

    /// The largest trailing-integer suffix among all existing feature ids (0 when
    /// none carry one) — the floor for a safe counter init on a document with no
    /// stored `featureCounter` (see [`Self::from_request_json`]).
    fn max_id_suffix(&self) -> u64 {
        self.features()
            .iter()
            .filter_map(|f| {
                f.get("inputParams")
                    .and_then(|p| p.get("id"))
                    .and_then(Value::as_str)
            })
            .map(trailing_number)
            .max()
            .unwrap_or(0)
    }

    /// The features slice (empty if none).
    pub fn features(&self) -> &[Value] {
        self.request
            .get("features")
            .and_then(Value::as_array)
            .map(Vec::as_slice)
            .unwrap_or(&[])
    }

    fn features_mut(&mut self) -> &mut Vec<Value> {
        let obj = self
            .request
            .as_object_mut()
            .expect("history request is a JSON object");
        obj.entry("features")
            .or_insert_with(|| Value::Array(Vec::new()));
        obj.get_mut("features")
            .and_then(Value::as_array_mut)
            .expect("features is a JSON array")
    }

    pub fn len(&self) -> usize {
        self.features().len()
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// The rolled-to index, clamped to a valid feature (0 when empty).
    pub fn rollback(&self) -> usize {
        self.rollback.min(self.len().saturating_sub(1))
    }

    pub fn set_rollback(&mut self, index: usize) {
        self.rollback = if self.is_empty() {
            0
        } else {
            index.min(self.len() - 1)
        };
        // Rolling to a step is a view move, not a model edit: it records NO undo
        // snapshot, but it DOES break the edit-coalescing run so the next edit
        // starts a fresh undo entry rather than merging with a pre-roll edit.
        self.last_edit_key = None;
    }

    pub fn feature_type(&self, index: usize) -> Option<String> {
        self.features()
            .get(index)?
            .get("type")
            .and_then(Value::as_str)
            .map(String::from)
    }

    pub fn feature_id(&self, index: usize) -> Option<String> {
        self.features()
            .get(index)?
            .get("inputParams")
            .and_then(|p| p.get("id"))
            .and_then(Value::as_str)
            .map(String::from)
    }

    pub fn index_of(&self, id: &str) -> Option<usize> {
        self.features().iter().position(|f| {
            f.get("inputParams")
                .and_then(|p| p.get("id"))
                .and_then(Value::as_str)
                == Some(id)
        })
    }

    /// The `inputParams` document of the feature at `index` (for the dialog).
    pub fn feature_params(&self, index: usize) -> Option<Value> {
        self.features().get(index)?.get("inputParams").cloned()
    }

    /// SOLVER write-back fold (the assembly pose-authority contract): set ONE
    /// `inputParams` key of the feature whose `inputParams.id == id`, WITHOUT an
    /// undo checkpoint and WITHOUT breaking edit coalescing — a solve write-back
    /// is the kernel adopting its own result, not a user edit, so it must never
    /// mint an undo entry (undoing a user action then re-running re-solves and
    /// re-folds anyway). Returns whether a feature matched.
    pub fn fold_param_no_undo(&mut self, id: &str, key: &str, value: Value) -> bool {
        let Some(index) = self.index_of(id) else {
            return false;
        };
        if let Some(feature) = self.features_mut().get_mut(index) {
            if let Some(params) = feature
                .get_mut("inputParams")
                .and_then(Value::as_object_mut)
            {
                params.insert(key.to_string(), value);
                return true;
            }
        }
        false
    }

    pub fn set_feature_params(&mut self, index: usize, params: Value) {
        if index >= self.len() {
            return;
        }
        // Coalesce a slider drag (many consecutive edits of the SAME feature) into
        // one undo entry, keyed by the feature index.
        self.checkpoint(Some(&format!("param:{index}")));
        if let Some(feat) = self.features_mut().get_mut(index) {
            if let Some(obj) = feat.as_object_mut() {
                obj.insert("inputParams".into(), params);
            }
        }
    }

    /// Replace the `inputParams` of MANY features as ONE mutation —
    /// [`Self::set_feature_params`]'s batch sibling, and the reason it exists:
    /// a packed BOM row rolls up N occurrences, so editing one cell writes N
    /// features. A `set_feature_params` loop would mint N undo entries (each
    /// keyed `param:{index}`, so none of them coalesce with each other), and
    /// the user would have to press undo N times to take back ONE edit.
    ///
    /// Exactly ONE checkpoint covers the whole batch. The coalesce key names
    /// the SET of indices, so a run of edits to the SAME set (typing into one
    /// packed cell) still merges into a single entry, while switching to a
    /// different set starts a new one — the `param:{index}` rule, lifted to a
    /// group. Out-of-range indices are skipped; an empty batch is a no-op (no
    /// checkpoint, so a fan-out that matched nothing leaves no empty entry).
    pub fn set_many_feature_params(&mut self, edits: &[(usize, Value)]) {
        let len = self.len();
        let mut in_range: Vec<&(usize, Value)> =
            edits.iter().filter(|(index, _)| *index < len).collect();
        if in_range.is_empty() {
            return;
        }
        // The key must not depend on the caller's ordering, or the same packed
        // row could produce two different keys and stop coalescing.
        in_range.sort_by_key(|(index, _)| *index);
        let key: Vec<String> = in_range
            .iter()
            .map(|(index, _)| index.to_string())
            .collect();
        self.checkpoint(Some(&format!("params:{}", key.join(","))));
        for (index, params) in in_range {
            if let Some(feature) = self.features_mut().get_mut(*index) {
                if let Some(object) = feature.as_object_mut() {
                    object.insert("inputParams".into(), params.clone());
                }
            }
        }
    }

    pub fn push_feature(&mut self, feature: Value) {
        self.checkpoint(None);
        self.features_mut().push(feature);
    }

    /// Append MANY features as ONE mutation — the batch an import lane needs
    /// (`EngineState::add_features`). Distinct from a `push_feature` loop in the
    /// two ways that matter: exactly ONE undo checkpoint (an N-instance assembly
    /// import undoes in one step, not N), and the caller re-runs once instead of
    /// once per feature. No-op for an empty batch (no checkpoint, so an import
    /// that produced nothing leaves no empty undo entry).
    pub fn push_features(&mut self, features: Vec<Value>) {
        if features.is_empty() {
            return;
        }
        self.checkpoint(None);
        self.features_mut().extend(features);
    }

    pub fn remove_feature(&mut self, index: usize) {
        if index >= self.len() {
            return;
        }
        self.checkpoint(None);
        self.features_mut().remove(index);
    }

    pub fn swap(&mut self, a: usize, b: usize) {
        let len = self.len();
        if a < len && b < len && a != b {
            self.checkpoint(None);
            self.features_mut().swap(a, b);
        }
    }

    /// Mint the id for a NEW feature: `{base}{N}` where `base` is the feature's
    /// shortName and `N` is this history's persistent GLOBAL counter, bumped by one
    /// on every mint (`P.CU` → `P.CU7`, `S` → `S8`). GLOBAL across all feature
    /// types, MONOTONIC, and NEVER reused — a delete does not free a number and
    /// undo does not rewind the counter — and it persists across save/load, so two
    /// features can never receive the same id over the document's whole lifetime.
    pub fn next_feature_id(&mut self, base: &str) -> String {
        self.feature_counter += 1;
        format!("{base}{}", self.feature_counter)
    }

    /// The `stopAtId`-truncated request that stops AFTER the rolled-to feature —
    /// the roll-to-step request the pipeline runs. Empty history → empty request.
    pub fn prefix_request(&self) -> Value {
        let mut request = self.request.clone();
        if let Some(id) = self.feature_id(self.rollback()) {
            if let Some(obj) = request.as_object_mut() {
                obj.insert("stopAtId".into(), Value::String(id));
            }
        }
        request
    }

    /// The tree listing for the UI: `{ step, features: [{index, type, id}] }`.
    pub fn listing_json(&self) -> String {
        let features: Vec<Value> = self
            .features()
            .iter()
            .enumerate()
            .map(|(index, _)| {
                serde_json::json!({
                    "index": index,
                    "type": self.feature_type(index).unwrap_or_else(|| "?".into()),
                    "id": self.feature_id(index).unwrap_or_else(|| "(no id)".into()),
                })
            })
            .collect();
        serde_json::json!({ "step": self.rollback(), "features": features }).to_string()
    }

    /// The whole request document (for persistence / debugging), with the
    /// persistent global feature counter folded back in under `"featureCounter"`
    /// so it round-trips through save/load (the twin of [`Self::from_request_json`],
    /// which lifts it back out). Written only when non-zero, so a document that has
    /// never minted a feature persists byte-for-byte as before (mirrors the
    /// metadata field's "un-annotated model persists unchanged" convention).
    pub fn request_json(&self) -> String {
        let has_library = self
            .parts_library
            .as_object()
            .map(|map| !map.is_empty())
            .unwrap_or(false);
        if self.feature_counter == 0 && !has_library {
            return self.request.to_string();
        }
        let mut document = self.request.clone();
        if let Some(obj) = document.as_object_mut() {
            if self.feature_counter != 0 {
                obj.insert("featureCounter".into(), Value::from(self.feature_counter));
            }
            if has_library {
                obj.insert("partsLibrary".into(), (*self.parts_library).clone());
            }
        }
        document.to_string()
    }

    /// The document WITHOUT the parts-library block — for the kernel round
    /// trips that never read it. The assembly pose fold
    /// (`assembly_apply_document_json`) only rewrites the `assembly` block and
    /// per-feature `inputParams`, so handing it the library would serialize,
    /// parse and re-serialize megabytes of part payload on every edit for
    /// nothing. [`Self::request_json`] is the SAVE door and still carries it.
    pub fn request_json_without_parts_library(&self) -> String {
        if self.feature_counter == 0 {
            return self.request.to_string();
        }
        let mut document = self.request.clone();
        if let Some(obj) = document.as_object_mut() {
            obj.insert("featureCounter".into(), Value::from(self.feature_counter));
        }
        document.to_string()
    }

    /// ADOPT a kernel-folded document (the assembly pose-authority write-back:
    /// `assembly_apply_document_json` returned this document with the solved
    /// `assembly` block + poses/isFixed folded onto the owning features).
    /// Replaces the request WHOLESALE while keeping the rollback index (clamped),
    /// the undo/redo stacks, and the live feature counter — a solver write-back
    /// is not a user edit, so no undo checkpoint is pushed (the constraint edit
    /// that triggered the solve lives in the kernel session's state, outside the
    /// engine undo lane — flagged for the integrator).
    pub fn adopt_folded_request(&mut self, json: &str) -> Result<(), String> {
        let mut value: Value = serde_json::from_str(json)
            .map_err(|error| format!("folded document parse: {error}"))?;
        let Some(object) = value.as_object_mut() else {
            return Err("folded document must be an object".to_string());
        };
        // `request_json` serialized the live counter into the document we handed
        // the fold; the in-memory counter stays authoritative, so strip the echo
        // (it is re-folded on the next serialize).
        object.remove("featureCounter");
        // As in `adopt_document`: present replaces, absent keeps.
        let adopted_library = object.remove("partsLibrary");
        if !object.contains_key("features") {
            object.insert("features".into(), Value::Array(Vec::new()));
        }
        self.request = value;
        if let Some(library) = adopted_library {
            self.set_parts_library(library);
            self.parts_library_mirrors_store = false;
        }
        let last = self.len().saturating_sub(1);
        self.rollback = self.rollback.min(last);
        Ok(())
    }

    // --- Undo / redo over the model document ------------------------------

    fn snapshot(&self) -> Snapshot {
        Snapshot {
            request: self.request.clone(),
            rollback: self.rollback,
            parts_library: self.parts_library.clone(),
        }
    }

    fn restore(&mut self, snap: Snapshot) {
        self.request = snap.request;
        self.parts_library = snap.parts_library;
        self.parts_library_mirrors_store = false;
        let last = self.len().saturating_sub(1);
        self.rollback = snap.rollback.min(last);
    }

    /// Record a pre-mutation snapshot for undo. `coalesce_key` groups a run of
    /// rapid same-target edits (one slider drag) into a SINGLE undo entry: while
    /// the same non-empty key repeats, no new snapshot is pushed. A `None` key
    /// never coalesces, so every structural add/delete/reorder is its own entry.
    /// Any new snapshot clears the redo stack (a fresh edit forks the timeline)
    /// and the oldest entry falls off once the stack passes [`MAX_UNDO`].
    fn checkpoint(&mut self, coalesce_key: Option<&str>) {
        if coalesce_key.is_some() && coalesce_key == self.last_edit_key.as_deref() {
            return;
        }
        self.undo_stack.push(self.snapshot());
        if self.undo_stack.len() > MAX_UNDO {
            self.undo_stack.remove(0);
        }
        self.redo_stack.clear();
        self.last_edit_key = coalesce_key.map(str::to_string);
    }

    /// Whether an undo step is available (for enabling the toolbar button).
    pub fn can_undo(&self) -> bool {
        !self.undo_stack.is_empty()
    }

    /// Whether a redo step is available.
    pub fn can_redo(&self) -> bool {
        !self.redo_stack.is_empty()
    }

    /// Undo the last model mutation: push the current state onto the redo stack
    /// and restore the previous document + rolled-to step. Returns whether it
    /// changed anything (false when the undo stack is empty).
    pub fn undo(&mut self) -> bool {
        let Some(prev) = self.undo_stack.pop() else {
            return false;
        };
        self.redo_stack.push(self.snapshot());
        self.restore(prev);
        // A distinct undo breaks any coalescing run so the next edit is fresh.
        self.last_edit_key = None;
        true
    }

    /// Redo the last undone model mutation (symmetric with [`Self::undo`]).
    pub fn redo(&mut self) -> bool {
        let Some(next) = self.redo_stack.pop() else {
            return false;
        };
        self.undo_stack.push(self.snapshot());
        self.restore(next);
        self.last_edit_key = None;
        true
    }
}

// ============================================================================
// Assembly document accessors (appended — the assemblies Wave-3 slice). A
// SEPARATE `impl` block so concurrent edits to the primary block don't
// conflict; purely additive over the existing history API.
// ============================================================================
impl History {
    /// ADOPT a whole replacement document — the assembly FOLD's write-back lane
    /// (`assembly_apply_document_json` returns the document with the solved
    /// `assembly` block + poses/isFixed folded into the features; the engine
    /// adopts it before persisting or re-running — the pose-authority contract).
    ///
    /// `checkpoint` chooses the undo semantics: a USER constraint mutation
    /// records an undo snapshot (so constraint edits stay undoable like any
    /// model edit); the silent post-run pose fold passes `false` (solver
    /// write-back is not a user edit — undoing the user's LAST edit must not
    /// strand an extra fold step in between).
    ///
    /// A stray `featureCounter` in the adopted document is stripped (the
    /// in-memory counter stays authoritative — `request_json` re-folds it on
    /// serialize, exactly like `from_request_json` lifts it on load). The
    /// rollback index is preserved (the fold never changes the feature count).
    pub fn adopt_document(&mut self, document_json: &str) -> Result<(), String> {
        let mut document: Value = serde_json::from_str(document_json)
            .map_err(|error| format!("adopt document parse: {error}"))?;
        if !document.is_object() {
            return Err("adopt document: not a JSON object".into());
        }
        let mut adopted_library = None;
        if let Some(obj) = document.as_object_mut() {
            obj.remove("featureCounter");
            // A block PRESENT in the adopted document replaces the field; one
            // ABSENT leaves it alone (the fold lane is handed a library-free
            // document by `request_json_without_parts_library` and must not
            // silently drop the library on the way back).
            adopted_library = obj.remove("partsLibrary");
            if !obj.get("features").map(Value::is_array).unwrap_or(false) {
                obj.insert("features".into(), Value::Array(Vec::new()));
            }
        }
        self.request = document;
        if let Some(library) = adopted_library {
            self.set_parts_library(library);
            self.parts_library_mirrors_store = false;
        }
        Ok(())
    }

    /// Same adoption with an undo snapshot recorded FIRST (never coalesced) —
    /// the user-mutation twin of [`Self::adopt_document`].
    pub fn adopt_document_checkpointed(&mut self, document_json: &str) -> Result<(), String> {
        // Validate BEFORE snapshotting so a parse failure never pushes a
        // phantom undo entry.
        let probe: Value = serde_json::from_str(document_json)
            .map_err(|error| format!("adopt document parse: {error}"))?;
        if !probe.is_object() {
            return Err("adopt document: not a JSON object".into());
        }
        self.checkpoint(None);
        self.adopt_document(document_json)
    }

    /// Replace the document's `partsLibrary` block (the assemblies parts
    /// library, spec §2.1) — the caller feeds `brep_kernel::parts_library_json()`
    /// here (never an echo of a loaded block), so SAVE serializes the kernel
    /// store with its heals and GC. An empty map clears the field, so a
    /// non-assembly document serializes byte-identically to before.
    ///
    /// The block is held in the `parts_library` FIELD rather than on
    /// `self.request`; [`Self::request_json`] folds it back into the saved
    /// document. The on-disk shape is unchanged.
    pub fn set_parts_library(&mut self, library: Value) {
        let empty = library.as_object().map(|m| m.is_empty()).unwrap_or(true);
        self.parts_library = std::rc::Rc::new(if empty { Value::Null } else { library });
        self.parts_library_mirrors_store = true;
    }

    /// Replace the `partsLibrary` block as a USER EDIT: one undo checkpoint,
    /// and the mirror flag CLEARED so the next run ships the block to the
    /// runner instead of assuming the kernel store already agrees.
    ///
    /// [`Self::set_parts_library`] is the other door and means the opposite —
    /// "this block came OUT of the kernel store" — so it must not be reused
    /// here: a part-attribute edit is authored on this side and the runner has
    /// never seen it. `coalesce_key` follows the `param:{index}` rule so a run
    /// of keystrokes into one attribute is one undo entry.
    pub fn set_parts_library_edited(&mut self, library: Value, coalesce_key: Option<&str>) {
        self.checkpoint(coalesce_key);
        let empty = library.as_object().map(|m| m.is_empty()).unwrap_or(true);
        self.parts_library = std::rc::Rc::new(if empty { Value::Null } else { library });
        self.parts_library_mirrors_store = false;
    }

    /// Whether the `partsLibrary` block currently mirrors the kernel store
    /// (see `parts_library_mirrors_store`).
    pub fn parts_library_mirrors_store(&self) -> bool {
        self.parts_library_mirrors_store
    }

    /// The `partsLibrary` block (`Value::Null` when the document has none).
    pub fn parts_library(&self) -> &Value {
        &self.parts_library
    }

    /// The document's `assembly` block (`{constraints, idCounter}`), if any.
    pub fn assembly_block(&self) -> Option<&Value> {
        self.request.get("assembly")
    }

    /// The document's `wireHarness` block (`{connections, idCounter,
    /// buildBundles}`), if any.
    pub fn wire_harness_block(&self) -> Option<&Value> {
        self.request.get("wireHarness")
    }

    /// Replace (or, with `None`, remove) the `wireHarness` block. A USER edit:
    /// snapshotted for undo, never coalesced — each add / edit / remove of a
    /// connection is its own undo step, like a feature add or delete.
    pub fn set_wire_harness_block(&mut self, block: Option<Value>) {
        self.checkpoint(None);
        if let Some(object) = self.request.as_object_mut() {
            match block {
                Some(block) => {
                    object.insert("wireHarness".into(), block);
                }
                None => {
                    object.remove("wireHarness");
                }
            }
        }
    }
}

// ============================================================================
// PMI block accessors (the PMI workbench slice). A SEPARATE `impl` block —
// purely additive over the history API.
// ============================================================================
impl History {
    /// The document's `pmi` block (`{views, idCounter}`), if any.
    pub fn pmi_block(&self) -> Option<&Value> {
        self.request.get("pmi")
    }

    /// Replace (or, with `None`, remove) the `pmi` block as a USER edit:
    /// snapshotted for undo. `coalesce_key` groups a run of rapid same-target
    /// edits (a label drag: `pmi:label:{id}`) into ONE undo entry; `None`
    /// makes the edit its own step (a view capture, an annotation add / edit
    /// / delete).
    pub fn set_pmi_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
        self.checkpoint(coalesce_key);
        self.put_pmi_block(block);
    }

    /// Replace the `pmi` block WITHOUT an undo checkpoint — for a write that
    /// belongs to the checkpoint just taken (an import lifting a file's PMI
    /// beside the feature it added, so one undo removes both).
    pub fn set_pmi_block_no_undo(&mut self, block: Option<Value>) {
        self.put_pmi_block(block);
    }

    fn put_pmi_block(&mut self, block: Option<Value>) {
        if let Some(object) = self.request.as_object_mut() {
            match block {
                Some(block) => {
                    object.insert("pmi".into(), block);
                }
                None => {
                    object.remove("pmi");
                }
            }
        }
    }

    /// End a coalescing run (a label drag released): the next edit with the
    /// same key starts a fresh undo entry.
    pub fn break_coalescing(&mut self) {
        self.last_edit_key = None;
    }
}

// ============================================================================
// PART ATTRIBUTES block accessors — the BOM attributes of the document ITSELF.
//
// `partAttributes` is a top-level document key (see
// `engine_state::bom`'s attributes block), so a document carries the BOM data
// of the PART it is. On a part in an assembly's library that record is written
// through the library entry's embedded document; on the document you have OPEN
// it is written here, by the toolbar's Properties dialog. Same key, same
// shape, two doors — which is what makes a part's Part Number the same value
// whether it is read from the assembly's BOM or from the part's own tab.
// ============================================================================
impl History {
    /// The document's own `partAttributes` record, if any.
    pub fn part_attributes_block(&self) -> Option<&Value> {
        self.request.get(crate::engine_state::PART_ATTRIBUTES)
    }

    /// Replace (or, with `None`, remove) the document's own `partAttributes`
    /// record as a USER edit: snapshotted for undo. `coalesce_key` groups a run
    /// of edits to ONE field (a typing run in the Properties dialog) into a
    /// single undo entry, exactly as the PMI block's does.
    pub fn set_part_attributes_block(&mut self, block: Option<Value>, coalesce_key: Option<&str>) {
        self.checkpoint(coalesce_key);
        if let Some(object) = self.request.as_object_mut() {
            match block {
                Some(block) => {
                    object.insert(crate::engine_state::PART_ATTRIBUTES.into(), block);
                }
                None => {
                    object.remove(crate::engine_state::PART_ATTRIBUTES);
                }
            }
        }
    }
}

// ============================================================================
// Expressions / configurator accessors (appended — the expressions/parameters
// panel slice). A SEPARATE `impl` block so concurrent edits to the primary block
// don't conflict; purely additive over the existing history API.
//
// The history document carries an `expressions` source string — the variable
// sheet feature params evaluate against (a numeric param may be the string
// `"boxW"`, evaluated by the pipeline's shared expression env). The panel edits
// this and re-runs; the `configurator` object (typed named inputs) is exposed
// read-only for display.
// ============================================================================
impl History {
    /// The history document's `expressions` source string (empty when absent or
    /// stored as `null`). The panel's editor binds to this.
    pub fn expressions(&self) -> String {
        self.request
            .get("expressions")
            .and_then(Value::as_str)
            .unwrap_or("")
            .to_string()
    }

    /// Replace the `expressions` source string. Snapshotted for undo, coalescing a
    /// run of keystroke edits into ONE undo entry (like a slider drag) via the
    /// shared `"expressions"` coalesce key, so a distinct add/edit/roll starts a
    /// fresh entry. A no-op re-set (same text) still records under the same key.
    pub fn set_expressions(&mut self, expressions: &str) {
        self.checkpoint(Some("expressions"));
        if let Some(obj) = self.request.as_object_mut() {
            obj.insert(
                "expressions".into(),
                Value::String(expressions.to_string()),
            );
        }
    }

    /// The `configurator` object (typed named inputs), or `{}` when absent —
    /// read-only for the panel's display (deeper configurator editing deferred).
    pub fn configurator(&self) -> Value {
        self.request
            .get("configurator")
            .cloned()
            .unwrap_or_else(|| Value::Object(serde_json::Map::new()))
    }
}

// ============================================================================
// Feature `persistentData` accessors (appended — the engine-native sketch mode
// slice). A SEPARATE `impl` block (like the expressions accessors above) so
// concurrent edits don't conflict; purely additive over the primary history API.
//
// A feature's `persistentData` is the kernel-persisted, non-input state (a
// SKETCH feature stores its solved `{points, geometries, constraints}` under the
// `sketch` key and the plane `basis` there). Sketch mode reads that state on
// enter and writes the edited doc back on commit — mirroring how the ref-select
// slice reads/writes `inputParams` through `feature_params` / `set_feature_params`.
// ============================================================================
impl History {
    /// The `persistentData` document of the feature at `index` (`None` if the
    /// feature or the field is absent) — the read twin of [`Self::feature_params`].
    pub fn feature_persistent_data(&self, index: usize) -> Option<Value> {
        self.features().get(index)?.get("persistentData").cloned()
    }

    /// Set a single `key` inside the feature-at-`index`'s `persistentData` object,
    /// creating (or replacing a non-object) `persistentData` as needed. Snapshotted
    /// for undo (a structural edit — never coalesced), like an add/delete.
    pub fn set_feature_persistent_field(&mut self, index: usize, key: &str, value: Value) {
        self.set_feature_persistent_field_coalesced(index, key, value, None);
    }

    /// [`Self::set_feature_persistent_field`] with an optional COALESCE key: a
    /// run of same-key writes (a gizmo drag moving a spline anchor, frame after
    /// frame) records ONE undo entry, exactly as a slider drag on a param does.
    pub fn set_feature_persistent_field_coalesced(
        &mut self,
        index: usize,
        key: &str,
        value: Value,
        coalesce_key: Option<&str>,
    ) {
        if index >= self.len() {
            return;
        }
        self.checkpoint(coalesce_key);
        if let Some(feat) = self.features_mut().get_mut(index).and_then(Value::as_object_mut) {
            let entry = feat
                .entry("persistentData")
                .or_insert_with(|| Value::Object(serde_json::Map::new()));
            if !entry.is_object() {
                *entry = Value::Object(serde_json::Map::new());
            }
            if let Some(obj) = entry.as_object_mut() {
                obj.insert(key.to_string(), value);
            }
        }
    }
}

// BREP private tests: 52cc072226360e97